Catalog
SAIU R20 1 6 The first 1 page
The first 1 Chapter . First time to know STM32...................................................................................................................... 1
1.1. Preview before class ........................................................................................................................................... 1
1.2. summary .................................................................................................................................................... 1
1.3. What is? STM32....................................................................................................................................1
1.4. STM32 What can be done ............................................................................................................................... 2
1.5. STM32 How to choose .............................................................................................................................. 3
1.5.1. STM32 classification ................................................................................................................................. 3
1.5.2. STM32 Naming method ........................................................................................................................ 4
1.5.3. Choose the right one MCU...................................................................................................................... 4
1.5.4. PCB Where to proofing ..............................................................................................................................6
1.6. summary .................................................................................................................................................... 7
1.7. Practice after class ........................................................................................................................................... 7
The first 2 Chapter . STM32 The structure and composition of ...................................................................................................... 8
2.1. Preview before class ........................................................................................................................................... 8
2.2. summary .................................................................................................................................................... 8
2.3. What is a register .................................................................................................................................. 8
2.4. STM 32 What does it look like ..................................................................................................................................8
2.5. What's in the chip ............................................................................................................................10
2.5.1. ICode Bus .................................................................................................................................10
2.5.2. Drive unit ....................................................................................................................................10
2.5.3. Passive unit ....................................................................................................................................11
2.6. Memory mapping .....................................................................................................................................13
2.7. Register mapping .....................................................................................................................................14
2.7.1. STM32 Peripheral address mapping for .......................................................................................................... 15
2.7.2. Bus base address ................................................................................................................................15
2.7.3. Peripheral base address ................................................................................................................................15
2.7.4. Peripheral registers ................................................................................................................................16
2.8. C Language encapsulates registers ................................................................................................................16
2.8.1. Encapsulate bus and peripheral base address ........................................................................................................... 16
2.8.2. Encapsulation register list ....................................................................................................................... 17
2.9. Practice after class ......................................................................................................................................... 20
The first 3 Chapter . First time to know STM32 Standard library ..................................................................................................... 21
3.1. Preview before class ......................................................................................................................................... 21
3.2. summary .................................................................................................................................................. 21
3.3. The library catalog 、 File info ....................................................................................................................... 21
3.4. STM32F10x_StdPeriph_Driver Folder ..................................................................................24
3.5. The relationship between the files in the library ....................................................................................................................... 26
3.6. First knowledge of library functions .....................................................................................................................................28
Catalog
The first 2 page SAIUR201 6
Edited by Mr. Chen Dejin
3.7. Practice after class ......................................................................................................................................... 29
The first 4 Chapter . GPIO Use .................................................................................................................. 30
4.1. Preview before class ......................................................................................................................................... 30
4.2. summary .................................................................................................................................................. 30
4.3. GPIO brief introduction .......................................................................................................................................30
4.4. GPIO Block diagram analysis .............................................................................................................................. 31
4.4.1. Protection diode and upper 、 Pull down resistance ................................................................................................... 31
4.4.2. P-MOS Tube and N-MOS tube ......................................................................................................... 31
4.4.3. Output data register ....................................................................................................................... 33
4.4.4. Reuse function output ........................................................................................................................... 34
4.4.5. Input data register ....................................................................................................................... 34
4.4.6. Reuse function input ........................................................................................................................... 34
4.4.7. Analog input and output ........................................................................................................................... 34
4.5. GPIO Working mode .............................................................................................................................. 35
4.5.1. The input mode ( simulation / Floating space / Pull up / The drop-down )............................................................................................. 35
4.5.2. The output mode ( push-pull / Open a leak )................................................................................................................35
4.5.3. Reuse function ( push-pull / Open a leak )................................................................................................................35
4.6. Lighten up LED- Hardware design ...................................................................................................................... 37
4.7. Lighten up LED- Programming points ...................................................................................................................... 38
4.8. Lighten up LED- The code analysis ...................................................................................................................... 38
4.8.1. LED Lamp pin macro definition ...................................................................................................................38
4.8.2. control LED Macro definition of light on / off state ........................................................................................... 39
4.8.3. LED GPIO Initialization function ............................................................................................................ 40
4.8.4. The main function ........................................................................................................................................41
4.9. Lighten up LED- Download validation ...................................................................................................................... 42
4.10. Practice after class .......................................................................................................................................42
The first 5 Chapter . STM32 RCC The clock system .................................................................................................... 43
5.1. Preview before class ......................................................................................................................................... 43
5.2. summary .................................................................................................................................................. 43
5.3. RCC The main role — The clock part .......................................................................................................... 43
5.4. RCC Block diagram analysis — The clock part .......................................................................................................... 43
5.5. The system clock ......................................................................................................................................... 44
5.5.1. HSE High speed external clock signal ...........................................................................................................44
5.5.2. PLL Clock source ............................................................................................................................... 45
5.5.3. PLL The clock PLLCLK.................................................................................................................. 45
5.5.4. The system clock SYSCLK.................................................................................................................. 45
5.5.5. AHB Bus clock HCLK............................................................................................................. 45
5.5.6. APB2 Bus clock HCLK2..........................................................................................................45
Catalog
SAIU R20 1 6 The first 3 page
5.5.7. Bus clock HCLK1.....................................................................................................................46
5.6. Set the system clock library function ................................................................................................................... 46
5.7. Other clocks ......................................................................................................................................... 47
5.7.1. USB The clock ...................................................................................................................................47
5.7.2. Cortex The system clock ........................................................................................................................47
5.7.3. ADC The clock .................................................................................................................................. 48
5.7.4. RTC The clock 、 Independent watchdog clock .................................................................................................. 48
5.7.5. MCO Clock output ......................................................................................................................... 48
5.8. Configure the system clock experiment ....................................................................................................................... 48
5.8.1. Use HSE..................................................................................................................................48
5.8.2. Use HSI................................................................................................................................... 48
5.8.3. Hardware design ....................................................................................................................................49
5.8.4. software design ....................................................................................................................................49
5.8.5. Programming points ....................................................................................................................................49
5.8.6. The code analysis ....................................................................................................................................49
5.8.7. Download validation ....................................................................................................................................54
The first 6 Chapter . STM32 Interrupt Application Overview ................................................................................................... 55
6.1. Preview before class ......................................................................................................................................... 55
6.2. summary .................................................................................................................................................. 55
6.3. Exception types ......................................................................................................................................... 55
6.4. NVIC brief introduction .......................................................................................................................................56
6.5. NVIC Register Introduction ..........................................................................................................................56
6.6. NVIC Interrupt configuration firmware library .................................................................................................................57
6.7. Definition of priority ................................................................................................................................ 58
6.7.1. Priority definition ................................................................................................................................58
6.7.2. Priority groups ................................................................................................................................58
6.8. Interrupt programming ......................................................................................................................................... 59
6.9. Practice after class ......................................................................................................................................... 60
The first 7 Chapter . EXTI— External interrupt / Event controller ..................................................................................... 61
7.1. Preview before class ......................................................................................................................................... 61
7.2. summary .................................................................................................................................................. 61
7.3. EXTI brief introduction .......................................................................................................................................61
7.4. EXTI Functional block diagram .............................................................................................................................. 61
7.5. interrupt / Event line .................................................................................................................................. 63
7.6. EXTI Initialization structure details ............................................................................................................ 64
7.7. External interrupt control experiment ....................................................................................................................... 65
7.7.1. Hardware design ....................................................................................................................................65
7.7.2. software design ....................................................................................................................................65
Catalog
The first 4 page SAIUR201 6
Edited by Mr. Chen Dejin
7.7.3. Programming points ....................................................................................................................................65
7.7.4. The code analysis ....................................................................................................................................65
7.7.5. Download validation ....................................................................................................................................69
7.8. Practice after class ......................................................................................................................................... 69
The first 8 Chapter . SysTick System timer .................................................................................................... 70
8.1. Preview before class ......................................................................................................................................... 70
8.2. summary .................................................................................................................................................. 70
8.3. SysTick brief introduction ................................................................................................................................ 70
8.4. SysTick Register introduction ................................................................................................................... 70
8.5. SysTick Timing experiments .......................................................................................................................... 72
8.5.1. Hardware design ....................................................................................................................................72
8.5.2. software design ....................................................................................................................................72
8.5.3. Programming points ....................................................................................................................................72
8.5.4. The code analysis ....................................................................................................................................73
8.6. Practice after class ......................................................................................................................................... 79
The first 9 Chapter . USART— A serial port communication ......................................................................................................... 80
9.1. Preview before class ......................................................................................................................................... 80
9.2. summary .................................................................................................................................................. 80
9.3. Introduction to serial communication protocol ....................................................................................................................... 80
9.3.1. The physical layer ........................................................................................................................................80
9.3.2. Protocol layer ........................................................................................................................................84
9.4. STM32 Of USART brief introduction ................................................................................................................ 85
9.5. USART Functional block diagram ............................................................................................................................85
9.6. USART Initialization structure details .......................................................................................................... 90
9.7. USART1 Receiving and transmitting communication experiment .................................................................................................................91
9.7.1. Hardware design ....................................................................................................................................92
9.7.2. software design ....................................................................................................................................92
9.7.3. Programming points ....................................................................................................................................92
9.7.4. The code analysis ....................................................................................................................................93
9.7.5. Download validation ....................................................................................................................................97
9.8. Practice after class ......................................................................................................................................... 97
The first 10 Chapter . DMA Direct store access .................................................................................................. 98
10.1. Preview before class .......................................................................................................................................98
10.2. summary ................................................................................................................................................98
10.3. DMA brief introduction .......................................................................................................................................98
10.4. DMA Functional block diagram .............................................................................................................................. 98
10.5. DMA Data configuration ............................................................................................................................100
10.6. DMA Initialization structure details .......................................................................................................... 101
Catalog
SAIU R20 1 6 The first 5 page
10.7. DMA Memory to memory mode experiment .............................................................................................103
10.7.1. Hardware design ................................................................................................................................103
10.7.2. software design ................................................................................................................................103
10.7.3. Programming points ................................................................................................................................103
10.7.4. The code analysis ................................................................................................................................104
10.7.5. Download validation ................................................................................................................................107
10.8. Practice after class .....................................................................................................................................107
The first 11 Chapter . TIM Basic timer ........................................................................................................ 108
11.1. Preview before class .....................................................................................................................................108
11.2. summary ..............................................................................................................................................108
11.3. Timer classification ................................................................................................................................ 108
11.4. Basic timer function block diagram explanation ......................................................................................................109
11.5. Timer initialization structure details ......................................................................................................110
11.6. Basic timer timing experiment ...............................................................................................................111
11.6.1. Hardware design ................................................................................................................................111
11.6.2. software design ................................................................................................................................111
11.6.3. Programming points ................................................................................................................................111
11.6.4. software analysis ................................................................................................................................111
11.6.5. Download validation ................................................................................................................................114
11.7. Practice after class .....................................................................................................................................114
The first 12 Chapter . TIM Advanced timer ........................................................................................................ 115
12.1. Preview before class .....................................................................................................................................115
12.2. summary ..............................................................................................................................................115
12.3. Advanced control timer ....................................................................................................................... 115
12.4. Function block diagram of advanced control timer ........................................................................................................116
12.4.1. Clock source ....................................................................................................................................117
12.4.2. External clock mode 1................................................................................................................... 117
12.4.3. External clock mode 2................................................................................................................... 118
12.4.4. Internal trigger input ....................................................................................................................... 119
12.4.5. Input capture ................................................................................................................................121
12.4.6. Output comparison ................................................................................................................................122
12.4.7. Open circuit function ................................................................................................................................125
12.5. Input capture application ............................................................................................................................125
12.5.1. Measure the frequency ................................................................................................................................126
12.5.2. Measure the pulse width ................................................................................................................................126
12.6. PWM The input mode ............................................................................................................................126
12.7. Output comparison application ............................................................................................................................128
12.7.1. PWM The output mode .....................................................................................................................128
Catalog
The first 6 page SAIUR201 6
Edited by Mr. Chen Dejin
12.7.2. PWM Edge alignment mode .............................................................................................................128
12.7.3. PWM Center alignment mode .............................................................................................................129
12.8. Timer initialization structure details ......................................................................................................129
12.8.1. TIM_TimeBaseInitTypeDef...................................................................................................130
12.8.2. TIM_OCInitTypeDef..............................................................................................................130
12.8.3. TIM_ICInitTypeDef............................................................................................................... 131
12.8.4. TIM_BDTRInitTypeDef.........................................................................................................132
12.9. PWM Complementary output experiment ................................................................................................................... 133
12.9.1. Hardware design ................................................................................................................................133
12.9.2. software design ................................................................................................................................133
12.9.3. Programming points ................................................................................................................................133
12.9.4. software analysis ................................................................................................................................134
12.9.5. Download validation ................................................................................................................................136
The first 13 Chapter . I2C Communications .................................................................................................................... 138
13.1. Preview before class .....................................................................................................................................138
13.2. summary ..............................................................................................................................................138
13.3. I2C Protocol Brief ............................................................................................................................138
13.3.1. I2C The physical layer ............................................................................................................................. 139
13.3.2. Protocol layer ....................................................................................................................................140
13.3.3. Start and stop signals of communication ....................................................................................................... 141
13.4. STM32 Of I2C Features and Architecture ................................................................................................... 144
13.4.1. STM32 Of I2C Introduction to peripherals .................................................................................................... 144
13.4.2. STM32 Of I2C Architecture analysis .................................................................................................... 145
13.4.3. Communication process ................................................................................................................................147
13.5. I2C Initialization structure details .......................................................................................................... 149
13.6. I2C— Reading and writing EEPROM experiment ........................................................................................................150
13.6.1. Hardware design ................................................................................................................................150
13.6.2. software design ................................................................................................................................151
13.6.3. Programming points ................................................................................................................................151
13.6.4. The code analysis ................................................................................................................................152
13.6.5. Download validation ................................................................................................................................167
13.7. Practice after class .....................................................................................................................................168
The first 14 Chapter . SPI Communications .................................................................................................................... 169
14.1. Preview before class .....................................................................................................................................169
14.2. summary ..............................................................................................................................................169
14.3. SPI Protocol Brief ............................................................................................................................169
14.3.1. SPI The physical layer .............................................................................................................................169
14.3.2. Protocol layer ....................................................................................................................................171
Catalog
SAIU R20 1 6 The first 7 page
14.4. STM32 Of SPI Features and Architecture ................................................................................................... 173
14.4.1. STM32 Of SPI Introduction to peripherals .................................................................................................... 173
14.4.2. TM32 Of SPI Architecture analysis ...................................................................................................... 174
14.4.3. Communication process ................................................................................................................................175
14.5. SPI Initialization structure details .......................................................................................................... 177
14.6. SPI— Read write serial FLASH experiment ................................................................................................. 178
14.6.1. Hardware design ................................................................................................................................179
14.6.2. software design ................................................................................................................................179
14.6.3. Programming points ................................................................................................................................180
14.6.4. The code analysis ................................................................................................................................180
14.6.5. Download validation ................................................................................................................................198
14.7. Practice after class .....................................................................................................................................198
The first 15 Chapter . Gyroscope attitude detection ....................................................................................................... 199
15.1. Preview before class .....................................................................................................................................199
15.2. summary ..............................................................................................................................................199
15.3. Attitude detection .....................................................................................................................................199
15.3.1. Basic knowledge ................................................................................................................................199
15.3.2. Coordinate system ....................................................................................................................................200
15.4. Using gyroscopes to detect angles ...............................................................................................................201
15.5. Use the accelerometer to detect the angle ............................................................................................................ 202
15.6. Use the magnetic field to detect the angle ................................................................................................................... 203
15.7. utilize GPS Detection angle ................................................................................................................ 204
15.8. Attitude fusion and quaternion ..................................................................................................................... 204
15.9. MPU6050 Module introduction ...................................................................................................................... 204
15.9.1. MPU6050 Module function and appearance ..................................................................................................204
15.9.2. MPU6050 Module pin function description ......................................................................................... 205
15.9.3. MPU6050 Hardware schematic diagram of the module ..............................................................................................205
15.10. MPU6050 The characteristic parameters of the module .......................................................................................................206
15.11. MPU6050— Get raw data, experiment ............................................................................................. 207
15.11.1. Hardware design ............................................................................................................................. 207
15.11.2. Brief introduction of supporting procedures ..................................................................................................................... 208
15.11.3. software design ............................................................................................................................. 209
15.11.4. Key points of programming ..................................................................................................................... 209
15.11.5. The code analysis ............................................................................................................................. 209
15.11.6. Download validation ............................................................................................................................. 215
15.12. MPU6050— utilize DMP Carry out attitude calculation ..................................................................................216
15.12.1. Hardware design ............................................................................................................................. 216
15.12.2. software design ............................................................................................................................. 216
15.12.3. Key points of programming ..................................................................................................................... 216
Catalog
The first 8 page SAIUR201 6
Edited by Mr. Chen Dejin
15.12.4. The code analysis ............................................................................................................................. 216
15.12.5. Download validation ............................................................................................................................. 226
15.13. MPU6050— Using a third-party host computer ............................................................................................. 227
15.13.1. Hardware design ............................................................................................................................. 227
15.13.2. software design ............................................................................................................................. 227
15.13.3. Key points of programming ..................................................................................................................... 227
15.13.4. The code analysis ............................................................................................................................. 227
15.13.5. Download validation ............................................................................................................................. 231
The first 1 Chapter . First time to know STM32
SAIU R20 1 6 The first 1 page
The first 1 Chapter . First time to know STM32
1.1. Preview before class
Find the answer in the book .
1. What is? STM32.
2. STM32 What can I do ?
1.2. summary
What's in this chapter :
(1)STM32 brief introduction
(2)STM32 Function is introduced
1.3. What is? STM32
STM32, To understand literally ,ST It's Italian French semiconductor ,M yes Microelectronics Abbreviation ,32 Express 32 position ,
Come together to understand ,STM32 Is refers to ST company-developed 32 Bit microcontroller . In today's 32 Bit controller ,STM32 can
So it's the brightest new star , It's adored , Very popular with engineers and the market , No core can make its right .
51 Embedded learning is an entry-level classic MCU, Because of its simple structure , Easy to teach , And can be programmed through the serial port without
Need extra emulators , So it is widely used in teaching , Up to now, many universities still use 51.51 Be born
On 70 years , It's traditional 8 Bit MCU , Now , After years of baptism , It has both its glory and its shortcomings . Now the market
Product competition is becoming more and more intense , Extremely cost sensitive , Accordingly MCU The performance requirements are more demanding : More functions , Lower power consumption ,
Easy to use interface and multitasking . In the face of these demands ,51 The existing resources seem to be limited . So whether it's college teaching or city teaching
Market demand , They all need a new one MCU To inject new vitality into this field . Based on such market demand , ARM The company launched its
Brand new basis ARMv7 Architecturally 32 position Cortex-M3 Microcontroller core . Followed by ,ST( Italian French semiconductor ) The company launched
Based on Cortex-M3 Kernel MCU— STM32.STM32 With the diversification of its product line 、 High cost performance 、 Easy to use
Library development mode , Quickly in many Cortex-M3 MCU Stand out from the rest , To be the brightest new star .STM32 As soon as it's on the market
Speed has occupied the middle and low end MCU market , It's very popular with the market and engineers , It's going to start a prairie fire . As a qualified teacher
Entry Engineer , In the face of new technologies , We don't turn a deaf ear to it , It's about meeting the needs of the market as soon as possible , Keep up with the technology .
The first 1 Chapter . First time to know STM32
The first 2 page SAIUR201 6
chart 1-2 STM32F103 Build the system interface
Now STM32 This is a trend , A trend , All we have to do is get on the express , Make your technology more competitive
force .
1.4. STM32 What can be done
STM32 It belongs to a microcontroller , It comes with a variety of common communication interfaces , such as USART、I2C、SPI etc. , It can connect many sensors
device , You can control a lot of devices . in real life , Many of the electrical products we come into contact with have STM32 The figure of , For example, smart bracelet ,
Micro four axis vehicle , Balance car 、 Move POST machine , Smart rice cooker ,3D Printers and so on . Let's take the two hottest ones recently
Let's talk about the products , One is a bracelet , One is aircraft .
chart 1-1 samsung GearFit Smart Bracelet
Red circle :STM32F439ZIY6S processor ,2048KB FLASH ,256KB RAM ,WLCSP143 encapsulation . Orange circle :Macronix
MX69V28F64 16 MB Flash memory , be based on MCP Packaged memory , It's a way of containing NOR and SRAM Flash memory , It's in the bracelet
It's often used in mobile devices , The advantage is small size , Can reduce PCB The size of the . This flash memory uses 439 Of FSMC Interface
drive . Yellow circle :InvenSense MPU-6500 gyroscope / Accelerometer , use
439 Of I2C Interface drive . Green circle : broadcom BCM4334WKUBG chip ,
Support 802.11n, bluetooth 4.0+HS as well as FM Receiver chip , use 439 Of
SDIO perhaps SPI Interface drive . Show :1.84" Flexible screen (Super
AMOLED),432 x 128 Pixels . Touch part with 439 Of I2C Interface
drive ,OLED The display part uses LTDC Interface drive .
In addition to the comparison of these important resources , Our overbearing development board also contains
It's Ethernet , Audio ,CAN, 485 , 232 , USB To serial port , bee
Buzzer , LED , Capacitors, buttons and other peripheral resources , Can learn enough
STM32F103ZET6 This chip . On the board , You can also run the system
ucosiii, Learn the graphical interface emwin. If you can do it , After learning ,
You can make a similar one yourself Gear Fit This kind of Bracelet . But a lot of people
Will say ,Gear Fit It involves hardware and software , The whole system is so complicated , Does not
It can be done by one person . That's right. , We can't do it , But we
The first 1 Chapter . First time to know STM32
SAIU R20 1 6 The first 3 page
The ability to do that is infinitely close to , Learn more , It's not too much skill . Now drones are very hot , For high-end drones STM32 Can't do it ,
But small four axis vehicles use STM32 More than enough . Pictured 1-3 Basically all the aircraft shown can be used STM32 Get it done .
chart 1-3 Four axis aircraft
1.5. STM32 How to choose
1.5.1. STM32 classification
STM32 There are a lot of series , It can meet the needs of the market , From the kernel there are Cortex-M0、M3、M4 and M7 These
Kind of , Each kernel is roughly divided into mainstream 、 High performance and low power consumption . See the table for details 1-1.
form 1-2 STM8 and STM32 classification
Just from the perspective of learning , You can choose F1 and F4,F1 It represents the basic type , be based on Cortex-M3 kernel , The main frequency is
72MHZ,F4 Represents high performance , be based on Cortex-M4 kernel , Main frequency 180M. To F1,F4(429 Series above ) except
The kernel is different from the main frequency , The obvious feature of the upgrade is that it brings LCD Controller and camera interface , Support SDRAM, this
Two differences will be given priority in project selection . But in terms of university teaching and user learning , Or the first choice F1 series , Currently in the city
The most information on the court , The largest share of products is F1 Series of STM32.
The first 1 Chapter . First time to know STM32
The first 4 page SAIUR201 6
1.5.2. STM32 Naming method
Here we have STM32F103ZET6 Let's talk about it STM32 Naming method of .
surface 1--3 STM32F103ZET6 Explanation of naming
For a more detailed naming method, see 1-4.
chart 1-4 STM8 and STM32 Naming method
1.5.3. Choose the right one MCU
I understand STM32 After the classification and nomenclature of , According to the specific needs of the project, you can roughly choose which kind of kernel first
MCU, General application , There is no need to connect the general selection of large screen Cortex-M3 Kernel F1 series , If you want to pursue high performance , need
A lot of data operations , And it needs external connection RGB On the large screen, choose Cortex-M4 Kernel F429 series . After making clear the general direction ,
The next step is the subdivision selection , Determine the pin first , More pins, more functions , The price is also expensive , It depends on the actual needs of the project
What functions , Enough is good . Determine the number of pins before selecting FLASH size , The same number of pins MCU It will be different
FLASH Size to choose from , This is also selected according to the actual needs , If the program is big, choose the bigger one FLASH, If the product is one quantity
production , All these savings are money . Some of the monthly shipments are based on KK( Million orders of magnitude ) Unit of product , Not only is MCU, Connect the electricity
The first 1 Chapter . First time to know STM32
SAIU R20 1 6 The first 5 page
Use less resistance and capacitance , What's more, even more PCB How many vias are there . The selection of components in the project is very deep , very
More knowledge .
How to assign a schematic IO
Before drawing the schematic , The general practice is to classify the pins first , Then I started to draw the schematic diagram , See table for pin classification 1-5.
form 1-5 Pin classification when drawing schematic diagram
To allocate according to function IO, Then you have to know each one first IO Function description of , We can get this from the official data book
I found . While studying , There are two official materials that we often use , One is the reference manual ( English name Reference manual),
The other is the data book ( English name Data Sheet). The specific differences between the two are shown in the table 1-6.
form 1-6 The content difference between reference manual and data manual
One sentence summary : The data manual is mainly used for reference in chip selection and schematic design , The reference manual is mainly used in programming
Waiting to check . These two official documents can be downloaded from the official website :
http://www.stmcu.org/document/list/index/category-150
In the data book , The part about pin definition is in Pinouts and pin description In this section , The specific definition is shown in the table
1-7.
The first 1 Chapter . First time to know STM32
The first 6 page SAIUR201 6
form 1-7 The pin definition in the data book
form 1-8 Interpretation of pin definition
Start distributing the schematic IO
such as MCU Model is STM32F103ZET6, Encapsulated in the LQFP144, We found the pins of this package in the data book
Definition , Then according to the pin number , Copy one by one , Put it in order excel surface . The specific arrangement method is in accordance with the table 5-4 The principle of painting
The pins in the diagram can be classified . After distribution, start drawing the schematic diagram .
1.5.4. PCB Where to proofing
Design the schematic diagram , Draw well PCB after , You need to make the board , Joint debugging of software and hardware . First of all PCB Proofing , Sure
Find some professional companies on the Internet to help , If you're lazy enough , I don't want to weld resistor capacitor diodes or triodes , You can also help
You put PCB The resistance and capacitance on the sample plate are well pasted for you , One stop proofing and pasting .
The first 1 Chapter . First time to know STM32
SAIU R20 1 6 The first 7 page
1.6. summary
This chapter introduces STM32 Basic concepts of 、 Application fields and chip selection methods . Mainly for STM32 One of the chips is clear
A clear understanding of , The following chapters will introduce each module and function of the chip in detail .
1.7. Practice after class
1. See which chips are used by UAVs and robots in the training room ? Which uses STM32?
The first 2 Chapter .STM32 The structure and composition of
The first 8 page SAIUR201 6
Edited by Mr. Chen Dejin
The first 2 Chapter . STM32 The structure and composition of
2.1. Preview before class
Find the answer in the book .
1. STM32 What's in it ?
2. STM32 Development methods and 51 What's the difference between single chip computers ?
2.2. summary
What's in this chapter :
(1)STM32 Chip structure
(2) Register mapping
2.3. What is a register
We often say register , So what is a register ? This is what we need to explain in this chapter , In the process of learning , everyone
Think about it with this question , Finally, let's see if you can define registers in one sentence .
2.4. STM 32 What does it look like
STM32 The basic structure of our development board is 144pin Of STM32F103ZET6, See Fig 6-1. This is
That's what we're going to learn next STM32, It's going to take us into the palace of embeddedness . The front of the chip is silk screen ,ARM It should mean that
The chip uses ARM The kernel of ,STM32F103ZET6 It's the chip model , The following words should be related to the production batch , Uppermost
yes ST Of LOGO. The chip is surrounded by pins , The dot in the lower left corner indicates 1 foot , And then from 1 The feet are arranged in counter clockwise order
( All chips are in a counter clockwise order ). Lead out the pins of the chip in the development board , Connect to various sensors ,
And then in STM32 Programming on ( In fact, the program controls these pins to output high level or low level ) To control all kinds of sensors
do , Learn by doing experiments STM32 The resources of the chip . The development board is an evaluation board , Onboard resources are very rich , lead
There's a lot of foot reuse , Try to verify all the functions of the chip on one board . chart 2-1 STM32F103ZET6 A physical picture ( In the middle of the red box
branch )
The first 2 Chapter .STM32 The structure and composition of
SAIU R20 1 6 The first 9 page
chart 2-1 STM32F103ZET6 A physical picture
chart 2-2 STM32F103ZET6 Front pin diagram
The first 2 Chapter .STM32 The structure and composition of
The first 10 page SAIUR2016
Edited by Mr. Chen Dejin
2.5. What's in the chip
What we see STM32 Chips are packaged products , It is mainly composed of kernel and peripherals on chip . If it's analogous to a computer , Inside
The core and peripherals are just like the ones on the computer CPU With motherboard 、 Memory 、 The graphics card 、 The relationship between hard disks .STM32F103 It's using Cortex-M3 Inside
nucleus , The kernel is CPU, from ARM Company design .ARM The company doesn't make chips , It's selling its chip technology license . Chip factories
merchant (SOC) Such as ST、TI、Freescale, Responsible for designing components outside the kernel and producing the entire chip , These components outside the kernel are called
For core peripherals or on-chip peripherals . Such as GPIO、USART( A serial port )、I2C、SPI And so on are called on-chip peripherals . See Fig 2-3.
chart 2-3 STM32 Schematic of the chip architecture
chip ( This is the kernel , Or call it CPU) And peripherals through a variety of bus connection , The driving unit has 4 individual , Passive single
Yuan also has 4 individual , See Fig 2-4. For ease of understanding , We can all understand the driver unit as CPU part , Passive unit
It's all understood as peripherals . Next, let's briefly introduce the components of the driving unit and the passive unit .
2.5.1. ICode Bus
ICode Medium I Express Instruction, Immediate instruction . The programs we have written are all instructions after compilation , Store in
FLASH in , If the kernel wants to read these instructions to execute the program, it must pass ICode Bus , It needs to be used almost all the time ,
It's used to take fingers .
2.5.2. Drive unit
DCode Bus
The first 2 Chapter .STM32 The structure and composition of
SAIUR201 6 The first 11 page
DCode Medium D Express Data, Data , That means that this bus is used to retrieve data . When we write the program , data
There are constants and variables , Constant is fixed , use C In language const Keyword modification , It's inside FLASH When
Medium , Variables are variable , Both global variables and local variables are placed inside SRAM. Because data can be Dcode total
Line and DMA Bus access , So to avoid access conflicts , When fetching data, it needs to go through a bus matrix to arbitrate , Decide which
A bus is fetching data .
The system bus
System bus is mainly used to access registers of peripheral devices , We usually call it register programming , That is to say, all the registers are read and written through this system
Bus .
DMA Bus
DMA Bus is also mainly used to transmit data , This data can be in the data register of a peripheral device , Can be in SRAM, can
With the inside FLASH. Because data can be Dcode Bus and DMA Bus access , So to avoid access conflicts , Taking
When counting, it needs to go through a bus matrix to arbitrate , Decide which bus is fetching data .
2.5.3. Passive unit
Internal flash memory
The internal flash memory is FLASH, This is where we put our programs . The kernel passes through ICode Come and get it
Face to face instructions .
Inside SRAM
Inside SRAM, That is what we usually say RAM, Program variables , The overhead of stacks and so on is internal SRAM. Inside
Nuclear passage DCode Bus to access it .
FSMC
FSMC Our English full name is Flexible static memory controller, It's called flexible static memory controller , yes
STM32F10xx One of the most distinctive peripherals in , adopt FSMC, We can expand memory , Such as the external SRAM,NANDFLASH
and NORFLASH. But one thing we should pay attention to is ,FSMC Only static memory can be expanded , In the name of S:static,
It can't be dynamic memory , such as SDRAM You can't expand .
The first 2 Chapter .STM32 The structure and composition of
The first 12 page SAIUR2016
Edited by Mr. Chen Dejin
AHB To APB The bridge of
from AHB The two lines that extend out of the bus APB2 and APB1 Bus , It's loaded with STM32 All kinds of features
set up . What we often say GPIO、 A serial port 、I2C、SPI These peripherals are mounted on these two buses , This is what we learn STM32
Key points of , Is to learn how to program these peripherals to drive a variety of external devices .
chart 2-4 STM32F10xx System diagram ( It doesn't include the interconnected type )
The first 2 Chapter .STM32 The structure and composition of
SAIUR201 6 The first 13 page
2.6. Memory mapping
In the figure 2-4 in , The controlled unit is FLASH,RAM,FSMC and AHB To APB The bridge of ( Peripherals on chip ), These functional units
The pieces are arranged together in a 4GB In the address space of . When we're programming , You can find them by their address , Then come on
Be them ( adopt C Language reads and writes data to them ). The memory itself has no address information , Its address is from the chip factory
Business or user distribution , The process of assigning addresses to memory is called memory mapping , See Fig 2-5. If you allocate another memory
One address is called memory remapping .
chart 2-5 Memory mapping
The first 2 Chapter .STM32 The structure and composition of
The first 14 page SAIUR2016
Edited by Mr. Chen Dejin
Here 4GB In the address space of ,ARM It has been divided into the average of thick lines 8 Block , each 512MB, Every block has its own rules
Set a purpose , The specific classification is shown in the table 6-1. The size of each block has 512MB, Obviously it's very big , Chip manufacturers in every block
It's not always enough to design unique peripherals within the scope of , It's just part of it .
form 2-1 Memory function classification
Here 8 individual Block Inside , Yes 3 One block is very important , And the three pieces that we care about the most .Block0 Designed to be inside
Ministry FLASH,Block1 Designed to be inside RAM,Block2 Used to design peripherals on a chip , Let's briefly introduce
These three Block The functional division of specific areas inside . Memory Block0 Internal regional function division Block0 It's mainly used to design movies
Internal FLASH , What we use STM32F103ZET6 Of FLASH yes 512KB, It's big capacity . In the chip
Internal integration is bigger FLASH perhaps SRAM It means an increase in the cost of the chip , It's often on-chip FLASH Not too much
Big ,ST Can be in pursuit of cost performance at the same time 512KB, It's a matter of conscience .
2.7. Register mapping
We know , The memory itself has no address , The process of assigning addresses to memory is called memory mapping , What is register mapping ?
What exactly is a register ? In memory Block2 This area , The design is peripherals on chip , They take four bytes as a unit , common
32bit, Each unit has its own function , When we control these units, we can drive the peripherals to work . We can find every
The starting address of the unit , And then through C Language pointer to access these units , If it's through this address every time
Way to visit , Not only bad memory, but also easy to make mistakes , At this time, we can according to the different functions of each unit , Give this in the name of function
The memory unit takes an alias , This alias is what we often call register , This is for a specific function that has been assigned an address
The process of getting aliases from the deposit receipt is called register mapping . such as , We find GPIOB The output data register of the port ODR The address of
yes 0x4001 0C0C( As for how to find this address, you can skip it first , We will explain it in detail later ),ODR The register is
32bit, low 16bit It works , Corresponding 16 External IO, Write 0/1 Corresponding IO The output is low / High level . Now let's go through C
How language pointers operate , Give Way GPIOB Of 16 individual IO All output high level , See code for details 2-1.
The first 2 Chapter .STM32 The structure and composition of
SAIUR201 6 The first 15 page
Code 2-1 Access memory units through absolute addresses
0x4001 0C0C It seems to us that GPIOB port ODR The address of , But in the compiler's view , It's just a normal
Variable , It's an immediate number , To make the compiler think of it as a pointer , We have to cast , Turn it into a pointer , namely
(unsigned int *)0x4001 0C0C, And then I'm going to do this pointer * operation . We just talked about that , Access memory through absolute address
Units are hard to remember and error prone , We can operate it in registers , See code for details 2-2.
Code 2-2 Access memory unit by register alias
For ease of operation , Let's just operate the pointer “*” Also defined in register alias , See code for details 2-3.
Code 2-3 Access memory units through register aliases
2.7.1. STM32 Peripheral address mapping for
On chip peripherals are divided into three buses , Depending on the speed of the peripheral , Different buses carry different peripherals ,APB1 Mount Low Speed outside
set up ,APB2 and AHB Mount High Speed peripherals . The lowest address of the corresponding bus is called the base address of the bus , The bus base address is also hung
The address of the first peripheral on the bus . among APB1 The address of the bus is the lowest , The peripherals start here , Also called peripheral base address .
2.7.2. Bus base address
form 2-2 Bus base address
form 2-2 Of “ Phase offset of external base address ” That is, the bus address and “ Peripherals on the film ” Base address 0x4000 0000 The difference between the . About
We'll talk about the address offset later .
2.7.3. Peripheral base address
There are all kinds of peripherals on the bus , These peripherals also have their own address ranges , The first address of a particular peripheral is called “XX Peripheral base
site ”, Also called XX The boundary address of the peripheral . Specific about STM32F10xx Please refer to 《STM32F10xx Reference resources
manual 》 Of 2.3 Section of the memory mapping table 1:STM32F10xx Register boundary address . In this we use GPIO This outside
Set to explain the base address of the peripheral ,GPIO High speed peripherals , Mount to APB2 On the bus , See table for details 2-3.
The first 2 Chapter .STM32 The structure and composition of
The first 16 page SAIUR2016
Edited by Mr. Chen Dejin
form 2-3 peripherals GPIO Base address
2.7.4. Peripheral registers
stay XX Peripheral address range , The registers of the peripheral are distributed . With GPIO Take peripherals as an example ,GPIO It's universal
Short for input and output port , In a nutshell STM32 Controllable pins , The basic function is to control the pin output high level or low power
flat . The simplest application is to put GPIO The pins of are connected to LED The cathode of the lamp ,LED The anode of the lamp is connected to the power supply , And then through
STM32 Control the level of the pin , In order to control LED The light goes on and off .GPIO There are many registers , Each one has a specific
The function of . Each register is 32bit, Four bytes , It is arranged in order on the base address of the peripheral , The register positions are in phase
Describe the offset address of the base address of the peripheral .
2.8. C Language encapsulates registers
All of the above about memory mapping , In the end, it is for us to better understand how to use C Language control read write peripheral register
Get ready , Here is the main content of this chapter .
2.8.1. Encapsulate bus and peripheral base address
In programming, in order to facilitate understanding and memory , We define the bus base address and peripheral base address with corresponding macro , Bus or
Peripherals use their names as macro names , See code for details 2-4.
The first 2 Chapter .STM32 The structure and composition of
SAIUR201 6 The first 17 page
Code 2-4 Bus and peripheral base macro definition
Code 2-4 First defined “ Peripherals on the film ” Base address PERIPH_BASE, And then PERIPH_BASE Add in the total
The address offset of the line , obtain APB1 、APB2 The address of the bus APB1PERIPH_BASE 、APB2PERIPH_BASE, stay
Add the offset of peripheral address on it , obtain GPIOA-G The peripheral address of , Finally, the address offset of each register is added to the peripheral address
move , Get the address of a specific register . Once you have a specific address , You can read and write with a pointer , See code for details 2-5.
Code 2-5 Use pointer control BSRR register
2.8.2. Encapsulation register list
Use the above method to define the address , It's still a little cumbersome , for example GPIOA-GPIOE Each has a set of registers with the same function ,
Such as GPIOA_ODR/GPIOB_ODR/GPIOC_ODR wait , They're just different addresses , But it has to be defined for each register
Its address . For more convenient access to registers , We introduce C The structure syntax of the language encapsulates registers , See Dai for details
code 2-6.
The first 2 Chapter .STM32 The structure and composition of
The first 18 page SAIUR2016
Edited by Mr. Chen Dejin
Code 2-6 Use structure pairs GPIO Encapsulation of register groups
This code uses typedef The keyword declares the name GPIO_TypeDef The type of structure , There's in the structure 7 One member changes
The amount , The variable name exactly corresponds to the name of the register .C The grammatical rules of language , The storage space of variables in a structure is continuous , among 32
Bit variables occupy 4 Bytes ,16 Bit variables occupy 2 Bytes , See Fig 2-6.
chart 2-6 GPIO_TypeDef Address offset of structure members
in other words , We define this GPIO_TypeDef , Suppose the first address of this structure is 0x4001 0C00( This is also
The first member variable CRL The address of ), So the second member variable in the structure CRH Your address is 0x4001 0C00
+0x04 , Plus this 0x04 , It represents CRL Occupied by 4 The offset of a byte address , Other member variables are relative to
The offset of the first address of the structure , On the right side of the above code, the comment has been given . Such an address offset is related to STM32 GPIO Peripheral defined registers
The address offset corresponds one by one , Just set the initial address of the structure , You can determine the address of the member in the structure , And then you can make a knot
Construct to access registers , See code for details 2-7.
The first 2 Chapter .STM32 The structure and composition of
SAIUR201 6 The first 19 page
Code 2-7 Access registers through struct pointers
This code starts with GPIO_TypeDef Type defines a structure pointer GPIOx , And let the pointer point to the address
GPIOB_BASE(0x4001 0C00), Use the address to determine , And then according to C The syntax of language access structure , use GPIOx->ODR
And GPIOx->IDR And so on . Last , We go further , Use macro to define GPIO_TypeDef Type of
The pointer , And the pointer points to each GPIO The first address of the port , When using, we can directly use the macro to access the register , Specific code 2-8.
Code 2-8 Well defined GPIO Port header address pin
Here we are just GPIO Take this peripheral as an example , I've explained it to you C Language encapsulates registers . And so on , Other than
We can also use this method to encapsulate . The good news is , This part of the work is done by the firmware library , Here we're just analyzing
This is the packaging process , Let everyone know , That's why .
The first 2 Chapter .STM32 The structure and composition of
The first 20 page SAIUR2016
Edited by Mr. Chen Dejin
2.9. Practice after class
1、 What is memory mapping ? What is memory remapping ?
2、 What is a register ?
The first 3 Chapter . First time to know STM32 Standard library
SAIUR201 6 The first 21 page
The first 3 Chapter . First time to know STM32 Standard library
3.1. Preview before class
Find the answer in the book .
1. What is? STM32 Standard library .
2. STM32 What is the difference between the development method of using standard library and the register method learned before
3.2. summary
What's in this chapter :
(1)STM32 Introduction to the standard library
(2)STM32 The folder and function of the standard library
In the last chapter , We built a couple of controls GPIO Functions of peripherals , It is the rudiment of function library , but GPIO also
We don't implement many functions , and STM32 Chips are not just GPIO This is a peripheral . If we want to finish it ourselves
Into this library , The workload is huge .ST Standard software library provided by the company , Contains STM32 Control of all registers on the chip
operation , We learn directly how to use ST Standard library , It will be very easy to control STM32 chip .
3.3. The library catalog 、 File info
STM32 The standard library is available on the official website , You can also get it directly from the supporting materials of this book . All the routines explained in this book are
3.5.0 The library files . Please open the following STM32 Standard library file with reading . Unzip the library file and enter its directory :
“STM32F10x_StdPeriph_Lib_V3.5.0\” The content description of each folder of the software library is shown in the figure 3-1.
The first 3 Chapter . First time to know STM32 Standard library
The first 22 page SAIUR2016
Edited by Mr. Chen Dejin
chart 3-1 ST Standard library catalog :STM32F10x_StdPeriph_Lib_V3.5.0\
1. Libraries: Under the folder is the source code and startup file of the driver library , This is very important , The firmware library we're going to use is right here
In a folder .
2. Project : Under the folder are examples and project templates written in the driver library , The routines written for each peripheral are very useful to us
Useful , When we study, we can refer to the routines in it , Very comprehensive , It's like exhausting all the functions of peripherals .
3. Utilities: Contains the ST The routine of the official experimental board , There is no need to use , Just skip it .
4. stm32f10x_stdperiph_lib_um.chm: Library help documentation , This is very useful , Those who don't like to see the source code directly can look it up in a reasonable way
Ask for the function description of each peripheral , Very detailed . This is a compiled HTML file , Mainly about how to use the drive
Dynamic library to write their own applications . To put it more vividly , This HTML Just tell us :ST The company has written for you
The driver of each peripheral device has been changed , If you want to know how to use these examples, please ask me for help . Unfortunately , This help document is in English
Wen's , This is a big obstacle for many friends who are not good at English . But here's to tell you , English is just a tool
have , Never let it become an obstacle to our study . In fact, the English is very simple , What we need is the courage to take it
gas . When developing with libraries , We need to take libraries Add the library function file under the directory to the project , And look up the library help article
Let's learn about ST Library functions provided , This document describes how to use each library function . Get into Libraries Folder
notice , The library files about the kernel and peripherals are stored in CMSIS and STM32F10x_StdPeriph_Driver Folder
in .
STM32F10x_StdPeriph_Lib_V3.5.0\Libraries\CMSIS\ The expanded contents of the folder are shown in the figure 3-2.
The first 3 Chapter . First time to know STM32 Standard library
SAIUR201 6 The first 23 page
chart 3-2 CMSIS Folder contents directory :Libraries\CMSIS\
The yellow box is what we need to use , Now let's explain the functions of these documents one by one . Kernel related files
stay CoreSupport Folder has core_cm3.c and core_cm3.h Two documents .Core_cm3.h The kernel is implemented in the header file
Register mapping for , Corresponding peripheral header file stm32f10x.h, The difference is a peripheral for the kernel , One for the film ( The kernel
Outside ) The peripherals of .core_cm3.c File to achieve the operation of the kernel peripheral register function , Use less . We also need to understand
Yes. core_cm3.h The header file contains “stdint.h” This header file , This is a ANSI C file , It's processor independent
External , As we all know C Language header file “stdio.h” file . be located RVMDK The installation directory of this software is , Lord
The purpose is to provide some type definitions . See code list 3-1.
Code list 3-1:stdint.h The type definition in the file
These new type definitions mask the use of different chip platforms , The emergence of such as int Its size is 16 position , still 32 Bit difference .
So in our later program , Will use new types such as uint8_t 、uint16_t etc. . In slightly older versions of the program also often appear
Such as u8、u16、u32 This type , Separately expressed without sign 8 position 、16 position 、32 An integer . Beginners encounter such old
I feel confused , They are defined in STM32f10x.h In file . It is suggested to use as much as possible in the new program in the future
The first 3 Chapter . First time to know STM32 Standard library
The first 24 page SAIUR2016
Edited by Mr. Chen Dejin
uint8_t 、uint16_t The definition of type . The startup file is placed in startup/arm Under this folder , Here's the startup file
There are many , Different types of microcontrollers use different startup files , For a detailed description of each boot file, see table
We use in the development board STM32F103VET6 perhaps STM32F103ZET6 Of FLASH All are 512K, It belongs to the basic type
Large capacity products , Start file unified selection startup_stm32f10x_hd.s.
Stm32f10x.h
This header file implements the mapping of all registers of peripherals on chip , It's a very important header file , In the kernel corresponding to the idea
The header file for is core_cm3.h.
system_stm32f10x.c
system_stm32f10x.c File implementation STM32 The clock configuration of , The operation is on-chip RCC This peripheral . The system is in
After power on , The first choice is to execute the startup file written by the assembly , In the reset function of the startup file SystemInit The function is right there
This document defines . After calling , The system clock is initialized to 72M. If we need to reconfigure the system later
The clock , We can refer to this function rewrite . To maintain the integrity of the library , We will not modify the clock configuration directly in this file
Set function .
3.4. STM32F10x_StdPeriph_Driver Folder
File directory : Libraries\STM32F10x_StdPeriph_Driver Get into libraries In the catalog
STM32F10x_StdPeriph_Driver Folder , See the picture 3-3.
chart 3-3 Peripheral driver
The first 3 Chapter . First time to know STM32 Standard library
SAIUR201 6 The first 25 page
STM32F10x_StdPeriph_Driver There is... Under the folder inc(include Abbreviation ) Follow src(source Abbreviation ) These two
A folder , The files here belong to CMSIS Other than 、 Peripherals on a chip .src Inside is the driver of each device peripheral
Source program ,inc Is the corresponding peripheral header file .src And inc The folder is ST The main content of the standard library , Even many people directly
Think ST The standard library refers to these files , So it's important . stay src and inc What's in the folder is ST The company targets at each
STM32 A library function file written for peripherals , Each peripheral corresponds to a .c and .h Postfix file . We call these peripheral files
by : stm32f10x_ppp.c or stm32f10x_ppp.h file ,PPP Represents the name of the peripheral . As we built in the last chapter
stm32f10x_gpio.c And tm32f10x_gpio.h file , It belongs to this category . For example, for analog-to-digital conversion (ADC) peripherals , stay src file
There's one under the clip stm32f10x_adc.c Source file , stay inc There's one under the folder stm32f10x_adc.h The header file , If we develop
It's used in the project STM32 Inside ADC, At least these two files should be included in the project . See the picture 3-4.
chart 3-4 Driver source file and header file
In these two folders , There's also a very special one misc.c file , This file provides the peripheral to the kernel NVIC( Interrupt to
Quantity controller ) Access functions for , When configuring interrupts , We have to add this file to the project .stm32f10x_it.c 、
stm32f10x_conf.h and system_stm32f10x.c file
stm32f10x_it.c: This file is dedicated to writing interrupt service functions , Before we change it , This file
Some system exceptions have been defined ( Special interruptions ) The interface of , Other ordinary interrupt service functions are added by ourselves . But how do we know
How to write the interface of these interrupt service functions ? Can I customize it ? The answer, of course, is not ,
These can be found in the assembly startup file , When we learn about interrupt and startup files, we'll talk about
system_stm32f10x.c: This file contains STM32 Initialize the system clock after the chip is powered on 、 For expanding external memory
The first 3 Chapter . First time to know STM32 Standard library
The first 26 page SAIUR2016
Edited by Mr. Chen Dejin
function , For example, we mentioned in the previous two chapters that “SystemInit” function , Used to initialize the clock after power on , The definition of this function is
Righteousness is stored in system_stm32f10x.c file .STM32F103 Series of chips , Call this of the library SystemInit After the function ,
The system clock is initialized to 72MHz, If necessary, you can modify the contents of this file , Set your own clock frequency , But
To keep the integrity of the library , When we do the system clock configuration, we will rewrite the clock configuration function .
stm32f10x_conf.h: This file is included in stm32f10x.h file . When we program with the firmware library , If you need
The driver library of a peripheral device , You need to include the header file of the peripheral :stm32f10x_ppp.h, Including a good , If it's too much
peripherals , You need to include multiple header files , This not only affects the beauty of the code, but also is not easy to manage , Now we use a header file stm32f10x_conf.h
Include the header files of these peripherals in it , Let the configuration header file manage the header files of these peripherals , We're in the app
Just include the configuration header file , We also know that this header file is stm32f10x.h The last part of is contained , So in the end I
We just need to include stm32f10x.h This header file is enough , Very convenient .Stm32f10x_conf.h See code list 3-2. By default
Next, all header files are included , It's not commented out . We can also comment out everything we don't want , Just leave what you need to use .
Code list 3-2 stm32f10x_conf.h File configuration software library
3.5. The relationship between the files in the library
In front, I briefly introduced the functions of each library file , Library files are directly included in the project , There's no need to change , Others
Files need to be configured according to specific needs when we use them . Next, from the overall grasp of each file in the library project
Hierarchy or relationship , These files correspond to CMSIS Standard Architecture . See the picture 3-5.
The first 3 Chapter . First time to know STM32 Standard library
SAIUR201 6 The first 27 page
chart 3-5 The relationship between the files in the library
chart 3-5 It describes STM32 The calling relationship between the files in the library , In the actual process of using library development project , Let's take a seat
On CMSIS Layer files are included in the project , In addition to special system clock needs to be modified system_stm32f10x.c, Other documents don't need any
modify , It is also not recommended to modify . For a few files at the user level , It's when we use the library , For different applications, kuwen
Add and delete ( Add and delete by conditional compilation ) And altered documents .
The first 3 Chapter . First time to know STM32 Standard library
The first 28 page SAIUR2016
Edited by Mr. Chen Dejin
3.6. First knowledge of library functions
Library functions , Namely STM32 Library file for us to write a good driver peripheral function interface , We just call these libraries
function , You can do that. STM32 To configure , Achieve the goal of control . We don't know how library functions are implemented , But we're going to
To use a function, you have to know the function 、 Parameters that can be passed in and their meanings 、 Values and return functions . therefore , Some readers ask so many questions
How can I remember ? My answer is : Just check it out , Who remembers so much . So it's very important for us to learn to look up the library help documents
It is necessary to . Open the library help document 《stm32f10x_stdperiph_lib_um.chm》 See the picture 3-6
chart 3-6 Library help documentation
Open the directory label of the document layer by layer : Tag list :Modules\STM32F10x_StdPeriph_Driver\ You can see STM32F10x
_StdPeriph_Driver There are many names of peripheral driver files under the tag MISC、ADC、BKP、CAN Such as tag . We're trying to find out
see GPIO Of “ Bit setting function GPIO_SetBits” have a look , Open label : Tag list :
Modules\STM32F10x_StdPeriph_Driver\GPIO\Functions\GPIO_SetBits See the picture 3-7.
The first 3 Chapter . First time to know STM32 Standard library
SAIUR201 6 The first 29 page
chart 3-7 Library help document function description
Using this document , Even if we didn't look at the specific source code , I know how to use it . Such as GPIO_SetBits,
The prototype of the function is void GPIO_SetBits(GPIO_TypeDef * GPIOx , uint16_tGPIO_Pin). Its function is : Enter a
Types are GPIO_TypeDef The pointer to GPIOx Parameters , Select the... To control GPIO port ; Input GPIO_Pin_x macro , Its
in x Refers to the pin number of the port , Specify the pins to control . The input parameters GPIOx by ST Custom numbers defined in the standard library
According to the type , Both of these incoming parameters are struct pointers . At the beginning of school , We don't know such as GPIO_TypeDef What is this type of
What do you mean , You can click on the underlined... In the function prototype GPIO_TypeDef You can see the declaration of this type . That's it
Learn about library functions , Readers will find that STM32 My library is beautifully written . Each function and data type conforms to the given name
The principle of knowing righteousness , Of course , It's a very long name to write , And for us to input such a long English , It's easy to make a mistake ,
So when developing software , Where library functions are used , Directly copy and paste the function name in the library help document into the project file
All right . and , coordination MDK Software code automatic completion function , It can reduce the amount of input . Some users feel that using library documents is very difficult
Bother , You can also refer to STM32 Source code of standard library , Library help documents are generated from the source code , So look directly at the source
Code can also understand the function function .
3.7. Practice after class
open ST Standard library , View its files , Compare the ST The standard library has the same name as the project in our previous chapter ,
See what the difference is .
The first 4 Chapter .GPIO Use
The first 30 page SAIUR2016
The first 4 Chapter . GPIO Use
4.1. Preview before class
Find the answer in the book .
1. STM32 f103zet6 Of GPIO How many ?
2. STM32 f103zet6 Of GPIO What are the working modes ?
4.2. summary
What's in this chapter :
(1)STM32 Of GPIO Structure and function of
(2) Use GPIO Lighten up LED The lamp
Use the library to build a good project template , It's easy to use STM32 Standard library for writing applications , It can be said that from this chapter I
We are really starting to step into STM32 The gateway to firmware library development .
4.3. GPIO brief introduction
GPIO Is the abbreviation of general input and output port , In a nutshell STM32 Controllable pins ,STM32 Chip GPIO
Pins are connected to external devices , So as to realize external communication 、 Control and data acquisition functions .STM32 Chip GPIO By
Divided into groups , Each group has 16 One pin , If the model is STM32F103ZET6 The models of chips have GPIOA、GPIOB、GPIOC
to GPIOG common 7 Group GPIO, The chip is a total of 144 One pin , among GPIO It's a big part of it , be-all GPIO Pin
They all have basic input and output functions . The most basic output function is made up of STM32 Control pin output high 、 Low level , Switch control is realized ,
If you put GPIO Pin into LED The lamp , Then you can control LED The light goes on and off , Pin into relay or triode , Then you can
To control the on-off of external high-power circuit through relay or triode . The most basic input function is to detect the external input level , If you put
GPIO Pin to key , Distinguish whether the key is pressed by the level .
The first 4 Chapter .GPIO Use
SAIUR201 6 The first 31 page
4.4. GPIO Block diagram analysis
chart 4-1 GPIO Structure diagram
adopt GPIO Hardware structure diagram , You can have a deeper understanding of GPIO Peripheral and its various application modes . From the most
From the right side , On the far right is the representation of STM32 From the chip GPIO Pin , The rest of the components are inside the chip .
4.4.1. Protection diode and upper 、 Pull down resistance
The two protection diodes of the pin can prevent too high or too low voltage input outside the pin , When the pin voltage is higher than VDD when , upper
The diode is on , When the pin voltage is below VSS when , The diode below is on , Prevent abnormal voltage from leading into the chip and causing the chip to burn
destroyed . Despite this protection , It doesn't mean that STM32 The pin can be directly connected to the high power driver , Such as direct drive motor ,
Forced drive or the motor doesn't work , Or cause the chip to burn out , It is necessary to increase the power and isolate the circuit drive .
4.4.2. P-MOS Tube and N-MOS tube
GPIO The pin line passes through two protection diodes , Up to “ The input mode ” structure , Down to “ The output mode ” structure .
Let's look at the output mode section first , The line goes through a road made up of P-MOS and N-MOS A cell circuit made up of tubes . This structure makes GPIO have
了 “ Push pull output ” and “ Open drain output ” Two modes . The so-called push-pull output mode , It's based on these two MOS How tube works to name
Of . In this structure, high level is input , After the reverse , At the top of the P-MOS Conduction , At the bottom of the N-MOS close , External output
High level ; In this structure, low level is input , After the reverse ,N-MOS The pipe is open ,P-MOS close , External output low level .
When the pin level switches between high and low , Two pipes turn on ,P The tube is responsible for filling the current ,N The tube is responsible for pulling the current , Make it load capacity and open
The closing speed is much higher than the ordinary way . The low level of push-pull output is 0 v , The high level is 3.3 v , Refer to the figure for details 4-2,
It is the equivalent circuit of push-pull output mode .
The first 4 Chapter .GPIO Use
The first 32 page SAIUR2016
chart 4-2 Push pull equivalent circuit
And in open drain mode , At the top of the P-MOS It doesn't work at all . If we control the output to be 0, Low level , be P-MOS
The tube is closed ,N-MOS The pipe is open , Ground the output , If the control output is 1 ( It can't directly output high level ) when , be P-MOS Tube and
N-MOS All the tubes are closed , So the pin neither outputs high level , It doesn't output low level either , It's a high resistance state . For normal use must be external
Connect the pull-up resistor , Refer to the figure 8-3 The equivalent circuit in the circuit . It has “ Line and ” characteristic , in other words , If there are many open drain mode pins connected
When we get together , Only if all the pins output high resistance state , The pull-up resistor provides the high level , This high level voltage is external pull-up
The voltage of the power supply connected to the resistor . If one of the pins is low , Then the line is equivalent to a short circuit to ground , Make the whole line low power
flat ,0 v . Push pull output mode is generally used when the output level is 0 and 3.3 Where high speed switching is required . stay
STM32 The application of , Except for situations where open drain mode must be used , We're all used to push-pull output mode . Open drain output is generally used in
I2C、SMBUS Communication, etc “ Line and ” Function of the bus circuit . besides , It is also used in the case of level mismatch , If you need to lose
Out 5 High voltage level , You can connect a pull-up resistor to the outside , Pull up the power supply for 5 v , And the GPIO Set to open drain mode ,
When high resistance state is output , Output from pull-up resistor and power supply 5 Volt level , See Fig 4-3.
The first 4 Chapter .GPIO Use
SAIUR201 6 The first 33 page
chart 4-3 STM32 IO External output 5V level
4.4.3. Output data register
The above mentioned double MOS The input signal of the tube structure circuit , By GPIO“ Output data register GPIOx_ODR” Provided ,
So we can modify it by modifying the value of the output data register GPIO The output level of the pin . and “ Set up / Reset register
GPIOx_BSRR” The output of the circuit can be affected by modifying the value of the output data register .
The first 4 Chapter .GPIO Use
The first 34 page SAIUR2016
4.4.4. Reuse function output
“ Reuse function output ” Medium “ Reuse ” Refer to STM32 Other on-chip peripherals of GPIO Pin control , here GPIO lead
The foot is used as part of the peripheral function , It's a second use . From other peripherals “ Multiplexing function output signal ” And GPIO In itself
All data registers are connected to the dual MOS Tube structure input , Through the trapezoidal structure in the figure as a switch switch selection . For example, I
We use it USART Serial communication , You need to use something GPIO The pin is used as the communication transmission pin , At this time, we can
GPIO The pins are configured to USART Serial port multiplexing function , The pin is controlled by the serial peripheral , send data .
4.4.5. Input data register
GPIO The top half of the block diagram ,GPIO The pins go through the internal top 、 Pull down resistance , It can be configured to / Drop down input , however
And then connect to the Schmidt trigger , The signal goes through the trigger , The analog signal is converted into 0、1 The digital signal of , Then stored in “ Input
Data register GPIOx_IDR” in , By reading this register, you can understand GPIO The level state of the pin .
4.4.6. Reuse function input
And “ Reuse function output ” Similar model , stay “ Reuse function input mode ” when ,GPIO The signal from the pin is transmitted to STM32 Other films
On the peripherals , The pin status is read by the peripheral . Again , If we use USART Serial communication , You need to use something GPIO Pin
As a communication receiving pin , At this time, we can GPIO The pins are configured to USART Serial port multiplexing function , send USART Sure
Receiving remote data through the communication pin .
4.4.7. Analog input and output
When GPIO Pins are used for ADC When collecting the input channel of voltage , Used as a “ Analog input ” function , At this time, the signal is not encrypted
Special , Because after Schmidt trigger, the signal is only 0、1 Two kinds of state , therefore ADC Peripherals need to collect the original module
Pseudo signal , The signal source input must precede the Schmidt trigger . Similarly , When GPIO Pins are used for DAC As an analog voltage output
Channel time , Now as “ Analog output ” function ,DAC The output of the analog signal does not go through the double MOS Tube structure , Analog signal directly
Output to pin .
The first 4 Chapter .GPIO Use
SAIUR201 6 The first 35 page
4.5. GPIO Working mode
To sum up , from GPIO It's the structure that determines GPIO It can be configured in the following modes :
In the firmware library ,GPIO All in all 8 It's a subdivision mode of work , A little sorting can be roughly classified into the following three categories :
4.5.1. The input mode ( simulation / Floating space / Pull up / The drop-down )
In input mode , Schmidt trigger on , Output is disabled , By inputting the data register GPIOx_IDR Read I/O shape
state . The input mode , Can be set to pull up 、 The drop-down 、 Floating and analog inputs . Pull up and pull down input are easy to understand , The default electricity
Level is determined by pull-up or pull-down . The level of the floating input is uncertain , It's all up to external input , It's usually used when you connect buttons
It's this pattern . Analog inputs are used for ADC collection .
4.5.2. The output mode ( push-pull / Open a leak )
In output mode , In push-pull mode, double MOS Tube works in rotation , Output data register GPIOx_ODR Controllable I/O
Output high and low level . In open drain mode , Only N-MOS Management work , The output data register can control I/O Output high resistance state or low level .
The output speed is configurable , Yes 2MHz\10MHz\50MHz The option to . The output speed here is I/O The high and low level states supported are the most
High switching frequency , The higher the frequency of support , The more power consumption , If the power consumption requirement is not strict , Set the speed to the maximum . In output mode
When the Schmidt trigger is on , The input is available , By inputting data register GPIOx_IDR Readable I/O The actual state of .
4.5.3. Reuse function ( push-pull / Open a leak )
In the reuse function mode , Output enable , The output speed is configurable , It can work in open drain and push-pull mode , But the output signal comes from its
It's peripherals , Output data register GPIOx_ODR Invalid ; Input available , It can be obtained by inputting data register I/O The actual state ,
But generally, the peripheral registers are used to obtain the data signal directly . Through to GPIO Registers write different parameters , You can change
GPIO Working mode of , stay GPIO In peripherals , Control port high and low control register CRH and CRL You can configure each GPIO Of
Working mode and working speed , Every time 4 One bit controls one IO,CRH The upper eight bits of the control port ,CRL Control port low 8 position ,
Specifically CRH and CRL Register description of .
The first 4 Chapter .GPIO Use
The first 36 page SAIUR2016
chart 4-4 GPIO Port configuration low register
The first 4 Chapter .GPIO Use
SAIUR201 6 The first 37 page
chart 4-5 GPIO Port configuration high register
4.6. Lighten up LED- Hardware design
In this tutorial STM32 Chip and LED The connection of the lamp is shown in the figure 12-1, This is a RGB The lamp , It's made up of three little red, blue and green lights
become , Use PWM Control can be mixed into 256*256*256 Plant different colors .
chart 4-6 LED Hardware schematic diagram
The first 4 Chapter .GPIO Use
The first 38 page SAIUR2016
these LED The cathode of the lamp is connected to STM32 Of GPIO Pin , As long as we control GPIO The level output of the pin
state , To control LED The light goes on and off . If you use a test board LED The connection mode or pin of the lamp is different , Just according to me
Our project can be modified , The control principle of the program is the same . Lighten up LED- Software design here only explains the core part of the code , There are some
Variable settings , The inclusion of header files may not involve , For complete code, please refer to the supporting project in this chapter . In order to make the project more efficient
Organization , We put LED The codes related to lamp control are stored separately , Easy to transplant later . stay “ Engineering formwork ” On top of the new
“ bsp_led.c” And “bsp_led.h ” file , Among them “bsp ” namely Board Support Packet Abbreviation ( Board level support package ), These documents are also
It can be named according to your preference , These files don't belong to STM32 Content of the standard library , It is written by ourselves according to the application needs .
4.7. Lighten up LED- Programming points
1. Can make GPIO Port clock ;
2. initialization GPIO The target pin is push-pull output mode ;
3. Write a simple test program , control GPIO High pin output 、 Low level .
4.8. Lighten up LED- The code analysis
4.8.1. LED Lamp pin macro definition
In the process of writing an application , Consider changing the hardware environment , for example LED The control pin of the lamp is different from the current one ,
We hope that the program can run normally in the new environment with minimal modification . At this time, we usually use the macro for the hardware related parts
encapsulation , If you change the hardware environment , Just modify these hardware related macros , These definitions are generally stored in the header file , In this case
“bsp_led.h” In file , See code list 4-1.
Code list 4-1 LED Control pin related macro
The above code respectively controls LED Of a lamp GPIO port 、GPIO Pin numbers and GPIO The port clock is packaged . stay
In actual control, we use these macros directly , In order to achieve the application code hardware independent effect . Among them GPIO Shi Zhonghong
“RCC_APB2Periph_GPIOB” yes STM32 The standard library defines GPIO Port clock related macro , Its function and
“GPIO_Pin_x” This kind of macro is similar to , Is used to indicate register bits , Easy to use library functions , Now initialize GPIO Clock time
You can see its usage .
The first 4 Chapter .GPIO Use
SAIUR201 6 The first 39 page
4.8.2. control LED Macro definition of light on / off state
For the convenience of control LED The lamp , We put LED The light is usually on 、 The control of extinction and state reversal is also directly defined as a macro , See code list 4-2.
Code list 4-2 control LED Bright macro
The first 4 Chapter .GPIO Use
The first 40 page SAIUR2016
This part of macro control LED The operation of lighting is directly to BSRR、BRR and ODR These three registers are written to the control instruction to implement
Current , Yes BSRR Write 1 Output high level , Yes BRR Write 1 Output low level , Yes ODR The XOR operation of a bit in a register can
The state of reverse transposition .RGB Color lights can mix colors , For example, in the last code, we control the red light and green light on and the blue light off , It's yellow
Color effect . In code “\” yes C Continuation grammar in language , The next line of the continuation character is the same line as the code of the continuation character .
In the code, because the macro defines keywords “#define” Only valid for the current line , So we use line continuation to connect , The following code is
The equivalent of :
#define LED_YELLOW LED1_ON; LED2_ON; LED3_OFF
Pay attention to when applying line continuation , stay “\” There can't be any characters after ( Including comments 、 Space ), You have to go straight back .
4.8.3. LED GPIO Initialization function
Use the macro above , To write LED Initialization function of light , See code list 4-3.
Code list 4-3 LED GPIO Initialization function
The first 4 Chapter .GPIO Use
SAIUR201 6 The first 41 page
The whole function is related to “ Building library function rudiments ” Similar in chapter , The main difference is that hardware related parts use macros instead of , initialization
GPIO Port clock also uses STM32 Library function , The execution flow of the function is as follows :
1. Use GPIO_InitTypeDef Definition GPIO Initializing structure variables , So that the following can be used for storage GPIO To configure .
2. Call library function RCC_APB2PeriphClockCmd Enable LED Of a lamp GPIO Port clock , In the previous chapters, I
They are direct to RCC Register assignment enables the clock to , It's not as intuitive as that . This function has two input parameters , The first one is
The number is used to indicate the clock to be configured , As in this example “RCC_ APB2Periph_GPIOB”, When applying, we use “|” At the same time
To configure 3 individual LED The clock of the lamp ; The second argument to the function sets the State , You can enter “Disable” Close or “Enable” send
It's a clock .
3. towards GPIO Initialize structure assignment , Initialize the pin to push-pull output mode , Among them GPIO_Pin Use macros
“LEDx_GPIO_PIN” To assign a value , It makes the realization of function easy to transplant .
4. Use the above to initialize the configuration of the structure , call GPIO_Init Function writes parameters to the register , complete GPIO The initialization ,
there GPIO Port usage “LEDx_GPIO_PORT” Macro , It's also for the convenience of program transplantation .
5. Use the same initialization structure , Only modify the pin and port of the control , Initialize other LED The lamp uses GPIO Pin .
6. Use macro control RGB The light is off by default .
4.8.4. The main function
written LED After the lamp control function , You can go to main Function tested , See code list 4-4.
Code list 4-4 control LED The lamp ,main file
The first 4 Chapter .GPIO Use
The first 42 page SAIUR2016
Code list 4-4 control LED The lamp ,main file main Function , Call what we defined earlier LED_GPIO_Config
Initialize well LED The control pin of , And then directly invoke the various controls LED Lights on and off macro to achieve LED Light control . above ,
It's a use STM32 Standard software library development and application process .
4.9. Lighten up LED- Download validation
Download the compiled program to the development board and reset it , You can see RGB The lights show different colors in turn .
4.10. Practice after class
Use GPIO Give Way LED The lights show different colors .
The first 5 Chapter .STM32 RCC The clock system
SAIUR201 6 The first 43 page
The first 5 Chapter . STM32 RCC The clock system
5.1. Preview before class
Find the answer in the book .
1. APB2 What's the maximum value of the clock ?
2. How to configure using the standard library GPIO The clock of ?
5.2. summary
What's in this chapter :
(1) Analysis of the structure and use of the clock system
(2) Use the standard library to configure the system clock
RCC :reset clock control Reset and clock controller . In this chapter, we mainly explain the clock part , Especially when it comes to understanding
Clock tree , Understand the clock tree ,STM32 I'll know everything about the clock .
5.3. RCC The main role — The clock part
Set the system clock SYSCLK、 Set up AHB Division factor ( decision HCLK How much )、 Set up APB2 Division factor
( decision PCLK2 How much )、 Set up APB1 Division factor ( decision PCLK1 How much )、 Set the frequency division of each peripheral
factor ; control AHB、APB2 and APB1 The three bus clocks are on 、 Control the clock on of each peripheral . about
SYSCLK、HCLK、PCLK2、PCLK1 The configuration of these four clocks is :PCLK2 = HCLK = SYSCLK=PLLCLK =
72M,PCLK1=HCLK/2 = 36M. This clock configuration is also standard for library functions , That's what we use the most .
5.4. RCC Block diagram analysis — The clock part
The clock tree is more boring if it only talks about theory , If you choose a main line , With code , It will be very nice to explain first and then
easy , And the memory is deeper . Here we select library function clock system clock function : SetSysClockTo72(); In terms of this function
Write a process to explain the clock tree , This function is also the default system clock setting function when we use the library . The function is to benefit
The first 5 Chapter .STM32 RCC The clock system
The first 44 page SAIUR2016
use HSE Set the clock to :PCLK2 = HCLK = SYSCLK = 72M,PCLK1=HCLK/2 = 36M. Now let's take this
A code flow as the main line , To analyze the clock tree , Corresponding to the yellow part of the picture , The code flow is in the order of number in the clock tree
Sequence identification .
chart 5-1 STM32 Clock tree
5.5. The system clock
5.5.1. HSE High speed external clock signal
HSE It's a high-speed external clock signal , It can be provided by active crystal oscillator or passive crystal oscillator , Frequency from 4-16MHZ Unequal . When to make
With active crystal oscillator , Clock from OSC_IN Pin in ,OSC_OUT Pin hanging , When using passive crystal oscillator , Clock from OSC_IN
and OSC_OUT Get into , And it should be equipped with resonant capacitor .HSE The most commonly used is 8M The passive crystal oscillator . When you are sure PLL Here comes the clock
The first 5 Chapter .STM32 RCC The clock system
SAIUR201 6 The first 45 page
When it comes to the source ,HSE You can do it without frequency division or 2 frequency division , This is configured by the clock register CFGR Bit 17:PLLXTPRE Set up ,
We set it to HSE Regardless of the frequency .
5.5.2. PLL Clock source
PLL There can be two clock sources , One from HSE, The other is HSI/2, Which register to use is configured by the clock
CFGR Bit 16:PLLSRC Set up .HSI It's an internal high-speed clock signal , The frequency is 8M, Depending on the temperature and the environment
The rate will drift , General inaction PLL The source of the clock . Here we choose HSE As PLL The source of the clock .
5.5.3. PLL The clock PLLCLK
By setting PLL The second harmonic factor of , It can be done to PLL Clock source for frequency doubling , The doubling factor can
yes :[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16], How much to set , Register configuration by clock CFGR Bit 21-18:
PLLMUL[3:0] Set up . We set it here to 9 frequency doubling , Because in the last step we set up PLL The source of the clock is HSE=8M,
So after PLL After frequency doubling PLL The clock :PLLCLK = 8M *9 = 72M.72M yes ST Official recommended stable operation time
The clock , If you want to overclock , Increase the frequency doubling factor , Up to 128M. We set up PLL The clock :PLLCLK = 8M
*9 = 72M.
5.5.4. The system clock SYSCLK
The system clock source can be :HSI、PLLCLK、HSE, Specific clock configuration registers CFGR Bit 1-0:SW[1:0]
Set up . We set the system clock here :SYSCLK = PLLCLK = 72M.
5.5.5. AHB Bus clock HCLK
The system clock SYSCLK after AHB After the prescaler divides the frequency, the clock is called APB Bus clock , namely HCLK, Frequency division factor
It can be :[1,2,4,8,16,64,128,256,512], Specifically, the register is configured by the clock CFGR Bit 7-4 :HPRE[3:0]
Set up . Most of the peripherals on the chip are clocked by HCLK Divide the frequency to get , as for AHB How many clocks are set for the peripherals on the bus ,
We have to wait until we use the peripheral to set , We just need to set the bold line here APB That's enough . We have
Set as 1 frequency division , namely HCLK=SYSCLK=72M.
5.5.6. APB2 Bus clock HCLK2
APB1 APB2 Bus clock PCLK2 from HCLK Through high speed APB2 The prescaler gets , The frequency division factor can
yes :[1,2,4,8,16], The register is configured by the clock CFGR Bit 13-11:PPRE2[2:0] decision .HCLK2 It's high speed
Bus clock , On chip high-speed peripherals are mounted on this bus , Like all of them GPIO、USART1、SPI1 etc. . as for APB2
How many clocks are set for the peripherals on the bus , We have to wait until we use the peripheral to set , We just need to set the bold line here
APB2 That's enough . We set it here to 1 frequency division , namely PCLK2 = HCLK =72M.
The first 5 Chapter .STM32 RCC The clock system
The first 46 page SAIUR2016
5.5.7. Bus clock HCLK1
APB1 Bus clock PCLK1 from HCLK After low speed APB The prescaler gets , The division factor can be :[1,2,4,8,16],
Specifically, the register is configured by the clock CFGR Bit 10-8:PRRE1[2:0] decision .HCLK1 It's a low speed bus clock , Up to
36M, The low-speed peripherals on the chip are mounted on this bus , such as USART2/3/4/5、SPI2/3,I2C1/2 etc. . as for APB1 total
How many clocks are set for the peripherals on the line , We have to wait until we use the peripheral to set , We just need to set the bold line here
APB1 That's enough . We set it here to 2 frequency division , namely PCLK1 = HCLK/2 = 36M.
5.6. Set the system clock library function
above 7 The corresponding function of setting system clock library is as follows , This function intercepts from the firmware library file
system_stm32f10x.c. For ease of reading , I have deleted the code related to interconnection , Translate English notes into Chinese , And put
The code is numbered , There are seven steps . This function operates the register directly , For the register section, please refer to the data manual RCC
The register description part of .
Code 5-1 Set the system clock library function
The first 5 Chapter .STM32 RCC The clock system
SAIUR201 6 The first 47 page
5.7. Other clocks
Through the explanation of system clock setting , We've got 60% or 70% of the whole clock tree , The rest of the clock is about a few
Important .
5.7.1. USB The clock
USB The clock is made up of PLLCLK after USB The prescaler gets , The division factor can be :[1,1.5], Specifically, it is configured by the clock
register CFGR Bit 22:USBPRE To configure .USB The highest clock is 48M, According to the frequency division factor, it can be calculated ,PLLCLK
Can only be 48M Or is it 72M . Generally we set PLLCLK=72M , USBCLK=48M.USB The clock requirements are quite different
high , therefore PLLCLK Only by HSE Multiply the frequency to get , Out of commission HSI frequency doubling .
5.7.2. Cortex The system clock
Cortex The system clock is controlled by HCLK 8 Divide the frequency to get , be equal to 9M,Cortex The system clock is used to drive the system timer of the kernel
SysTick,SysTick Generally used for operating system clock beat , It can also be used for ordinary timing .
The first 5 Chapter .STM32 RCC The clock system
The first 48 page SAIUR2016
5.7.3. ADC The clock
ADC Clock by PCLK2 after ADC The prescaler gets , The division factor can be [2,4,6,8], The details are sent by the clock configuration
Memory CFGR Bit 15-14:ADCPRE[1:0] decision . It's strange that there's no 1 frequency division .ADC The clock can only be
14M, If the sampling period is set to the shortest 1.5 In a cycle ,ADC The conversion time is the shortest 1us. If you really want to
Achieve the shortest conversion time 1us Words , that ADC Your clock has to be 14M, Back to PCLK2 My clock can only be :28M、56M、
84M、112M, Whereas PCLK2 Is the highest 72M, So we can only take 28M and 56M.
5.7.4. RTC The clock 、 Independent watchdog clock
RTC The clock can be controlled by HSE/128 Divide the frequency to get , It can also be controlled by low speed external clock signal LSE Provide , The frequency is 32.768KHZ, also
It can be controlled by low speed internal clock signal HSI Provide , Which clock to select is controlled by the backup domain BDCR Bit 9-8:
RTCSEL[1:0] To configure . The clock of the independent watchdog is made up of LSI Provide , And only by LSI Provide ,LSI It's a low-speed internal clock
Number , The frequency is 30~60KHZ Not directly , Usually take 40KHZ.
5.7.5. MCO Clock output
MCO yes microcontroller clock output Abbreviation , Is the microcontroller clock output pin , stay STM32 F1 In the series by
PA8 The result of reuse , The main function is to provide external clock , It's equivalent to an active crystal oscillator .MCO The source of the clock can be :
PLLCLK/2 、HSI、HSE 、SYSCLK , Which register to select is configured by the clock CFGR Bit 26-24:MCO[2:0]
decision . In addition to the function of providing external clock , We can also monitor it with an oscilloscope MCO The clock output of the pin verifies me
Is your system clock configured correctly .
5.8. Configure the system clock experiment
5.8.1. Use HSE
In general , We all use HSE, then HSE after PLL After frequency doubling, it is used as the system clock . The usual configuration is :
HSE=8M,PLL The frequency doubling factor of is :9, The system clock is set to :SYSCLK = 8M * 9 = 72M. Use HSE, The system clock
SYSCLK Is the highest 128M. That's what the library functions we use do , When the program comes to main Function before , Startup file :
statup_stm32f10x_hd.s Has called SystemInit() Function to initialize the system clock to 72MHZ,SystemInit() In the library file :
system_stm32f10x.c In the definition of . If we want to set the system clock lower or overclock , You can modify the underlying library files ,
But to maintain the integrity of the library , We can write one by ourselves according to the process of the clock tree .
5.8.2. Use HSI
HSE When it breaks down , If PLL The source of my clock is HSE, So when HSE When it breaks down , Not only HSE Can't make
use , even PLL It will also be shut down , At this time, the system will switch automatically HSI As a system clock , here SYSCLK=HSI=8M, Such as
If it doesn't open CSS and CSS interrupts , Then the whole system can only run at low speed , It's a system. It's like paralysis .
The first 5 Chapter .STM32 RCC The clock system
SAIUR201 6 The first 49 page
If it's on CSS Function words , Then you can be HSE When it breaks down , stay CSS Take remedial measures , Use HSI,
And set the system clock to a higher frequency , Is the highest 64M, 64M The frequency is enough for general peripherals , Such as :ADC 、SPI、
I2C etc. . But here's another problem , original SYSCLK=72M, Now it's changed to 64M, So the peripherals
My clock must have been changed , Then peripheral work will be disrupted , So are we setting up HSI Clock time , And readjust
The frequency division factor of the whole peripheral bus , namely AHB,APB2 and APB1 The frequency division factor of , Make the clock of peripherals reach to HSE No reason
Just like before . But this is not the most secure way , After all, it can't be used all the time HSI, So when HSE In case of failure, we still need to adopt
Take alarm measures . There is another case , Some users don't want to use HSE, Want to use HSI, But I don't know how to use it HSI To set up
The system clock , Because all library functions are called using HSE, Let's show you how to use HSI Example of configuring the system clock , Throw a brick
The function of leading jade .
5.8.3. Hardware design
1、RCC
2、LED One
RCC It is the internal resource of MCU , No external circuits are needed . adopt LED Flash frequency to intuitively judge the clock frequency of different systems
The effect of rate on software delay .
5.8.4. software design
We write two RCC Driver file ,bsp_clkconfig.h and bsp_clkconfig.c, For storage RCC System clock configuration
function .
5.8.5. Programming points
Programming points correspond to the serial number in the clock tree .
1、 Turn on HSE/HSI , And wait for HSE/HSI Stable
2、 Set up AHB、APB2、APB1 The prescaler factor of
3、 Set up PLL The source of the clock , and PLL The second harmonic factor of , Setting various frequencies is mainly set here
4、 Turn on PLL, And wait for PLL Stable
5、 hold PLLCK Switch to system clock SYSCLK
6、 Read clock switch status bit , Make sure PLLCLK Selected as the system clock
5.8.6. The code analysis
Here is just the core part of the code , Some variable settings , The inclusion of header files does not involve , Please refer to the complete code
The supporting projects in this chapter . Use HSE Configure the system clock
The first 5 Chapter .STM32 RCC The clock system
The first 50 page SAIUR2016
Code 5-2 HSE As a system clock source
The first 5 Chapter .STM32 RCC The clock system
SAIUR201 6 The first 51 page
This function is written in library functions , Function has a parameter pllmul,pllmul Used to set PLL The second harmonic factor of , In the call of the
The formal parameter can be :RCC_PLLMul_x , x:[2,3,...16], These macros come from the definition of library functions , Macro expansions are some 32 Bit
Hexadecimal number , The specific function is to configure the clock configuration register CFGR Bit 21-18 PLLMUL[3:0], Define the multiplier factor in advance
Son , Convenient to call . Function call examples :HSE_SetSysClock(RCC_PLLMul_9); Set the system clock to :8MHZ * 9 =
72MHZ.HSE_SetSysClock(RCC_PLLMul_16); Set the system clock to :8MHZ * 16 = 128MHZ Use it with caution .
Code 5-3 practical HSI Configure the system clock
The first 5 Chapter .STM32 RCC The clock system
The first 52 page SAIUR2016
HSI Set up
System clock function HSE Setting the system clock function is the same in principle , One difference is that ,HSI must 2 branch
Only after frequency can we act as PLL The source of the clock , So use HSI when , Maximum system clock SYSCLK Can only be
HSI/2*16=4*16=64MHZ. Function call examples :HSI_SetSysClock(RCC_PLLMul_9); Set the system clock to :4MHZ
* 9 = Use HSI Configure the system clock 36MHZ. Software delay
Software delay function , Using different system clocks , The delay time is different , Can pass LED The frequency of the flicker .
MCO Output
stay STM32F103 In the series ,PA8 It can be reused as MCO Pin , Provide external clock output , We can also use an oscilloscope
Monitor the output of this pin to determine whether our system clock is set correctly .
The first 5 Chapter .STM32 RCC The clock system
SAIUR201 6 The first 53 page
Code 5-4 MCO GPIO initialization
Code 5-5 MCO Output clock selection
We initialize MCO After the pin , You can call library functions directly RCC_MCOConfig() Choose MCO Clock source . Lord
Functions like code 5-5
The first 5 Chapter .STM32 RCC The clock system
The first 54 page SAIUR2016
Code 5-5 The main function
In the main function , You can call HSE_SetSysClock() perhaps HSI_SetSysClock() These two functions set the system clock to
All kinds of commonly used clocks , And then through MCO Pin monitoring , Or by LED Flash fast and slow experience different system clocks on the same
The influence of a software delay function .
5.8.7. Download validation
Download the compiled program to the development board , You can see when setting different system clocks ,LED The speed of flashing is different . More refined
We can monitor the exact data with an oscilloscope MCO I can see .
chart 5-2 MCO=SYSCLK=72M chart 5-3 MCO=HSI=8M
The first 6 Chapter .STM32 Interrupt application overview
SAIUR201 6 The first 55 page
The first 6 Chapter . STM32 Interrupt Application Overview
6.1. Preview before class
Find the answer in the book .
1. What is an interrupt controller ?
2. How to configure NVIC register
6.2. summary
What's in this chapter :
(1)NVIC Introduction to
(2)NVIC Configuration method of
STM32 Interruptions are very powerful , Every peripheral can generate an interrupt , So it's hard to tell which peripherals the interrupted explanation should be placed in
Don't fit , Here is a separate chapter to make a summary introduction , In this way, we don't know about interruptions in other chapters
It takes a lot of time to explain , As long as you show it by hand . Unless otherwise specified in this chapter , An exception is an interrupt , An interrupt is an exception , please
Don't try to compete .
6.3. Exception types
STM32F103 There is an exception response system on the kernel level , Supports a large number of system exceptions and external interrupts . Its
There are some exceptions in the system 8 individual ( If you put Reset and HardFault In addition, it is 10 individual ), External interruptions are 60 individual . except
Individual exceptions are prioritized , The priority of other exceptions is programmable . Specific system exceptions and external interrupts can be marked
Quasi library files stm32f10x.h This header finds , stay IRQn_Type This structure contains F103 All the differences in the series
It is often stated that .
form 6-1 F103 System exception list
The first 6 Chapter .STM32 Interrupt application overview
The first 56 page SAIUR2016
form 6-2 F103 External interrupt list
6.4. NVIC brief introduction
Before we talk about how to configure interrupt priority , We need to know something about NVIC.NVIC It's a nested vector interrupt controller , Controls the
Interrupt related functions of the whole chip , It's tightly coupled to the kernel , It's a peripheral in the kernel . But chip manufacturers are designing chips
It will be right Cortex-M3 In the kernel NVIC Tailoring , Get rid of what you don't need , So STM32 Of NVIC
yes Cortex-M3 Of NVIC A subset of .
6.5. NVIC Register Introduction
In the firmware library ,NVIC The definition of "structure" is far sighted , Many bits are reserved for each register , I'm afraid it's for Japan
Post expansion function . however STM32F103 Not so much , It's just part of it , How much is used can be referred to
The first 6 Chapter .STM32 Interrupt application overview
SAIUR201 6 The first 57 page
《Cortex-M3 Kernel programming manual 》-4.3.11:NVIC Register mapping .
Code 6-1 NVIC Structure definition , From the firmware library header file :core_cm3.h
When configuring interrupts, we usually only use ISER、ICER and IP These three registers ,ISER Used to enable interruption ,ICER use
To disable the interruption of ,IP Used to set interrupt priority .
6.6. NVIC Interrupt configuration firmware library
Firmware library file core_cm3.h Last , It also provides NVIC Some functions of , These functions follow CMSIS The rules , only
If Cortex-M3 All processors can use , As follows :
form 6-3 accord with CMSIS The standard NVIC Library function
We use less of these library functions when programming , Not even at all . We have a simpler way to configure interrupts
Methods , See the interrupt programming section .
The first 6 Chapter .STM32 Interrupt application overview
The first 58 page SAIUR2016
6.7. Definition of priority
6.7.1. Priority definition
stay NVIC There is a special register : Interrupt priority register NVIC_IPRx, Used to configure the priority of external interrupts ,IPR
Width is 8bit, In principle, the configurable priority of each external interrupt is 0~255, The smaller the numerical , The higher the priority . But the vast majority
CM3 Chips will be streamlined , So that the number of priorities actually supported decreases , stay F103 in , Only high 4bit, As shown below :
form 6-4 F103 Use 4bit Express priority
This is used to express priority 4bit, It is divided into preemptive priority and sub priority . If there are multiple interrupts responding at the same time , preemption
The high priority will preempt, and the low priority will be executed , If the preemption priority is the same , Just compare sub priorities . If you rob
If the priority and sub priority are the same , Compare their hardware interrupt numbers , The smaller the number , The higher the priority .
6.7.2. Priority groups
Priority grouping is done by kernel peripherals SCB Application interrupt and reset control register AIRCR Of
PRIGROUP[10:8] Bit decided ,F103 Divided into 5 Group , As follows : Primary priority = preemption
form 6-5 Priority table
Set priority groups to call library functions NVIC_PriorityGroupConfig() Realization , of NVIC Interrupt related library functions
It's all in the library misc.c and misc.h in .
form 6-7 Priority group truth table
The first 6 Chapter .STM32 Interrupt application overview
SAIUR201 6 The first 59 page
Code 6-2 Interrupt priority group library function NVIC_PriorityGroupConfig()
6.8. Interrupt programming
When configuring each interrupt, there are usually 3 A programming point :
1. Enable a peripheral interrupt , This is controlled by the interrupt enable bit of each peripheral . For example, the serial port has send complete interrupt , Pick up
Collection completion interrupt , Both interrupts are controlled by the related interrupt enable bit of the serial port control register .
2. initialization NVIC_InitTypeDef Structure , Configure interrupt priority grouping , Set preemption priority and sub priority , In enabling
Cut off the request .NVIC_InitTypeDef The structure is in the firmware library header file misc.h In the definition of .
Code 6-3 NVIC Initialize structure
of NVIC Initialization structure members, let's explain one by one :
NVIC_IROChannel: Used to set the interrupt source , Different interrupt sources are different , And don't make mistakes , Even if you write the wrong program, it won't
Report errors , Will only result in no response interrupt . Please refer to stm32f10x.h In the header file IRQn_Type Structure determination
The righteous , This structure contains all interrupt sources .
Code 6-4 IRQn_Type Interrupt source structure
The first 6 Chapter .STM32 Interrupt application overview
The first 60 page SAIUR2016
NVIC_IRQChannelPreemptionPriority: preemption , The specific value should be determined according to the priority group ..
NVIC_IRQChannelSubPriority: Sub priority , The specific value should be determined according to the priority group , Please refer to the table for details 17-5 optimal
First group truth table .
NVIC_IRQChannelCmd: Interrupt enable (ENABLE) Or disability (DISABLE). The operation is NVIC_ISER and
NVIC_ICER These two registers .
3. Write interrupt service function
In the startup file startup_stm32f10x_hd.s We write an interrupt service function for each interrupt in advance , That's all
All interrupt functions are empty , To initialize the interrupt vector table . The actual interrupt service functions need to be rewritten , For the sake of prescription
So we write the interrupt service function in stm32f10x_it.c In this library file . The function name of the interrupt service function must be
It's the same as the preset in the boot file , If you write wrong , The system can't find the entry of the interrupt service function in the interrupt vector table , straight
Then jump to the empty function written in advance in the startup file , And it circulates infinitely inside , There's no interruption .
6.9. Practice after class
1、 The library files core_cm3.h What has been achieved ?
2、 The library files mics.c and mics.h What has been achieved ?
3、 If a software system reset is realized , Specifically, the implementation of which bit of which register to operate ?
The first 7 Chapter .EXTI- External interrupt / Event controller
SAIUR201 6 The first 61 page
The first 7 Chapter . EXTI— External interrupt / Event controller
7.1. Preview before class
Find the answer in the book .
1. EXTI How many kinds? ?
2. How to use standard library configuration EXTI
7.2. summary
What's in this chapter :
(1)EXTI Introduction to
(2)EXTI Configuration method of
In the last chapter we have described in detail NVIC, Yes STM32F10x Series interrupt management system has a global understanding , We
The content of this chapter is NVIC An example application of , It's also STM32F10x Controller is a very important resource . When learning this chapter , with
close 《STM32F10X- Chinese Reference Manual 》 Read the interrupt and events section together , The effect will be better , Especially when it comes to register descriptions
part .
7.3. EXTI brief introduction
EXTI(External interrupt/event controller)— External interrupt / Event controller , Managed the controller's 20 A break / things
Piece line . Every interrupt / Each event line has an edge detector , It can detect the rising edge and falling edge of the input signal .
EXTI It can be implemented for each interrupt / Event lines are configured separately , It can be configured separately as interrupt or event , And the genus that triggers the event
sex .
7.4. EXTI Functional block diagram
EXTI The functional block diagram of contains EXTI The core content , Master the functional block diagram , Yes EXTI There is an overall grasp of ,
When programming, the idea is very clear .EXTI The functional block diagram is shown in the figure 7-1. In the figure 18-1 You can see a lot of people putting a slash on the signal line
And mark “20” word , This indicates that there are similar signal lines in the controller 20 individual , This is related to EXTI All in all 20 A break / things
Edited by Mr. Chen Dejin
The first 7 Chapter .EXTI- External interrupt / Event controller
The first 62 page SAIUR2016
The lines match . So we just need to understand the principle of one of them , The others 19 The principle of a circuit is also known .
chart 7-1 EXTI Functional block diagram
EXTI It can be divided into two major functions , One is to generate interrupts , The other is the generation of events , These two functions are different in hardware
Same as . First, let's look at the picture 18-1 The red dotted line indicates the circuit flow . It's a line that breaks , Finally, the signal flows into
NVIC In the controller . Number 1 It's the input line ,EXTI The controller has 19 A break / Event input line , These input lines can be sent to
The memory is set to any GPIO, It can also be peripheral events , This part will be explained later . Input line one
Generally, there is a change in the level of the signal . Number 2 It's an edge detection circuit , It triggers the selection register based on the rising edge (EXTI_RTSR)
And falling edge trigger select register (EXTI_FTSR) The setting of the corresponding bit controls the signal triggering . The edge detection circuit takes the input line as the signal
Input end , If edge jump is detected, an effective signal is output 1 Number 3 circuit , Otherwise, invalid signal will be output 0. and
EXTI_RTSR and EXTI_FTSR Two registers can be used to determine which type of level jump the controller needs to detect , It can only be on
The rising edge triggers 、 Only the falling edge triggers or both the rising edge and the falling edge trigger . Number 3 A circuit is actually an OR gate circuit , It's one
Enter the number from 2 circuit , The other input comes from the software interrupt event register (EXTI_SWIER).EXTI_SWIER Allow me to
We can start interrupt by program control / Event line , It's very useful in some places . We know that the function of or gate is to have 1 for
1, So either of these two inputs has a valid signal 1 You can output 1 Number 4 And number 6 circuit . Number 4 The circuit is a
And gate circuit , One of its inputs is the number 3 circuit , The other input is from the interrupt mask register (EXTI_IMR). And gate circuit to
All the inputs are 1 Just output 1, The result is if EXTI_IMR Set to 0 when , No matter the number 3 The output signal of the circuit
Number is 1 still 0, Final number 4 The output signal of the circuit is 0; If EXTI_IMR Set to 1 when , Final number 4 electric
The output signal is numbered by 3 The output signal of the circuit determines , So we can simply control EXTI_IMR To realize whether or not to produce
The purpose of life . Number 4 The output signal of the circuit is stored in the suspend register (EXTI_PR) Inside , If you are sure of the number 4 Circuit output
Out for 1 It will EXTI_PR Corresponding position 1. Number 5 Yes, it will EXTI_PR The contents of the register are output to NVIC Inside , So as to realize
Now system interrupt event control . Next, let's look at the circuit flow indicated by the green dotted line . It's a circuit of events , Final
The first 7 Chapter .EXTI- External interrupt / Event controller
SAIUR201 6 The first 63 page
Output a pulse signal . The event line is numbered 3 After the circuit and interrupt the line is different , Before, the circuits were all shared .
Number 6 A circuit is an and gate , It's an input from the number 3 circuit , The other input comes from the event mask register
(EXTI_EMR). If EXTI_EMR Set to 0 when , No matter the number 3 The output signal of the circuit is 1 still 0, Final edition
Number 6 The output signal of the circuit is 0; If EXTI_EMR Set to 1 when , Final number 6 The output signal of the circuit is numbered by
3 The output signal of the circuit determines , So we can simply control EXTI_EMR To achieve the purpose of whether an event occurs . Number 7 yes
A pulse generator circuit , When its input , I.e. number 6 The output of the circuit , It's a valid signal 1 And then there's a
pulse ; If the input is invalid, the pulse will not be output . Number 8 It's a pulse signal , It's the line that produced the event, the final
product , This pulse signal can be used by other peripheral circuits , Like timers TIM、 Analog to digital converter ADC wait , such
The pulse signal is usually used to trigger TIM perhaps ADC Start conversion . The purpose of generating the interrupt line is to input the input signal to NVIC,
The next step is to run the interrupt service function , Realization function , This is software level . And the purpose of the event line is to transmit a pulse signal
For other peripherals , And it's circuit level signal transmission , At the hardware level . in addition ,EXTI Is in APB2 On the bus ,
You need to pay attention to this when programming .
7.5. interrupt / Event line
EXTI Yes 20 A break / Event line , Every GPIO Can be set as input lines , Occupy EXTI0 to EXTI15, There's something else
Seven for specific peripheral events , See table 7-1.4 Root specific peripheral interrupt / Event lines are triggered by peripherals .
surface 7-1 EXTI interrupt / Event line
EXTI0 to EXTI15 be used for GPIO, Any one of them can be realized by programming control GPIO As EXTI The input source .
Edited by Mr. Chen Dejin
The first 7 Chapter .EXTI- External interrupt / Event controller
The first 64 page SAIUR2016
By the table 7-1 You know ,EXTI0 Can pass AFIO External interrupt configuration register for 1(AFIO_EXTICR1) Of EXTI0[3:0] Biting
Select the configuration as PA0、PB0、PC0、PD0、PE0、PF0、PG0、PH0 perhaps PI0, See the picture 7-2. other EXTI Line (EXTI in
break / Event line ) Using configuration is similar .
chart 7-2 EXTI0 Input source selection
7.6. EXTI Initialization structure details
The standard library function creates an initialization structure for each peripheral , such as EXTI_InitTypeDef, Structure members are used to set
Set the working parameters of peripheral devices , The configuration function is initialized by the peripheral , such as EXTI_Init() call , These setting parameters will set the peripheral corresponding
The register of , To achieve the purpose of configuring the working environment of peripherals . The combination of initialization structure and initialization library function is the essence of standard library ,
After understanding the meaning of each member of the initialization structure, you can basically use the peripheral freely . The initialization structure is defined in
stm32f10x_exti.h In file , Initialization library functions are defined in stm32f10x_exti.c In file , When programming, we can combine these two
In file comments use .
Code list 7-1 EXTI Initialize structure
EXTI_Line:EXTI interrupt / Event line selection , Optional EXTI0 to EXTI19, Refer to table 7-1 choice .
EXTI_Mode : EXTI Mode selection , The option is to generate an interrupt (EXTI_Mode_Interrupt) Or an event
(EXTI_Mode_Event).
EXTI_Trigger:EXTI Edge triggered events , Optional rising edge trigger (EXTI_Trigger_Rising)、 Falling edge trigger
( EXTI_Trigger_Falling) Or both rising and falling edges trigger ( EXTI_Trigger_Rising_Falling).
EXTI_LineCmd: Control whether to enable EXTI Line , Optional enable EXTI Line (ENABLE) Or disable (DISABLE).
The first 7 Chapter .EXTI- External interrupt / Event controller
SAIUR201 6 The first 65 page
7.7. External interrupt control experiment
Interrupt plays a very important role in embedded applications , Almost every controller has interrupt function . Interruptions are important to ensure that emergencies
It's very important to get dealt with in the first place . We design to use external buttons as trigger source , Cause the controller to interrupt , And in
Interrupt service function to achieve control RGB The task of the Lantern .
7.7.1. Hardware design
Tap the button to turn the pin on when pressed , Through the circuit design, we can make the level change when we press it , See the picture 7-3.
chart 7-3 Key circuit design
7.7.2. software design
Here is just the core part of the code , Some variable settings , The inclusion of header files does not involve , For complete code, please refer to
Consider the supporting projects in this chapter . We created two files :bsp_exti.c and bsp_exti.h Files are used to hold EXTI Driver and phase
The definition of Guan Hong , The interrupt service function is placed in stm32f10x_it.h In file .
7.7.3. Programming points
1. Initialization is used to generate interrupts GPIO;
2. initialization EXTI;
3. To configure NVIC;
4. Write interrupt service function ;
7.7.4. The code analysis
Use macro definition method to specify configuration related to hardware circuit design , This is very useful for program migration or upgrade . The macro above
In righteousness , In addition to driving GPIO Out of the port clock , We've opened it AFIO The clock of , That's because wait for configuration EXTI The signal
We need to use AFIO External interrupt control register of AFIO_EXTICRx, Specific view 《STM32F10X- Chinese reference hand
book 》8.4 chapter AFIO Register description . Nested vector interrupt controller NVIC Configure the NVIC Please refer to 《STM32
Interrupt Application Overview 》 Chapter content , There's not much to explain here . Here we configure two interrupt software with the same priority , If it does
When two buttons are pressed at the same time , What to do with that , Which interrupt should be executed ? When the software priority of two interrupts is the same ,
Edited by Mr. Chen Dejin
The first 7 Chapter .EXTI- External interrupt / Event controller
The first 66 page SAIUR2016
When the interruption comes , Which interrupt service function to execute first depends on the interrupt number of the hardware , The smaller the number , The higher the priority . About peripherals
The hardware number of can be queried 《STM32F10X- Chinese Reference Manual 》 The vector table in the interrupts and events section of , The position number in the table is
Is the hardware interrupt priority of each peripheral . Of course , We can also set preemption priority to the same , The sub priority is set to different ,
In this way, we can distinguish the situation when two buttons are pressed at the same time , Instead of comparing hardware numbers with hardware numbers .
Code list 7-2 Keys and EXTI Macro definition
Code list 7-3 NVIC To configure
The first 7 Chapter .EXTI- External interrupt / Event controller
SAIUR201 6 The first 67 page
EXTI Interrupt configuration
Code list 7-4 EXTI Interrupt configuration
First , Use GPIO_InitTypeDef and EXTI_InitTypeDef Structure defines two functions for GPIO and EXTI initialization
Configuration variables , The two structures have been explained in detail . Use GPIO It has to be turned on before GPIO Port of
The clock ; be used EXTI Must be turned on AFIO The clock . call NVIC_Configuration Function to complete the key 1、 Key 2 optimal
First configure and enable interrupt channel . As an interruption / Input line of events GPIO Configured as input mode , Specific for the floating input , from
The external circuit completely determines the state of the pin .GPIO_EXTILineConfig Function to specify the interrupt / The input source of the event line , It's actually
Edited by Mr. Chen Dejin
The first 7 Chapter .EXTI- External interrupt / Event controller
The first 68 page SAIUR2016
Set the value of the external interrupt configuration register AFIO_EXTICRx value , This function takes two arguments , The first parameter specifies GPIO port
Source , The second parameter is selection correspondence GPIO Pin source number . Our goal is to create disruption , Execute the interrupt service function ,EXTI choose
Select interrupt mode , Key 1 Use rising edge trigger mode , And enable EXTI Line . Key 2 Basically, it's the same as the buttons 1 Related parameters
To configure , It's just changed to the falling edge trigger mode . The circuit of the two buttons is the same , But in the code, we set the key 1 It's the rising edge interruption ,
Key 2 It's a falling edge interrupt , Some people will ask if this is wrong ? In fact, it can be understood that , Key 1 It's a keystroke
State of , Key 2 It detects the status of the button's bouncing off , That makes sense .
Code list 7-5 EXTI Interrupt service function
When the interrupt occurs , The corresponding interrupt service function will be executed , We can implement some control in the interrupt service function . It's usually
Make sure the interruption does happen , In the interrupt service function, we call the interrupt flag status read function to read the interrupt sign bits of the peripheral and judge
Flag bit status .EXTI_GetITStatus Function to get EXTI Interrupt flag bit status of , If EXTI There is a break in the line
Number return “ SET ” Otherwise return to “ RESET ” . actually , EXTI_GetITStatus Function by reading EXTI_PR
Register value EXTI Line state . Key 1 Let's use the interrupt service function of LED1 Flip its state , Key 2 The interrupt
Service function let's LED2 Flip its state . After executing the task, you need to call EXTI_ClearITPendingBit Function cleanup EXTI Line
Interrupt flag bit of . The main function
Code list 7-6 The main function
The main function is very simple , There are only two task functions .LED_GPIO_Config Function defined in bsp_led.c In the file , complete RGB
The first 7 Chapter .EXTI- External interrupt / Event controller
SAIUR201 6 The first 69 page
The color of the lantern GPIO Initialize configuration .EXTI_Key_Config Function to complete the two buttons GPIO and EXTI To configure .
7.7.5. Download validation
Ensure that the development board hardware connection is correct , Download the compiled program to the development board . here RGB The color light is dark , If
We press the button on the development board 1,RGB The lights go on , Press the button again 1,RGB The lights went dark again ; If we press development
The buttons on the board 2 And flick it away ,RGB The lights go on , And then press... On the development board KEY2 And flick it away ,RGB The lights went dark again . Key
Press to indicate rising edge , When the button pops open, it means the falling edge , This is the same as our software settings .
7.8. Practice after class
1、 Whether it can be used at the same time PA0 and PB0 interrupt ? If not , What's the solution .
2、 From the hardware point of view, combined with program analysis , Why press the button 1RGB The lights change right away , And the buttons 2 But you need to press
After the button is flicked off again RGB The lights change ?
The first 8 Chapter .SysTick System timer
The first 70 page SAIUR2016
The first 8 Chapter . SysTick System timer
8.1. Preview before class
Find the answer in the book .
1. SysTIck What's the difference from the system clock ?
8.2. summary
What's in this chapter :
(1)SysTick Description and use of
8.3. SysTick brief introduction
SysTick— The system timer belongs to CM3 A peripheral in the kernel , Embedded in NVIC in . The system timer is a 24bit
A counter that decrements downward , The counter counts every time for 1/SYSCLK, Generally, we set the system clock SYSCLK be equal to
72M. When the value of the reload value register is decremented to 0 When , The system timer generates an interrupt , And so on . because
SysTick It belongs to CM3 Peripherals of kernel , So all based on CM3 All the single chip microcomputers in the kernel have this system timer , bring
Software in CM3 MCU can be easily transplanted . System timers are generally used for operating systems , Used to generate time bases , Maintain operation
The heartbeat of the system .
8.4. SysTick Register introduction
SysTick— The system timer has 4 A register , The brief introduction is as follows . In the use of SysTick When timing occurs , Need configuration
The first three registers , The last calibration register does not need to be used .
surface 8-1 SysTick Register summary
The first 8 Chapter .SysTick System timer
SAIUR201 6 The first 71 page
surface 8-2 SysTick Control and status register
surface 8-3 SysTick Reload the load value register
surface 8-4 SysTick Current value register
The first 8 Chapter .SysTick System timer
The first 72 page SAIUR2016
surface 8-5 SysTick Current value register
The calibration value register of the system timer does not need to be used in the timing experiment . For the description of each bit, please refer to the English in the manual
Text version , It's more obscure , I don't know what this register is used for . Friends who have studied can communicate with each other , Let's throw a brick to attract jade
The role of .
8.5. SysTick Timing experiments
utilize SysTick produce 1s Time base of ,LED With 1s The frequency of the flash .
8.5.1. Hardware design
SysTick It belongs to the peripheral device inside the single chip microcomputer , No need for additional hardware circuits , There's only one left LED Just light up .
8.5.2. software design
Here is just the core part of the code , Some variable settings , The inclusion of header files does not involve , For complete code, please refer to
Consider the supporting projects in this chapter . We created two files :bsp_SysTick.c and bsp_ SysTick.h Files are used to hold SysTick drive
Dynamic program and related macro definition , The interrupt service function is placed in stm32f10x_it.h In file .
8.5.3. Programming points
1、 Set the value of the reload register
2、 Clear the value of the current value register
3、 Configure control and status registers
The first 8 Chapter .SysTick System timer
SAIUR201 6 The first 73 page
8.5.4. The code analysis
SysTick Peripherals that belong to the kernel , The register definitions and library functions are in the kernel related library files core_cm3.h in .
SysTick Configure library functions
Code 8-1 SysTick Configure library functions
When programming with the firmware library, we just need to call the library function SysTick_Config() that will do , Shape parameter ticks Used to set up reload
The value of the memory , The maximum cannot exceed the value of the reload register 224, When the value of the reload register decrements to 0 There's an interruption when it's time , however
After reloading, the value of the register is reloaded and counted down , And so on . Next, set the interrupt priority , Final configuration
The clock of the system timer is equal to AHBCLK=72M, Enable timer and timer interrupt , So the system timer is configured , One
Library functions are done .SysTick_Config() Library functions are mainly configured with SysTick Three registers in :LOAD、VAL and CTRL,
For specific parts, just look at the code comments .
To configure SysTick Interrupt priority
stay SysTick_Config() Library functions also call firmware library functions NVIC_SetPriority() To configure the interrupt priority of the system timer
level , The library function is also in core_m3.h In the definition of , The prototype is as follows :
The function first determines the formal parameters IRQn Size , If it's less than 0, This is a system exception , Priority of system exception
By kernel peripherals SCB The register of SHPRx control , If it is greater than 0 It's an external interrupt , The priority of external interrupt is determined by kernel peripheral
NVIC Medium IPx Register control . because SysTick It belongs to kernel peripherals , It's different from the interrupt priority of ordinary peripherals , did not
There are preemptive priorities and sub priorities . stay STM32F103 in , The interrupt priority of kernel peripherals is determined by the kernel SCB This peripheral is
The first 8 Chapter .SysTick System timer
The first 74 page SAIUR2016
register :SHPRx(x=1.2.3) To configure the . of SHPRx For a detailed description of the register, please refer to 《Cortex-M3 Kernel programming manual 》
4.4.8 chapter . Now let's briefly introduce this register .SPRH1-SPRH3 It's a 32 Bit register , But only through
Byte access , Every time 8 A field controls the interrupt priority configuration of a kernel peripheral . stay STM32F103 in , Only one 7:3 this
The senior four are effective , The lower four didn't use , So the interrupt priority of kernel peripherals can be programmed as :0~15, Only 16 Programmable first
level , The smaller the numerical , The higher the priority . If the software priority configuration is the same , Then number them according to their position in the interrupt vector table
Determine the priority size , The smaller the number , The higher the priority .
surface 8-6 System exception priority field
If you want to change the priority of kernel peripherals , Just modify a field corresponding to the following three registers .
chart 8-1 SHPR1 register
chart 8-2 SHPR2 register
The first 8 Chapter .SysTick System timer
SAIUR201 6 The first 75 page
chart 8-3 SHPR3 register
In the system timer , The configuration priority is (1UL << __NVIC_PRIO_BITS) - 1UL) , Among them, macro
__NVIC_PRIO_BITS by 4, So the calculation is equal to 15, It can be seen that the priority set by the system timer at this time is in the kernel peripherals
The lowest of all , If you want to modify the priority, you can modify this value , The scope is :0~15.
systick And peripherals ? And on chip peripherals just need to use interrupt , that systick The interrupt priority of is the same as that of peripheral
How to set the priority ? Will it be because systick It's the peripherals in the kernel , So its interrupt priority must be higher than that outside the kernel
Peripherals have high priority ?
from 《STM32 Interrupt Application Overview 》 In this chapter we know , When peripheral sets interrupt priority , First of all, we need to group , then
Set preemption priority and sub priority . and systick When configuring the peripherals of this kind of kernel , Just configure a register ,
The value range is 0~15. Since the configuration method is different , So how to prioritize the two ? Here's an example . For example, configure a peripheral
The interrupt priority group of is 2, Preemption priority is 1, The sub priority is also 1,systick The priority of is the default configuration of the firmware library 15.
When we compare the interrupt priorities of kernel peripherals and on-chip peripherals , We just need to catch NVIC The interrupt priority grouping of is not only
Works for peripherals on chip , The same is true for kernel peripherals . We put systick The priority of the 15 Converting to a binary value is
1111(0b), Again because NVIC Priority grouping of 2, So the top two 11(0b) Namely 3, The last two 11(0b) It's also 3. nothing
In terms of preemption or sub priority, the priority of peripheral is lower than our set priority . If both software priorities are configured to be the same , that
Compare their hardware numbers in the interrupt vector table , The smaller the number , The higher the priority .
The first 8 Chapter .SysTick System timer
The first 76 page SAIUR2016
SysTick Initialization function
Code 8-2 SysTick Initialization function
SysTick The initialization function is written by the user , It's called in SysTick_Config() This firmware library function , By setting the firmware
Formal parameters of library functions , It determines how much time the system timer takes to produce an interrupt .
SysTick Calculation of interruption time
SysTick The counter of the timer is down , Count the time once TDEC=1/CLKAHB, When reloading
The value in the filter VALUELOAD Reduced to 0 When , The interrupt , We can know the time of one interruption TINT=VALUELOAD *
TDEC= VALUELOAD/CLKAHB , among CLKAHB =72MHZ . If you set VALUELOAD by 72,
The time of one interruption TINT=72/72M=1us. however 1us There's no point in interrupting , The focus of the whole program is on in and out interruptions
了 , There's no time for other tasks .
SysTick_Config() We configure the shape of SystemCoreClock / 100000=72M/100000=720, From just analyzing me
We know that the value of this parameter is eventually written to the reload register LOAD Medium , So we can now put SysTick Timer interrupt
One time TINT=720/72M=10us.
SysTick Calculation of timing time
When the interrupt time is set TINT after , We can set a variable t, It is used to record the number of times to enter the interrupt , So variable t ride
In the time of interruption TINT You can calculate the time that needs to be timed .
The first 8 Chapter .SysTick System timer
SAIUR201 6 The first 77 page
SysTick Timing function
Now let's define a microsecond delay function , The formal parameter is nTime, When you multiply this parameter by the interrupt time TINT should
Give us the delay we need , among TINT We've set it to 10us. For the specific call of this function, just look at the comments .
function Delay_us() We're waiting for TimingDelay by 0, When TimingDelay by 0 The delay time is up . change
The amount TimingDelay Decrement... In interrupt function , namely SysTick Every interrupt is 10us Time for TimingDelay Decrement once .
SysTick Interrupt service function
The interrupt reset function calls another function TimingDelay_Decrement(), The prototype is as follows :
TimingDelay The value of is equal to the value passed in the delay function nTime Value , such as nTime=100000, Then the delay time is equal to
100000*10us=1s.
The first 8 Chapter .SysTick System timer
The first 78 page SAIUR2016
In the main function LED and SysTick, And then in a while In the cycle with 1s The frequency makes LED flashing . another
Outside a more concise timing programming, the above experiment , We used interrupt , And through multiple function calls , We also use global variables
The amount , It's hard to understand , In fact, there is another simpler way to write it . We know ,systick Of counter from reload value
Down to 0 When ,CTRL Bit of register 16:countflag I'll set 1, And read the value of this bit to clear 0, So we can
Delay is achieved by using software query . See code for specific code 8-3 And code 8-4, I'm sure that's the way it's written , beginner
I'm sure I'll prefer , Because it's direct , The routine is shallow .
Code 8-3 systick Microsecond delay
In these two microsecond and millisecond delay functions , We still called SysTick_Config This firmware library function , of
This function is described in the code 19-5 . The supporting code comments can be understood . among SystemCoreClock Is a macro , Big
Xiao Wei 72000000, If you don't want to use this macro , It can also be changed directly to a number .
The first 8 Chapter .SysTick System timer
SAIUR201 6 The first 79 page
8.6. Practice after class
1、 If modified SysTick Interrupt priority of ?
2、 How to calculate SysTick Enter the time of an interruption ?
3、 How to use it SysTick Achieve one 1ms Time delay of ?
The first 9 Chapter .USART- A serial port communication
The first 80 page SAIUR2016
The first 9 Chapter . USART— A serial port communication
9.1. Preview before class
Find the answer in the book .
1. The difference between synchronous and asynchronous ?
2. USART How many pins ?
9.2. summary
What's in this chapter :
(1)USART Introduction to
(2) Use serial port to send and receive data
9.3. Introduction to serial communication protocol
A serial port communication (Serial Communication) It's a very common way of serial communication between devices , Because it's simple and convenient , therefore
Most electronic devices support this mode of communication , Electronic engineers often use this communication mode to output debugging information when debugging equipment .
In Computer Science , Most complex problems can be simplified by layering . For example, the chip is divided into kernel layer and on-chip peripherals ;STM32
The standard library is the software layer between registers and user code . For communication protocols , We also understand it in a hierarchical way , The most basic
The key is to divide it into physical layer and protocol layer . The physical layer specifies that the communication system has mechanical 、 The characteristics of the electronic functional part , Make sure the original number
According to the transmission in physical media . The protocol layer mainly specifies the communication logic , Unify the data packaging of both sender and receiver 、 Unpacking standard . In short, things
The management rules that we use our mouth or our body to communicate , The protocol layer specifies whether we should communicate in Chinese or English . Now we are going to do the following
Explain the physical layer and protocol layer of serial communication protocol .
9.3.1. The physical layer
There are many standards and variations in the physical layer of serial communication , We mainly explain RS-232 standard ,RS-232 The standard mainly stipulates the letter
The purpose of the number 、 Communication interface and signal level standard . Use RS-232 The common communication structure between standard serial port devices is shown in figure 9-1.
The first 9 Chapter .USART- A serial port communication
SAIUR201 6 The first 81 page
chart 9-1 Serial communication structure diagram
In the communication mode above , Two communication devices “DB9 Interface ” The connection between them is established through the serial signal line , Serial signal line
Use in “RS-232 standard ” Transmitting data signals . because RS-232 The level standard signal cannot be directly recognized by the controller , therefore
These signals go through a “ Level conversion chip ” Convert to something the controller can recognize “TTL standard ” The level of the signal , To communicate .
Level standard
According to the level standard used in communication , Serial communication can be divided into TTL Standards and RS-232 standard , See table 9-1.
surface 9-1 TTL Level standard and RS232 Level standard
We know that it is often used in common electronic circuits TTL The level standard of , ideally , Use 5V Represents binary logic 1,
Use 0V To express logic 0; In order to increase the ability of long-distance transmission and anti-interference of serial communication , It USES -15V To express logic 1,+15V
To express logic 0. Use RS232 And TTL The comparison when the level calibration represents the same signal is shown in Fig 8-2.
chart 9-2 RS-232 And TTL Under the level standard, it means the same signal
Because controllers generally use TTL Level standard , So we often use MA3232 Chip pair TTL And RS-232 My letter
The first 9 Chapter .USART- A serial port communication
The first 82 page SAIUR2016
The numbers are converted to each other .
RS-232 The signal line
In the initial application ,RS-232 Serial standards are often used in computers 、 Routing and modem (MODEN, Be commonly called “ cat ”) Between
Communications , In this communication system , Devices are divided into data terminal devices DTE( Computer 、 route ) And data communication equipment DCE( modulation
Mediator ). We use this communication model to explain the connection mode of their signal lines and the function of each signal line . On old desktop computers
There are usually RS-232 The standard COM mouth ( Also known as DB9 Interface ), See the picture 9-3.
chart 9-3 On the computer motherboard COM Port and serial line
Among them, the connection port which leads out the signal line with needle type is called male , The hole type leading out signal line is called female head . In a computer, it usually leads to
Male interface , And in the modem equipment, the lead out is generally the female head , Use the serial port cable in the figure above to connect it to the computer
Come on . Communication time , The signal transmitted in the serial port line is the one explained above RS-232 Standard modulation . In this application ,DB9
The standard signal wire connection method of each pin of male and female in the interface is shown in the figure 9-4 And table 9-2.
The first 9 Chapter .USART- A serial port communication
SAIUR201 6 The first 83 page
chart 9-4 DB9 Standard male and female connections
surface 9-2 DB9 Signal line description ( Male head , For the sake of understanding , Can handle DTE Computers ,DCE It is understood as modulation and mediation
device )
In the table above is the computer side DB9 Male standard connection , Because of the signal between two communication devices (RXD And TXD) Should be
Cross connect , So the modem side DB9 The receiving and transmitting signal connection method of female head is generally opposite to that of male head , When two devices are connected ,
Just use “ Straight through ” You can connect the serial port cable of , See the picture 9-5.
The first 9 Chapter .USART- A serial port communication
The first 84 page SAIUR2016
chart 9-5 The computer is connected to the signal line of the modem
In the serial line RTS、CTS、DSR、DTR And DCD The signal , Using the logical 1 Indicates that the signal is valid , Logic 0 A letter of expression
The number is invalid . for example , When the computer controls DTR Signal lines are represented as logic 1 when , It's to tell the modem at the far end , Ben
The machine is ready to receive data ,0 It's not ready yet . In the current serial communication used in other industrial control , Generally only used
RXD、TXD as well as GND Three signal lines , Direct transmission of data signals , and RTS、CTS、DSR、DTR And DCD The signal
It's all cut out .
9.3.2. Protocol layer
The data packet of serial communication is sent by the sending device through its own TXD Interface to the receiving device RXD Interface . In the serial port communication
In the protocol layer of , Specifies the content of the packet , It starts from the beginning 、 Subject data 、 Check bit and stop bit , Data from both sides of the communication
The packet format must be consistent in order to send and receive data normally , Its composition is shown in the figure 9-6.
chart 9-6 The basic composition of serial data packet
Baud rate
This chapter is mainly about serial asynchronous communication , There is no clock signal in asynchronous communication ( As explained earlier DB9 There's nothing in the interface
There's a clock signal ), So the baud rate needs to be agreed between two communication devices , That is, the length of each symbol , To decode the signal ,
chart 21-6 Each space separated by a dotted line represents a symbol . The common baud rate is 4800、9600、115200 etc. .
Start and stop signals of communication
A packet of serial communication starts with the starting signal , Until the stop signal is over . The starting signal of the data packet consists of a logic 0 Of
Data bits represent , The stop signal of data packet can be controlled by 0.5、1、1.5 or 2 A logic 1 The data bits of the , As long as both parties agree
that will do .
Valid data
Next to the start bit of the packet is the main data content to be transmitted , Also known as valid data , The length of valid data is often
It is agreed that 5、6、7 or 8 Bit length .
The first 9 Chapter .USART- A serial port communication
SAIUR201 6 The first 85 page
data verification
After the valid data , There is an optional data check bit . Because data communication is relatively more vulnerable to external interference, resulting in the transmission of data
There is a deviation , This problem can be solved by adding check bits in the transmission process . There are odd check methods (odd)、 Even check (even)、0 school
Examination (space)、1 check (mark) And no verification (noparity). Odd check requires valid data and check bit “1” The number of is odd , such as
One 8 The valid data of bit length is :01101001, At this time, there are 4 individual “1”, In order to achieve odd check effect , Check bit is “1”, Last
The data to be transmitted will be 8 Bits of valid data plus 1 The total number of check bits is 9 position . Even check and odd check require the opposite , requirement
In frame data and check bits “1” The number of is even , Like data frames :11001010, At this point, the data frame “1” The number of 4 individual , So I
Check bit is “0”.0 Verification is no matter what is in the valid data , The check bits are always “0”,1 The check bit is always “1”.
9.4. STM32 Of USART brief introduction
Universal synchronous asynchronous transceiver (Universal Synchronous Asynchronous Receiver and Transmitter) It's a serial communication
equipment , It can flexibly exchange full duplex data with external devices . Different from USART One more UART(Universal
Asynchronous Receiver and Transmitter), It's in USART On this basis, the synchronous communication function is cut off , Only asynchronous communication .
The simple distinction between synchronous and asynchronous depends on whether the external clock output is required for communication , We usually use serial communication is basically
UART. Serial communication generally transmits data in frame format , It's frame by frame transmission , Each frame contains a starting signal 、 Data and information 、
Stop message , There may also be verification information .USART There are specific provisions for these transmission parameters , Of course, it's not the only one
Parameter values , Many parameter values can be customized , Just to enhance its compatibility .USART Meet external equipment to industry standards NRZ
Requirements of asynchronous serial data format , And a fractional baud rate generator is used , Can provide a variety of baud rates , Make its application more
widely .USART Support synchronous one-way communication and duplex one-way communication ; It also supports lan LIN、 The smart card (SmartCard) agreement
And lrDA( Infrared Data Association ) SIR ENDEC standard .USART Support use DMA, High speed data communication can be realized , of
DMA The specific application will be in DMA Chapter for specific explanation .USART stay STM32 There is nothing more useful than “ Print ” Program information , One
In general, one will be reserved in hardware design USART The communication interface connects to the computer , It can be used in debugging program to put some debugging information
“ Print ” In the computer side of the serial port debugging assistant tool , So as to know whether the program is running correctly 、 If something goes wrong, exactly where it goes wrong and so on .
9.5. USART Functional block diagram
USART The functional block diagram of contains USART The core content , Master the functional block diagram , Yes USART There is a whole
grasp , When programming, the thinking is very clear .USART The functional block diagram is shown in the figure 9-7.
The first 9 Chapter .USART- A serial port communication
The first 86 page SAIUR2016
chart 9-7 USART Functional block diagram
Function pin
TX: Send data output pin .
RX: Receive data input pin .
SW_RX: Data receiving pin , Only for single line and smart card modes , Belongs to the internal pin , No specific external pins .
nRTS: Request to send (Request To Send),n Indicates that the low level is active . If enabled RTS flow control , When
USART When the receiver is ready to receive new data, it will nRTS Turn to low level ; When the receive register is full ,nRTS Will be
Set to high level . This pin is only suitable for hardware flow control .
nCTS: Clear to send (Clear To Send),n Indicates that the low level is active . If enabled CTS flow control , The transmitter is sending
One frame of data is detected before nCTS Pin , If it's low level , Indicates that data can be sent , If it is high level, then after transmitting the current
Stop sending after data frame . This pin is only suitable for hardware flow control .
SCLK: Transmitter clock output pin . This pin is only available in synchronous mode .
USART Pin in STM32F103ZET6 The specific chip distribution is shown in the table 21-3.
surface 9-3 STM32F103VET6 Chip USART Pin
The first 9 Chapter .USART- A serial port communication
SAIUR201 6 The first 87 page
STM32F103VET6 The system controller has three USART And two UART, among USART1 And the clock comes from
APB2 Bus clock , Its maximum frequency is 72MHz, The other four clocks come from APB1 Bus clock , Its maximum frequency is
36MHz.UART It's just the asynchronous transfer function , So there was no SCLK、nCTS and nRTS Function pin .
Data register
USART Data register (USART_DR) Only low 9 Bit effective , And No 9 Whether bit data is valid depends on USART
Control register 1(USART_CR1) Of M Bit settings , When M Position as 0 It means 8 Bit data word length , When M Position as 1 Express 9
Bit data word length , We usually use 8 Bit data word length .USART_DR Contains data that has been sent or received .
USART_DR It actually contains two registers , A writable... Dedicated to sending TDR, A readable device dedicated to receiving
RDR. When sending , Go to USART_DR The written data is automatically stored in TDR Inside ; When reading , towards
USART_DR Reading data will automatically extract RDR data .TDR and RDR It's between the system bus and the shift register .
Serial communication is transmitted bit by bit , Send TDR The contents are transferred to the transmit shift register , Then put the number of shift registers
According to each person sent out , When receiving, the order of each bit received is saved in the receive shift register, and then transferred to RDR.
USART Support DMA transmission , Can achieve high-speed data transmission , Specifically DMA Use will be in DMA Chapter explanation .
controller
USART There's a transmitter that specifically controls the transmission 、 The receiver that controls the reception , And the wake-up unit 、 Interrupt control and so on .
Use USART We need to ask USART_CR1 The register of UE Location 1 Can make USART,UE Bit is used to turn on for
Clock for serial port . Send or receive data word length optional 8 Bit or 9 position , from USART_CR1 Of M Bit control . transmitter
When USART_CR1 The transmit enable bit of the register TE Set up 1 when , Start data transmission , The data of the transmit shift register will be in TX
Pin out , Little Endian , High position behind . If it's synchronous mode SCLK Also output clock signal . It takes three to send a character frame
part : Start bit + Data frame + Stop bit . The start bit is the low level of a bit period , Bit period is the time taken by each bit ; data
The frame is what we're going to send 8 Bit or 9 Bit data , Data is transmitted from the lowest bit ; The stop bit is a high current for a certain period of time
flat . The length of stop bit time can be determined by USART Control register 2(USART_CR2) Of STOP[1:0] Bit control , Optional 0.5
individual 、1 individual 、1.5 And 2 Stop bits . By default 1 Stop bits .2 Two stop bits apply to normal USART Pattern 、 Single line
Mode and modem mode .0.5 And 1.5 Stop bits for smart card mode . When choosing 8 The word is long , Use 1 Stop bits
when , The specific sending character sequence diagram is shown in the figure 9-8.
The first 9 Chapter .USART- A serial port communication
The first 88 page SAIUR2016
chart 9-8 Character sending sequence diagram
When sending the enable bit TE Set up 1 after , The transmitter starts by sending a free frame ( A high level of data frame length ), continue with
Come and go USART_DR Register writes the data to be sent . After writing the last data , Need to wait USART shape
State register (USART_SR) Of TC Position as 1 , Indicates that the data transmission is completed , If USART_CR1 The register of TCIE
Location 1, There will be interruptions . When sending data , When programming, there are several important flag bits. Let's summarize .
Receiver
If you will USART_CR1 The register of RE Location 1, Can make USART receive , Make the receiver in RX The line starts searching
The starting position of the rope . After the start position is determined, it is based on RX The line level state stores the data in the receive shift register . When the reception is complete
Move the receive shift register data to RDR Inside , And put USART_SR The register of RXNE Location 1, At the same time, if
USART_CR2 The register of RXNEIE Set up 1 You can have interruptions . When receiving data , There are several comparisons when programming
Let's summarize the important signs .
Fractional baud rate generation
Baud rate refers to the modulation rate of data signal to carrier , It is expressed by the number of changes of carrier modulation state per unit time , The unit is wave
, . Bit rate is the number of bits transmitted per unit time , Company bit/s(bps). about USART The baud rate is equal to the bit rate , I don't want to
Distinguish between the two concepts . The higher the baud rate , The faster the transmission rate .USART The same baud rate is used for both the transmitter and the receiver . Calculate the public
The formula is as follows :
The formula 9-1 Baud rate calculation
among ,fPLCK by USART The clock , USARTDIV It's a baud rate register (USART_BRR) One of the none
Signed fixed point number . among DIV_Mantissa[11:0] Bit definition USARTDIV The integral part of ,DIV_Fraction[3:0] Bit definition
The first 9 Chapter .USART- A serial port communication
SAIUR201 6 The first 89 page
USARTDIV Decimal part of . for example : DIV_Mantissa=24(0x18) , DIV_Fraction=10(0x0A) , here
USART_BRR The value is 0x18A; that USARTDIV The decimal places of 10/16=0.625; Integer bit 24, Final USARTDIV Of
The value is 24.625. If you know USARTDIV The value is 27.68, that DIV_Fraction=16*0.68=10.88, The nearest positive integer
by 11, therefore DIV_Fraction[3:0] by 0xB;DIV_Mantissa= Integers (27.68)=27, That is to say 0x1B. Common values of baud rate
Yes 2400、9600、19200、115200. Here is an example to explain how to set the baud rate value of the register value . We know USART1
Use APB2 Bus clock , Up to 72MHz, other USART The highest frequency of is 36MHz. We choose USART1 do
Explain for example , namely fPLCK=72MHz. In order to get 115200bps Baud rate , here :
Solution USARTDIV=39.0625, It can be counted. DIV_Fraction=0.0625*16=1=0x01,DIV_Mantissa=39=0x17, namely
Should be set USART_BRR The value of is 0x171.
Calibration control
STM32F103 Series controller USART Support parity . When using check bits , The length of serial transmission will be 8 Bit
Data frame plus 1 The total number of check bits is 9 position , here USART_CR1 The register of M Bit needs to be set to 1, namely 9 Data bits .
take USART_CR1 The register of PCE Location 1 You can start parity control , Parity check is done automatically by hardware . start-up
After the parity control , Check bits are added automatically when sending data frames , Automatically verify check bits when receiving data . When receiving data
If parity bit verification fails , meeting USART_SR The register of PE Location 1, And can generate parity interrupt .
After enabling parity control , The format of each character frame will become : Start bit + Data frame + Check bit + Stop bit .
Interrupt control
USART There are multiple interrupt request events , See table for details 9-4.
surface 9-4 USART Interrupt request
The first 9 Chapter .USART- A serial port communication
The first 90 page SAIUR2016
9.6. USART Initialization structure details
The standard library function creates an initialization structure for each peripheral , such as USART_InitTypeDef, Structure members are used for
Set the working parameters of peripherals , The configuration function is initialized by the peripheral , such as USART_Init() call , These settings will set the peripherals
Corresponding registers , To achieve the purpose of configuring the working environment of peripherals . The combination of initialization structure and initialization library function is the essence of standard library
stay , After understanding the meaning of each member of the initialization structure, you can basically use the peripheral freely . The initialization structure is defined in
stm32f10x_usart.h In file , Initialization library functions are defined in stm32f10x_usart.c In file , When programming, we can combine these two
Use... For comments within a file .
USART_BaudRate: Baud rate setting . Generally set as 2400、9600、19200、115200. Standard library functions will be based on
The set point is calculated USARTDIV value , To set up USART_BRR Register values .
USART_WordLength: Data frame word length , Optional 8 Bit or 9 position . It sets USART_CR1 The register of M Bit
value . If there is no enable parity control , In general use 8 Data bits ; If parity is enabled, it is generally set to 9 Data bits .
USART_StopBits: Stop bit setting , Optional 0.5 individual 、1 individual 、1.5 And 2 Stop bits , It sets USART_CR2
The register of STOP[1:0] The value of a , Generally, we choose 1 Stop bits .
USART_Parity : Parity control selection , Optional USART_Parity_No( No verification ) 、
USART_Parity_Even( Even check ) as well as USART_Parity_Odd( Odd check ) , It sets USART_CR1
The register of PCE Bit and PS The value of a .
USART_Mode:USART Mode selection , Yes USART_Mode_Rx and USART_Mode_Tx, Allow the use of logic or
The operation selects two , It sets USART_CR1 The register of RE Bit and TE position .
USART_HardwareFlowControl: Hardware flow control selection , Only in hardware flow control mode , Optional ⑴ Can make
RTS、⑵ Can make CTS、⑶ At the same time enable RTS and CTS、⑷ Do not enable hardware streaming . When using synchronous mode, you need to configure SCLK lead
The properties of the output pulse of the foot , The standard library uses a clock to initialize the structure USART_ClockInitTypeDef To set up , In this structure
Only in synchronous mode can capacity be set .
The first 9 Chapter .USART- A serial port communication
SAIUR201 6 The first 91 page
USART_Clock : In synchronous mode SCLK Clock output enable control on pin , Optional disable clock output
(USART_Clock_Disable) Or turn on the clock output (USART_Clock_Enable); If you send in synchronous mode , Generally
Turn on the clock . It sets USART_CR2 The register of CLKEN The value of a .
USART_CPOL: In synchronous mode SCLK Output clock polarity setting on pin , It can be set in idle time SCLK The pin is low
level (USART_CPOL_Low) Or high level (USART_CPOL_High). It sets USART_CR2 The register of CPOL Bit
value .
USART_CPHA: In synchronous mode SCLK Output clock phase setting on pin , Can be set at the first change of the clock along the capture number
According to the (USART_CPHA_1Edge) Or capture data along the second change of the clock . It sets USART_CR2 The register of CPHA position
Value .USART_CPHA And USART_CPOL When used together, you can get multiple mode clock relations .
USART_LastBit: Select whether the clock pulse is in when the last data bit is sent SCLK Pin out , Sure
It doesn't output pulses (USART_LastBit_Disable) 、 Output pulse (USART_LastBit_Enable). It sets
USART_CR2 The register of LBCL The value of a .
9.7. USART1 Receiving and transmitting communication experiment
USART Only two signal lines are needed to complete two-way communication , Low hardware requirements , Many modules are reserved USART Interface
Realize data transmission with other modules or controllers , such as GSM modular ,WIFI modular 、 Bluetooth module and so on . In the hardware design
timing , Note that one more is needed “ Common ground wire ”. We use it a lot USART To realize the data transmission between the controller and the computer . This makes
It's very convenient for us to debug the program , For example, we can take the values of some variables 、 The return value of the function 、 Register flag bits and so on
USART Send to serial debugging assistant , In this way, we can be very clear about the running state of the program , When we officially release the program, we'll put
The debugging information can be removed . We can not only send data to the serial port debugging assistant , We can also debug the assistant in the serial port to send
Send data to the controller , The controller program carries out the next work according to the received data . First , Let's write a program to realize
Communication between hair board and computer , Power on the development board through USART Send a string to the computer , Then the development board enters into interrupt reception and so on
Wait for the state , If the computer sends data , The development board will have an interrupt , We receive data in the interrupt service function , And immediately put
The data is sent back to the computer .
The first 9 Chapter .USART- A serial port communication
The first 92 page SAIUR2016
9.7.1. Hardware design
To make use of USART Realize the communication between development board and computer , Need to use a USB turn USART Of IC, We choose
CH340G Chip to achieve this function ,CH340G It's a USB Bus adapter chip , Realization USB turn USART、USB
turn lrDA Infrared or USB To the printer interface , We use it USB turn USART function . The specific circuit design is shown in the figure 9-9.
We will CH340G Of TXD Pin and USART1 Of RX Pin connection ,CH340G Of RXD Pin and USART1 Of
TX Pin connection .CH340G The chip is integrated on the development board , Its ground wire (GND) Has been linked to the controller's GND connected .
chart 9-9 USB Hardware design of serial port
9.7.2. software design
Here is just the core part of the code , Some variable settings , The inclusion of header files does not involve , For complete code, please refer to
Consider the supporting projects in this chapter . We created two files :bsp_usart.c and bsp _usart.h Files are used to hold USART Driving range
Order and related macro definitions .
9.7.3. Programming points
1. Can make RX and TX Pin GPIO The clock and USART The clock ;
2. initialization GPIO, And will GPIO Reuse to USART On ;
3. To configure USART Parameters ;
4. Configure the interrupt controller and enable USART Receive interrupt ;
5. Can make USART;
6. stay USART Receive interrupt service function to receive and send data .
The first 9 Chapter .USART- A serial port communication
SAIUR201 6 The first 93 page
9.7.4. The code analysis
Code list 9-1 GPIO and USART Macro definition
Use macro definition to facilitate program migration and upgrade . In the development board CH340G By default, the transmit and receive pins of are connected to
USART1, If you want to use other serial ports , You can put CH340G Follow USART1 Directly connect the jump cap and pull it out , And then put the other
Serial port IO Connect with DuPont wire CH340G The transceiver pin of . Here we use USART1, Set the baud rate to 115200,
selected USART Of GPIO by PA9 and PA10. Nested vector interrupt controller NVIC To configure .
Code list 9-2 Interrupt controller NVIC To configure
The first 9 Chapter .USART- A serial port communication
The first 94 page SAIUR2016
Code list 9-3 USART Initialize configuration
The first 9 Chapter .USART- A serial port communication
SAIUR201 6 The first 95 page
Use GPIO_InitTypeDef and USART_InitTypeDef Structure defines a GPIO Initialization variables and a
USART Initialize variable , We have explained these two structures in detail before . call RCC_APB2PeriphClockCmd
Function on GPIO Port clock , Use GPIO The clock of the corresponding port must be turned on before . Use
RCC_APB2PeriphClockCmd Function on USART The clock . Use GPIO You need to initialize and configure it before , And also
Add special settings , Because we use it as a pin for peripherals , Generally, they have special functions . When we initialize, we need to change its mode
Set to reuse function . Here is the serial port Tx The pins are configured to multiplex push-pull output ,Rx The pin is floating input , The data is completely external
Input decision . Next , We configure USART1 The communication parameters are : Baud rate 115200, The word is 8,1 Stop bits , No,
Check bit , No hardware flow control , Transceiver integrated working mode , And then call USART Initialize the function to complete the configuration . The program uses
USART Receive interrupt , Need configuration NVIC, This call NVIC_Configuration Function to complete the configuration . End of configuration NVIC And
After the call USART_ITConfig The function enables USART Receive interrupt .
Last call USART_Cmd The function enables USART, The final configuration of this function is USART_CR1 Of UE position , Specifically
The function of is to turn on USART The working clock of , There is no clock USART This peripheral doesn't work .
Code list 9-4 Character sending function
Usart_SendByte Function is used to specify USART Send a ASCLL Code value characters , It has two formal parameters , The first is
USART, The second is the character to be sent . It's by calling library functions USART_SendData To achieve , And increased waiting
Send complete function . By using USART_GetFlagStatus Function to get USART Event flag to achieve the send complete function
stay , It takes two parameters , One is USART, One is the event sign . Here we loop to check that the transmit data register is empty
sign , When you jump out while Loop indicates the fact that the transmit data register is empty .Usart_SendString Function to send a word
Fu string , It's actually calling Usart_SendByte Function to send each character , It doesn't stop sending until it encounters a null character . Finally, use the loop
Detect the event flag for send complete TC To ensure that the data sent after the completion of the exit function .
The first 9 Chapter .USART- A serial port communication
The first 96 page SAIUR2016
USART Interrupt service function
Code list 21-5 USART Interrupt service function
This code is stored in stm32f10x_it.c In the document , This file is used to store peripheral interrupt service functions . When we make
The interrupt service function here will be executed when the interrupt occurs . We're in the code list 21-3 Enabled USART receive
interrupt , When USART Once the data is received, it will be executed USART_IRQHandler function .USART_GetITStatus Function and
USART_GetFlagStatus Function to get the status of the flag bit , but USART_GetITStatus Function is specifically used to get
Break the event flag , And return the status of the flag bit . Use if Statement to determine whether it is really generated USART Data reception interrupt
event , If it's true, use USART Data reading function USART_ReceiveData Read data to the specified storage area . then
Call again USART Data sending function USART_SendData Send the data back to the source device , namely PC The serial port debugging assistant of the terminal .
The main function
Code list 9-6 The main function
First we need to call USART_Config Function completion USART Initialize configuration , Include GPIO To configure ,USART with
Set up , Receive interrupt enable and so on . Next, you can call the character sending function to send the data to the serial port debugging assistant . Finally, I write to you
I don't do anything , Just waiting in silence USART The generation of receive interrupt , And the interrupt service function returns the data .
The first 9 Chapter .USART- A serial port communication
SAIUR201 6 The first 97 page
9.7.5. Download validation
Ensure that the development board hardware connection is correct , use USB The cable connects the development board USB Serial port and computer , Open the serial port on the computer
Debug assistant and configure relevant parameters :115200 8-N-1, Download the compiled program to the development board , At this time, the serial port debugging assistant can receive
Data sent to the development board . We input any character in the sending area of the serial port debugging assistant , Click Send button , Debug in the serial port immediately
The same characters can be seen in the assistant reception area .
chart 9-10 Experimental phenomena
9.8. Practice after class
1. Use Usart control RGB coloured lights
The first 10 Chapter .DMA Direct store access
The first 98 page SAIUR2016
The first 10 Chapter .DMA Direct store access
10.1. Preview before class
Find the answer in the book .
1. What is? DMA
10.2. summary
What's in this chapter :
(1)DMA Function and configuration
(2) Use DMA Read and write memory data
10.3. DMA brief introduction
DMA(Direct Memory Access)— Direct memory access , It's a peripheral of MCU , Its main function is to carry numbers
According to the , But it doesn't take CPU, That is, when transmitting data ,CPU Can do other things , It's like multithreading . data
Transport support from peripheral to memory or memory to memory , The memory here can be SRAM Or is it FLASH.DMA control
The controller contains DMA1 and DMA2, among DMA1 Yes 7 Channels ,DMA2 Yes 5 Channels , The passageway here can manage
It's a pipe for transmitting data . It should be noted that DMA2 It only exists in large capacity single chip microcomputer .
10.4. DMA Functional block diagram
DMA The controller is independent of the kernel , Belongs to a separate peripheral , Simple structure , From a programming point of view , We just need to palm
Just grasp the three parts in the function diagram , See Fig 10-1:DMA The block diagram of the controller .
The first 10 Chapter .DMA Direct store access
SAIUR201 6 The first 99 page
chart 10-1 DMA block diagram
DMA request
If peripherals want to get through DMA To transmit data , Must give first DMA Controller send DMA request ,DMA Receive a request
After the signal , The controller will give the peripheral a response signal , When the peripheral responds and DMA After the controller receives the response signal , It will start
dynamic DMA The transmission of , Until the transmission is complete .DMA Yes DMA1 and DMA2 Two controllers ,DMA1 Yes 7 Channels ,DMA2
Yes 5 Channels , Different DMA The channels of the controller correspond to different peripheral requests , This determines how we program software
Set up , Specific view DMA Request image table .
chart 10-2 DMA1 The request image of each channel
The first 10 Chapter .DMA Direct store access
The first 100 page SAIUR2016
chart 10-3 DMA2 The request image of each channel
among ADC3、SDIO and TIM8 Of DMA Requests only exist in high volume products , This should be paid attention to in specific projects .
passageway
DMA have 12 Two independent programmable channels , among DMA1 Yes 7 Channels ,DMA2 Yes 5 Channels , Every channel
Corresponding to different peripherals DMA request . Although each channel can receive requests from multiple peripherals , But only one can be received at a time ,
You can't receive multiple .
Arbiter
When multiple DMA Channel request , It means that there is a sequence of response processing , This is also managed by the arbiter .
Arbiter Management DMA The channel request is divided into two phases . The first phase belongs to the software phase , Can be in DMA_CCRx Set... In the register
Set up , Yes 4 Level : Very high 、 high 、 Four priorities, medium and low . The second phase belongs to the hardware phase , If two or more DMA
Channel requests are set with the same priority , Then their priority depends on the channel number , The lower the number, the higher the priority , Like a channel 0 higher than
passageway 1. In large capacity products and interconnected products ,DMA1 The controller has more than DMA2 The priority of the controller .
10.5. DMA Data configuration
Use DMA, The core is to configure the data to be transmitted , Including where the data comes from , Where to go , The unit of data transmitted
What is it? , How much data to transmit , Is it a transmission or a circular transmission and so on .
Where to come from
We know DMA There are three directions for transmitting data : From peripherals to memory , From memory to peripherals , From memory to memory .
Specific direction DMA_CCR position 4 DIR To configure :0 From peripheral to memory ,1 From memory to peripherals . It's about
The peripheral address to be reached by DMA_CPAR To configure , The memory address is determined by DMA_CMAR To configure . Peripherals to memory when we use
When transferring from peripheral to memory , With ADC Take the acquisition as an example .DMA The address of the peripheral register corresponds to ADC Data register
Address ,DMA The memory address is our custom variable ( Used to receive storage AD Collected data ) The address of . The direction is me
The first 10 Chapter .DMA Direct store access
SAIUR201 6 The first 101 page
We set the peripheral as the source address . Memory to peripherals when we use memory to peripherals transfer , Sending data to the computer through the serial port is regarded as
example .DMA The address of peripheral register corresponds to the address of serial data register ,DMA The address of the memory is our own
The variable of meaning ( Equivalent to a buffer , It is used to store the data sent to the computer through the serial port ) The address of . We set the peripheral as the target
Address . Memory to memory when we use memory to memory transfer , Inside FLASH To the inside SRAM Copy number
For example .DMA The address of the peripheral register corresponds to the internal FLASH( Let's put the interior here FALSH As a peripheral
see ) The address of ,DMA The memory address is our custom variable ( Equivalent to a buffer , Used to store data from inside FLASH
The data of ) The address of . We set up peripherals ( Inside FLASH) Is the source address . What's different from the two above is , Need here
hold DMA_CCR position 14:MEM2MEM: The memory to memory mode is configured to 1, start-up M2M Pattern .
How much to pass , What are the units
When we've configured where the data will come from and where it will go , We also need to know how much data we want to transmit , Data
What are the units . Take sending data from serial port to computer as an example , We can send a lot of data to the computer at one time , How much is decided by
DMA_CNDTR To configure , This is a 32 Bit register , It can only be transmitted at most at one time 65535 Data . If you want data transmission to be
indeed , The width of the data stored in the source and destination addresses must also be the same , The serial data register is 8 Bit , So what we define to send
The data also has to be 8 position . The data width of the peripheral is determined by DMA_CCR Of PSIZE[1:0] To configure , It can be 8/16/32 position , Memory
The data width of is determined by DMA_CCR Of MSIZE[1:0] To configure , It can be 8/16/32 position .
stay DMA Under the control of the controller , In order to move data from one place to another in an orderly way , It also has to be set up correctly
Incremental mode of data pointers on both sides . The address pointer of the peripheral is controlled by DMA_CCRx Of PINC To configure , The address pointer of the memory consists of
MINC To configure . Take sending data from serial port to computer as an example , There's a lot of data to send , Every time you send one , So the address of the memory is
The needle should be added 1, There is only one serial data register , Then the address pointer of the peripheral is fixed . Specific increment of data pointer
The pattern is determined by the actual situation .
When the transmission is complete
When will the data be transmitted , We can check the flag bit or interrupt to identify . Every DMA passageway
stay DMA More than half the transmission 、 There will be corresponding flag bits when the transmission is completed and when the transmission is wrong , If this type of interrupt is enabled , will
The interrupt . For a detailed description of each flag bit, please refer to DMA Interrupt status register DMA_ISR Detailed description of . The transmission is over
There are two modes of success , Is it a transmission or a circular transmission , A transmission is easy to understand , That is, the transmission stops after one transmission , If you want to pass it on again
If you lose , It has to be turned off DMA Enable and reconfigure to continue transmission . Circular transmission is a transmission completed and then restored
The configuration of the first transmission is cyclic transmission , Keep repeating . Concrete DMA_CCR The register of CIRC Loop mode bit control .
10.6. DMA Initialization structure details
The standard library function creates an initialization structure for each peripheral xxx_InitTypeDef(xxx Name the peripheral ), The structure forms
It is used to set working parameters of peripherals , And by the standard library function xxx_Init() Call these setting parameters to enter the corresponding registers of setting peripherals ,
To achieve the purpose of configuring the working environment of peripherals . Structure xxx_InitTypeDef And library functions xxx_Init Cooperation is the essence of the standard library
The first 10 Chapter .DMA Direct store access
The first 102 page SAIUR2016
stay , Understand the structure xxx_InitTypeDef Each member can basically use the peripheral freely . Structure
xxx_InitTypeDef It's defined in stm32f10x_xxx.h( Back xxx Name the peripheral ) In file , Library function xxx_Init It's defined in
stm32f10x_xxx.c In file , When programming, we can use it in combination with the comments in these two files .
DMA_PeripheralBaseAddr: Peripheral address , Set up DMA_CPAR Register value ; It is generally set as the data of peripheral devices
Register address , If it's memory to memory mode, set it to one of the memory addresses .
DMA_Memory0BaseAddr: Memory address , Set up DMA_CMAR Register values ; The general setting is our custom
The first address of the store .
DMA_DIR : Transmission direction selection , Optional peripherals to memory 、 Memory to peripherals . It sets DMA_CCR register
Of DIR[1:0] The value of a . There is no memory to memory direction selection , When using memory to memory , Just put it
A memory can be used as a peripheral .
DMA_BufferSize: Set the number of data to be transmitted , Initialization settings DMA_CNDTR Register value .
DMA_PeripheralInc: If configured as DMA_PeripheralInc_Enable, Enable peripheral address auto increment function , it
Set up DMA_CCR The register of PINC The value of a ; Generally, peripherals have only one data register , So it's not usually able to
position .
DMA_MemoryInc: If configured as DMA_MemoryInc_Enable, Enable memory address auto increment function , It sets up
set DMA_CCR The register of MINC The value of a ; Our custom storage area is usually used to store multiple data , So make it possible
Memory address auto increment function .
DMA_PeripheralDataSize: Peripheral data width , Optional bytes (8 position )、 Half word (16 position ) He Zi (32 position ), It sets
DMA_CCR The register of PSIZE[1:0] The value of a .
DMA_MemoryDataSize: Memory data width , Optional bytes (8 position )、 Half word (16 position ) He Zi (32 position ), It sets
DMA_CCR The register of MSIZE[1:0] The value of a . When data is transferred between peripheral and memory , The data width on both sides should be set
For consistent size .
DMA_Mode : DMA Transmission mode selection , It can be transmitted once or circularly , It sets DMA_CCR Deposit
The first 10 Chapter .DMA Direct store access
SAIUR201 6 The first 103 page
Organic CIRC The value of a . It's our ADC Acquisition is a continuous cycle , So use circular transmission mode .
DMA_Priority: The software sets the priority of the channel , Yes 4 The optional priorities are very high 、 high 、 And low , It sets up
set DMA_CCR The register of PL[1:0] The value of a .DMA Channel priority is limited to multiple DMA Only when channels are used at the same time
The righteous , If it's a single channel , The priority can be set at will .
DMA_M2M : Memory to memory mode , Using memory to memory uses , Set up DMA_CCR Bit 14
MEN2MEN Start memory to memory mode .
10.7. DMA Memory to memory mode experiment
This chapter only explains the memory to memory and memory to peripheral modes , Other function modes can be used in other chapters
speak . Memory to memory mode can realize the fast copy of data in two memories . Let's first define a static source data , Store in
Inside FLASH, And then use DMA Transport copies the source data to the destination address ( Inside SRAM), Finally, compare the source data with
Destination address data , See if the transmission is accurate .
10.7.1. Hardware design
DMA Memory to memory experiments do not require other hardware requirements , Only for RGB Color lights are used to indicate program status .
10.7.2. software design
Here is just the core part of the code , Some variable settings , The inclusion of header files does not involve , For complete code, please refer to
Consider the supporting projects in this chapter . This experimental code is relatively simple , The main program code is in main.c In file .
10.7.3. Programming points
1. Can make DMA The clock ;
2. To configure DMA Data parameters ;
3. Can make DMA, transmitted ;
4. Wait for the transfer to complete , And compare the source data with the destination address data .
The first 10 Chapter .DMA Direct store access
The first 104 page SAIUR2016
10.7.4. The code analysis
DMA Macro definition and related variable definition
Code list 10-1 DMA Data flow and related variable definitions
Use macro definition to set peripheral configuration to facilitate program modification and upgrade . There are no hard and fast rules for memory to memory transfer channels , Be free to
choice .aSRC_Const_Buffer[BUFFER_SIZE] Definition is used to store source data , And used const Keyword modification , That is to say
Quantity type , So that variables are stored internally flash In space .
The first 10 Chapter .DMA Direct store access
SAIUR201 6 The first 105 page
DMA Data configuration
Code list 10-2 DMA Transmission parameter configuration
Use DMA_InitTypeDef Structure defines a DMA Initialize variable , We have detailed the content of this structure before
Explain . call RCC_AHBPeriphClockCmd Function on DMA The clock , Use DMA The controller must be turned on before the corresponding
The clock of . The source address and destination address use the first address of the array defined before , The amount of data transferred is macro BUFFER_SIZE decision , Source
And destination address pointer address increment , Using one-time transmission mode can't cycle transmission , Because there's only one DMA passageway , Whatever the priority
Set up , Last call DMA_Init Function completion DMA Initialization configuration of .
DMA_ClearFlag Function to clear DMA Sign a , The code uses the transmission completion flag bit , Clear the transmission before use
In order to avoid unnecessary interference .DMA_ClearFlag The function needs 1 Parameters , That is, the event flag bit , Optional transmission complete
Sign a 、 Half transmit flag bit 、FIFO Error flag bit 、 Transmission error flag bits and so on , A lot , We choose the transmission completion mark here
Ambition , You Hong DMA_FLAG_TC Definition .
DMA_Cmd Functions are used to start or stop DMA The data transfer , It takes two parameters , The first is DMA passageway , another
The other one is open ENABLE Or stop DISABLE. Memory data comparison
The first 10 Chapter .DMA Direct store access
The first 106 page SAIUR2016
Code list 10-3 Compare source data with destination address data
Determine whether two data sources of specified length are equal , If it's exactly equal, return 1; As long as one pair of data is not equal, return 0.
It needs three formal parameters , The first two are the addresses of the two data sources , The third is to compare the data length .
The main function
Code list 10-4 Memory to memory mode main function
The first 10 Chapter .DMA Direct store access
SAIUR201 6 The first 107 page
First of all, a variable is defined to save the memory data comparison results .RGB Color lights are used to indicate the progress of the program , Before you use it, you need to
Initialize it ,LED_GPIO_Config It's defined in bsp_led.c In file . Began to set RGB The color light is purple ,LED_PURPLE
Is defined in bsp_led.h A macro definition of the file .Delay Function is just a simple delay function . call DMA_Config Letter
Count to finish DMA Data flow configuration and start DMA The data transfer .DMA_GetFlagStatus Function to obtain DMA Of the event flag bit
current state , Here for DMA Data transmission completes this flag bit , Use the loop to wait until the flag bit is set , namely
DMA The transmission is complete and this event occurs , And then exit the loop , After running the program . determine DMA After the transfer is complete, you can call
Buffercmp Function to compare source data with DMA Whether the data of the destination address corresponds one by one after transmission .TransferStatus Save the comparison knot
fruit , If 1 It means that two data sources correspond to each other one by one DMA Transmission successful ; contrary , If 0 Represents two data sources
There is inequality in data , explain DMA Transmission error . If DMA Transfer successful settings RGB The color light is blue , If DMA
Transmission error settings RGB The color light is red .
10.7.5. Download validation
Make sure the power supply of the development board is normal , Compile the program and download . Observe RGB Color light changes . Under normal circumstances RGB Color lights first
It's purple , And then it turns blue . If DMA Transmission error will be red .
10.8. Practice after class
1. According to the memory to peripheral mode experiment, write a peripheral to memory program , Realization USART Of DMA Receive request function ,
While receiving data LED Constantly on and off , It is equivalent to two tasks in execution .
The first 11 Chapter .TIM Basic timer
The first 108 page SAIUR2016
The first 11 Chapter . TIM Basic timer
11.1. Preview before class
Find the answer in the book .
1. What is? TIM Basic timer ?
11.2. summary
What's in this chapter :
(1) The classification of timers
(2) Timer function block diagram
(3) Program with basic timers
11.3. Timer classification
STM32F1 In the series , In addition to connected products , share 8 A timer , Divided into basic timers , Universal timer and advanced
Timer . Basic timer TIM6 and TIM7 It's a 16 A timer that can only count up , It can only be timed , No external
IO. Universal timer TIM2/3/4/5 It's a 16 You can go up / The next timer to count , It can be timed , Can output comparison , can
Capture... With input , Each timer has four external IO. Advanced timer TIM1/8 It's a 16 You can go up / The timing of the next count
device , It can be timed , Can output comparison , You can enter capture , There can also be three-phase motor complementary output signal , Each timer has 8 individual
external IO. For more specific classification details, see 11-1.
The first 11 Chapter .TIM Basic timer
SAIUR201 6 The first 109 page
chart 11-1 Timer classification
11.4. Basic timer function block diagram explanation
The core of the basic timer is the time base , Not only are the basic timers , General timer and advanced timer also have . When learning timers , I
Let's start with a simple basic timer , To the following general and advanced timer learning , Let's just skip the time base section
that will do . The functional block diagram of the basic timer is shown in the figure 11-2.
chart 11-2 Basic timer function block diagram
Clock source
Timer clock TIMxCLK, The internal clock CK_INT, the APB1 The prescaler provides , If APB1 Pre score
The frequency coefficient is equal to 1, Then the frequency does not change , Otherwise, the frequency is multiplied by 2, Library function APB1 The coefficient of the prescaler is 2, namely PCLK1=36M,
So the timer clock TIMxCLK=36*2=72M.
Counter clock
The timer clock goes by PSC After the prescaler , namely CK_CNT, Used to drive the counter to count .PSC It's a 16 Bit
Preassigned frequency counter , You can set the timer clock TIMxCLK Conduct 1~65536 Any number between them . Specific calculation method
The first 11 Chapter .TIM Basic timer
The first 110 page SAIUR2016
by :CK_CNT=TIMxCLK/(PSC+1).
Counter
Counter CNT It's a 16 Bit counter , You can only count up , The maximum count is 65535. When the count reaches auto reset
An update event is generated when a register is loaded , And clear, count from the beginning .
Auto reload register
Auto reload register ARR It's a 16 Bit register , It's got the maximum number that a counter can count . Count when
When it comes to this value , If interruption is enabled , The timer generates an overflow interrupt .
Calculation of timing time
The timer time is equal to the interrupt period of the counter multiplied by the number of interrupts . The counter is in CK_CNT Driven by , Count one
The number of times is CK_CLK Reciprocal , be equal to :1/(TIMxCLK/(PSC+1)), The time to generate an interrupt is equal to :1/
(CK_CLK * ARR). If you set a variable in the interrupt service program time, Used to record the number of interrupts , then
It can be calculated that the timing time we need is equal to : 1/CK_CLK * (ARR+1)*time.
11.5. Timer initialization structure details
In the standard library function header file stm32f10x_tim.h Four initialization structures are established for timer peripherals in , The basic timer is just
To one of them, that is TIM_TimeBaseInitTypeDef, See the code list for details 11-1, The other three are in the advanced timer section
Explain .
Code list 11-1 Timer basic initialization structure
TIM_Prescaler: Timer prescaler settings , The clock source is the timer clock through the prescaler , It sets TIMx_PSC Send
The value of the memory . The settable range is 0 to 65535, Realization 1 to 65536 frequency division .
TIM_CounterMode: Timer counting mode , But counting up for 、 Down counting and three center alignment patterns . The base
This timer can only count up , namely TIMx_CNT Only from 0 Began to increase , And there's no need to initialize .TIM_Period: timing
The period of the filter , It's actually setting the value of the auto overload register , Update to shadow register when event is generated . The settable range is 0 to
65535.
TIM_ClockDivision: The clock frequency division , Set the timer clock CK_INT Frequency and digital filter sampling clock frequency division
The first 11 Chapter .TIM Basic timer
SAIUR201 6 The first 111 page
Than , The basic timer doesn't have this function , No settings .
TIM_RepetitionCounter: Repeat counter , It belongs to special register bit of advanced control register , It can be very easy to use
Control output PWM The number of . There's no need to set up . Although the timer basic initialization structure has 5 Members , But for basic timing
Just set up two of them , Think about using a basic timer .
11.6. Basic timer timing experiment
11.6.1. Hardware design
This experiment uses basic timer TIM6/7 timing 1s,1s Time out LED Flip once . The basic timer is inside the MCU
Resources for , No external IO, There's no need to connect an external circuit , Now just one is needed LED that will do .
11.6.2. software design
Here is just the core part of the code , Some variable settings , The inclusion of header files does not involve , For complete code, please refer to
Consider the supporting projects in this chapter . We write two timer driver files ,bsp_TiMbase.h and bsp_TiMbase.h, Used to configure timing
Interrupt priority and initialization timer .
11.6.3. Programming points
1. Turn on the timer TIMx_CLK, x[6,7];
2. Initialization time base initialization structure ;
3. Can make TIMx, x[6,7] update interrupt ;
4. Turn on timer ;
5. Write interrupt service program
General timer and advanced timer timing programming points with the basic timer almost , Just need to select the next counter's counting mode
type , Up or down . Because the basic timer can only count up , And there is no register configured for count mode , The default is up .
11.6.4. software analysis
Basic timer macro
The first 11 Chapter .TIM Basic timer
The first 112 page SAIUR2016
Code list 11-2 Macro definition
The basic timers are TIM6 and TIM7, We can use it selectively , In order to improve the code portability , We need to
To modify the timer, the code to be modified is defined as a macro , The default is timer 6, If you want to change it to a timer 7, Only need to
macro BASIC_TIM6 Just comment it out .
Basic timer configuration
Code list 11-3 Basic timer mode configuration
The first 11 Chapter .TIM Basic timer
SAIUR201 6 The first 113 page
We set the timer to reload the register automatically ARR The value of is 1000, Set the clock prescaler to 71, Then drive the counter
The clock of :CK_CNT = CK_INT / (71+1)=1M, Then the time for the counter to count once is equal to :1/CK_CNT=1us, When counter
Count to ARR Value 1000 when , Create an interrupt , The interruption time is :1/CK_CNT*ARR=1ms. Initializing
When it's on the timer , We define a structure : TIM_TimeBaseInitTypeDef , TIM_TimeBaseInitTypeDef junction
There's in the construct 5 Members ,TIM6 and TIM7 There are only TIM_Prescaler and TIM_Period, The other three are
There is no basic timer , So use TIM6 and TIM7 You just need to initialize these two members , The other three members
It's universal timer and advanced timer , The details are as follows :
among TIM15/16/17 It only exists in the connected products , stay F1 Big / in / Not in the small capacity models .
Timer interrupt priority configuration
We set the interrupt group to 0, The primary priority is 0, Preemption priority is 3.
Timer interrupt service program
The timer interrupts once for 1ms, We define a global variable time, Every time there is an interruption , Give Way time Come on
Record the number of times to enter the interrupt . If we want to achieve a 1s The timing of , We just need to judge time Is it equal to 1000 that will do ,
1000 individual 1ms Namely 1s. And then put time clear 0, Recount , And so on . At the end of the interrupt service routine , To put
The corresponding interrupt flag bit is cleared , Bear in mind .
The first 11 Chapter .TIM Basic timer
The first 114 page SAIUR2016
The main function
The main function does some necessary initialization , And then in a dead cycle of judgment time Value ,time The value of is in the timer
Change , Each time you add it means the timer has passed 1ms, When time be equal to 1000 when ,1s Time out ,LED1 Flip once , And put time
clear 0.
11.6.5. Download validation
Download the program to the development board , You can see LED1 With 1s The frequency of a flash .
11.7. Practice after class
1. Calculate the maximum time of a basic timer , If you need to use a basic timer to generate 100s What is the solution to periodic events
present ?
2. Modify the experimental procedure , Make sure that every 0.5s Flip once LED1 At the same time in every 10s Flip LED2.
The first 12 Chapter .TIM Advanced timer
SAIUR201 6 The first 115 page
The first 12 Chapter .TIM Advanced timer
12.1. Preview before class
Find the answer in the book .
1. What is? TIM Advanced timer ?
12.2. summary
What's in this chapter :
(1) Advanced timer function block diagram
(2) Write programs using advanced timers
12.3. Advanced control timer
Advanced control timer (TIM1 and TIM8) And universal timer introduces external pins on the basis of basic timer , Can achieve
Input capture and output comparison functions . Advanced control timer adds programmable dead time complementary output to general timer 、 Repeat counter 、 belt
brake ( Open circuit ) function , These functions are for industrial motor control . These functions are not detailed in this book , This paper mainly introduces
Common input capture and output comparison functions . The advanced control timer time base unit contains a 16 Bit auto reload register ARR,
One 16 Bit counter CNT, But up / Count down , One 16 Bit programmable prescaler PSC, There are many kinds of clock sources in prescaler
Optional , There's an internal clock 、 The external clock . One more 8 Bit repetition counter RCR, This is the highest possible 40 Bit programmable
timing .STM32F103ZET6 Advanced / Universal timer IO The distribution is shown in the table 12-1. Supporting development board because IO A shortage of resources ,
Timer IO Many have reused it , So in the table below IO Only part of it can be used in timer experiments .
The first 12 Chapter .TIM Advanced timer
The first 116 page SAIUR2016
surface 12-1 Advanced control and general timer channel pin distribution
12.4. Function block diagram of advanced control timer
The function block diagram of advanced control timer contains the core content of advanced control timer , Master the functional block diagram , For advanced control timer
There is an overall grasp of , When programming, the idea is very clear , see , Some of the registers in the picture are shadowed , It means it has shadow deposit
device .
chart 12-1 Function block diagram of advanced control timer
The first 12 Chapter .TIM Advanced timer
SAIUR201 6 The first 117 page
12.4.1. Clock source
Advanced control timer has four clock sources to choose from :
1. Internal clock source CK_INT
2. External clock mode 1: External input pins TIx(x=1,2,3,4)
3. External clock mode 2: External trigger input ETR
4. Internal trigger input (ITRx)
5. Internal clock source (CK_INT)
Internal clock CK_INT It comes from inside the chip , be equal to 72M, In general , We all use internal clocks . When the slave die
Type control register TIMx_SMCR Of SMS Bit is equal to 000 when , Then use the internal clock .
12.4.2. External clock mode 1
chart 12-2 External clock mode 1 block diagram
①: Clock signal input pin
When using external clock mode 1 When , The clock signal comes from the input channel of the timer , All in all 4 individual , Respectively
TI1/2/3/4, namely TIMx_CH1/2/3/4. Which signal to use , from TIM_CCMRx Bit CCxS[1:0] To configure , among
CCMR1 control TI1/2,CCMR2 control TI3/4.
②: filter
If the frequency of external clock signal is too high or mixed with high frequency interference signal , We need to use a filter for the signal
Resampling , To achieve the purpose of reducing frequency or removing high frequency interference , The specific reason is TIMx_CCMRx Bit ICxF[3:0] To configure .
③: Edge detection
The edge detection signal comes from the output of the filter , Before it becomes a trigger signal , Edge detection is needed , The decision is that the rising edge has
Effective or falling edge effective , The specific reason is TIMx_CCER Bit CCxP and CCxNP To configure .
The first 12 Chapter .TIM Advanced timer
The first 118 page SAIUR2016
④: Trigger selection
When using external clock mode 1 when , There are two trigger sources , One is the filtered timer input 1(TI1FP1) And filtered
Timer input 2(TI2FP2), The specific reason is TIMxSMCR Bit TS[2:0] To configure .
⑤: From mode selection
After the touch source signal is selected , Finally, we need to connect the signal to TRGI Pin , Make trigger signal external clock mode 1 Of
Input , In the end, it's equal to CK_PSC, And then drive the counter CNT Count . Specific configuration TIMx_SMCR Bit SMS[2:0] by 000
You can select the external clock mode 1.
⑥: Enable counter
Through the top 5 After one step , Finally, we just need to enable the counter to start counting , External clock mode 1 The configuration is complete .
The enable counter consists of TIMx_CR1 Bit CEN To configure .
12.4.3. External clock mode 2
chart 12-3 External clock mode 2 block diagram
①: Clock signal input pin
When using external clock mode 2 When , The clock signal comes from a specific input channel of the timer TIMx_ETR, Only 1 individual .
②: External trigger polarity
come from ETR The signal of pin input can be selected as rising edge or falling edge , The specific reason is TIMx_SMCR Bit ETP
To configure .
③: External trigger prescaler
because ETRP The frequency of the signal must not exceed TIMx_CLK(72M) Of 1/4, When the frequency of the trigger signal is very high ,
You have to use a frequency divider to reduce the frequency , The specific reason is TIMx_SMCR Bit ETPS[1:0] To configure .
④: filter
If ETRP If the frequency of the signal is too high or mixed with high-frequency interference signal , We need to use filters to ETRP
Signal resampling , To achieve the purpose of reducing frequency or removing high frequency interference . The specific reason is TIMx_SMCR Bit ETF[3:0] To configure , Its
Medium fDTS It's from the internal clock CK_INT Divide the frequency to get , The specific reason is TIMx_CR1 Bit CKD[1:0] To configure .
The first 12 Chapter .TIM Advanced timer
SAIUR201 6 The first 119 page
⑤: From mode selection
The filtered signal is connected to ETRF After pin , The trigger signal becomes the external clock mode 2 The input of , In the end, it's equal to
CK_PSC, And then drive the counter CNT Count . Specific configuration TIMx_SMCR Bit ECE by 1 You can select an external clock
Pattern 2.
⑥: Enable counter
Through the top 5 After one step , Finally, we just need to enable the counter to start counting , External clock mode 2 The configuration is complete .
The enable counter consists of TIMx_CR1 Bit CEN To configure .
12.4.4. Internal trigger input
The internal trigger input is a prescaler that uses one timer as another . Hardware advanced control timer and general timer
The timers are connected internally , Timer synchronization or cascade can be realized . The timer in master mode can reset the timer in slave mode 、
start-up 、 Stop or provide a clock .
controller
Advanced control timer controller includes trigger controller 、 From the mode controller and encoder interface . The trigger controller is used for
On chip and on-chip output trigger signal , For example, providing clocks and triggers for other timers DAC/ADC transformation . The encoder interface is designed specifically for
The coder is designed for counting . The counter reset can be controlled from the mode controller 、 start-up 、 Increasing / Decline 、 Count . For the controller part, just
Read the register description skillfully .
Time base unit
chart 12-4 Advanced timer time base unit
Advanced control timer time base unit function includes four registers , They are counter registers (CNT)、 Prescaler register
(PSC)、 Auto reload register (ARR) And repeat counter register (RCR). The repeat counter RCR It's unique to advanced timers ,
Universal and basic timers don't have . The first three registers are 16 Bit effective ,TIMx_RCR The register is 8 Bit effective .
Preassigned frequency counter PSC
Preassigned frequency counter PSC , There is an input clock CK_PSC And an output clock CK_CNT . Input clock CK_PSC Namely
The output of the clock source above , Output CK_CNT Is used to drive the counter CNT Count . By setting the prescaler PSC The value of can be
The first 12 Chapter .TIM Advanced timer
The first 120 page SAIUR2016
Get different CK_CNT, The actual calculation is :fCK_CNT be equal to fCK_PSC/(PSC[15:0]+1), Can achieve 1 to 65536 branch
frequency .
Counter CNT
The advanced control timer has three counting modes , They are incremental counting mode 、 Count down mode and count up mode / Decline ( center
alignment ) Count mode .
1. In incremental mode , Counter from 0 Start counting , Every one of them CK_CNT The pulse counter goes up 1, Until the counter
The value of is the same as the autoload register ARR The values are equal , And then the counter goes from 0 Start counting and generate counter overflow Events , meter
The counter is always counting like this . If the repeat counter is disabled , When the counter generates an overflow event, an update event is generated immediately
(UEV); If enable repeat counter , Every time an overflow event is generated, the repeat counter is subtracted 1, Until the repeat counter
Rong Wei 0 The update event will be generated when .
2. In countdown mode , The counter is automatically reloaded from the register ARR Value starts counting , Every one of them CK_CNT Pulse counter
Will decrease 1, Until the counter value is 0, Then the counter is automatically reloaded from the register ARR The value begins to decrement the count and generates the count
Device underflow Events , The counter is always like this, counting in cycles . If the repeat counter is disabled , When the counter generates a underflow event, it immediately generates
Update Events ; If enable repeat counter , Every time an underflow event is generated, the content of the repeat counter is subtracted 1, Until the count is repeated
The content of the device is 0 The update event will be generated when .
3. In center aligned mode , Counter from 0 Start counting up , Until the count equals (ARR-1) Value generates counter overflow event ,
And then from ARR The value starts to count down until 1 Generate counter underflow Events . And then from 0 Start counting , So circular .
Every time counter overflow and underflow events occur, an update event is generated .
Auto reload register ARR
Auto reload register ARR It's used to store and counter CNT The value of comparison , If two values are equal, the weight reduction counter is passed . Sure
adopt TIMx_CR1 The register of ARPE Bit control automatically reloads shadow register function , If ARPE Location 1, Auto reload shadow
The subregister is valid , Only when the event is updated TIMx_ARR Value to the shadow register . If ARPE Position as 0, The modified
TIMx_ARR The value works immediately .
Repeat counter RCR
In basic / Universal timer happens on / When an underflow event occurs, an update event is generated directly , This is not true for advanced control timers ,
The advanced control timer has a repeat counter in the hardware structure , When an overflow or underflow event occurs on the timer, the repeat counter is decremented
value , Only if the repeat counter is 0 The update event will be generated when . In the event of a N+1 An overflow or underflow event (N by RCR Value )
An update event is generated when .
The first 12 Chapter .TIM Advanced timer
SAIUR201 6 The first 121 page
12.4.5. Input capture
chart 12-5 Input capture function block diagram
Input capture can detect the rising edge of the input signal , Capture along the falling edge or both sides , Commonly used to measure the pulse width of the input signal
And measure PWM The frequency and duty cycle of the input signal . The general principle of input capture is , When the jump edge of the signal is captured
When , Put the counter CNT To the capture register CCR in , Take the two captured CCR The value in the register is
reduce , You can calculate the pulse width or frequency . If the duration of the captured pulse exceeds the period of your capture timer , There will be an overflow ,
This we need to do extra processing .
① Input channel
The signal to be measured comes from the external pin of the timer TIMx_CH1/2/3/4 Get into , Usually called TI1/2/3/4, Capture in the back
In the explanation, for the signal to be measured, we all use TIx It's the standard name .
② Input filters and edge detectors
When there is high frequency interference in the input signal , We need to filter the input signal , That is, resampling , According to the sampling
The laws of , The sampling frequency must be greater than or equal to twice the input signal . For example, the input signal is 1M, There is also high frequency signal interference ,
Then it is necessary to filter at this time , We can set the sampling frequency to 2M, In this way, we can ensure that the effective signal can be sampled
On the basis of that, put the higher than 2M The high frequency interference signal is filtered out . The configuration of the filter is determined by CR1 Bit of register CKD[1:0] and CCMR1/2 Of
position ICxF[3:0] control . from ICxF The description of bit shows that , sampling frequency fSAMPLE Can be fCK_INT and fDTS After frequency division
The clock provides , Where is fCK_INT Internal clock ,fDTS yes fCK_INT The frequency obtained after frequency division , The frequency division factor is determined by
CKD[1:0] decision , It can be no frequency division ,2 Frequency division or 4 frequency division . The edge detector is used to set what the signal is when it is captured
The edge works , It can be a rising edge , Falling edge , Or both sides , The specific reason is CCER Bit of register CCxP and CCxNP
decision .
③ Capture channels
The first 12 Chapter .TIM Advanced timer
The first 122 page SAIUR2016
The capture channel is in the picture IC1/2/3/4, Each capture channel has a corresponding capture register CCR1/2/3/4, When capture happens
When , Counter CNT The value of is locked in the capture register . Here we need to figure out the area between the input channel and the capture channel
other , The input channel is used to input signals , The capture channel is the channel used to capture the input signal , The signal of an input channel can be simultaneously
Input to two capture channels . For example, input channel TI1 After the filtered edge detector TI1FP1 and TI1FP2 Sure
Enter the capture channel IC1 and IC2, In fact, this is what we will talk about later PWM Input capture , There's only one input signal (TI1)
It takes up two capture channels (IC1 and IC2). When only the pulse width of the input signal needs to be measured , Just use one capture channel . transport
The mapping relationship between input channel and capture channel is determined by register CCMRx Bit CCxS[1:0] To configure .
④ Preassigned frequency counter
ICx The output of the signal goes through a prescaler , Used to capture once when deciding how many events occur . Specific by deposit
device CCMRx Bit ICxPSC To configure , If you want to capture every edge of the signal , No frequency division .
⑤ Capture register
The signal passing through the prescaler ICxPS It's the signal that's finally captured , When capture occurs ( for the first time ), Counter CNT Value
Will be locked in the capture register CCR in , There will be CCxI interrupt , The corresponding interrupt bit CCxIF( stay SR In the register ) Meeting
To be placed , By software or reading CCR The value in can change CCxIF clear 0. If a second capture happens ( Repeat capture :CCR
The counter value has been captured in the register and CCxIF The logo is set 1), The overflow flag bit is captured CCxOF( stay SR In the register )
Will be set to ,CCxOF It can only be cleared by software .
12.4.6. Output comparison
chart 12-6 Output comparison function block diagram
The first 12 Chapter .TIM Advanced timer
SAIUR201 6 The first 123 page
Output comparison is to output control signal through external pin of timer , There's freezing 、 Put the passage X(x=1,2,3,4) Set up
Output effective level for matching 、 Put the passage X Output invalid level when set to match 、 Flip 、 Force to invalid level 、 Force becomes
Effective level 、PWM1 and PWM2 These eight models , Which mode to use is determined by the register CCMRx Bit OCxM[2:0] To configure .
among PWM Patterns are a special case of output comparison , It's also the most used .
① Compare register
When counter CNT And the comparison register CCR When the values of are equal , Output reference signal OCxREF The pole of the signal
Sex will change , among OCxREF=1( High level ) It's called effective level ,OCxREF=0( Low level ) It's called the invalid level ,
And there will be a comparison interrupt CCxI, Corresponding flag bit CCxIF(SR In the register ) Can set the position . then OCxREF After another
The control of the series then becomes the real output signal OCx/OCxN.
② Dead zone generator
In the generated reference waveform OCxREF On the basis of , You can insert dead time , Used to generate two complementary output signals OCx
and OCxN, The size of the dead time is determined by BDTR Bit of register DTG[7:0] To configure . The size of the dead time must be based on the input
It can be adjusted by the device connected with the signal and its characteristics . Let's give a simple example of the following with dead zone PWM Application of signals , We use
Take a board bridge drive circuit as an example .
chart 12-7 Half bridge drive circuit
In this half bridge drive circuit ,Q1 Conduction ,Q2 end , At this point I want Q1 end Q2 Conduction , It must be to let Q1 section
After a while , Wait a little longer for Q2 Conduction , Then the waiting time is called dead time , because Q1 close
It takes time to ( from MOS The process of the tube decides ). If Q1 After the closing , Open it now Q2, Well, at this time, it's quite
On Q1 and Q2 It's all on , This shortens the circuit . chart 12-8 Is for the above half bridge drive circuit and draw with dead band insertion
PWM The signal , The dead time in the graph should be based on MOS Tube technology to adjust .
The first 12 Chapter .TIM Advanced timer
The first 124 page SAIUR2016
chart 12-8 Complementary output with dead band insertion
chart 12-9 Output comparison ( passageway 1~3) Output control block diagram of
③ Output control
In the output control of output comparison , Reference signal OCxREF After passing through the dead zone generator, two complementary signals with dead zone will be generated
Number OCx_DT and OCxN_DT( passageway 1~3 There are complementary signals , passageway 4 No, , The rest of the way 1~3 equally ), These two ways
The complementary signal with dead time then enters the output control circuit , If dead zone control is not added , So the signal going into the output control circuit
Directly OCxREF. The signal entering the output control circuit will be divided into two channels , All the way to the original signal , One way is the signal reversed ,
Specifically, the register CCER Bit CCxP and CCxNP control . Whether the polarity selected signal is generated by OCx Pin out
Part of the pin CHx/CHxN Then the register CCER Bit CxE/CxNE To configure . If a break is added ( brake ) function , Open circuit
And deadband registers BDTR Of MOE、OSSI and OSSR These three bits together affect the output signal .
④ Output pin
The output signal of the output comparison finally passes through the external part of the timer IO To output , Respectively CH1/2/3/4, The first three of them
Channels also have complementary output channels CH1/2/3N. In more detail IO Please refer to the relevant data manual for instructions .
The first 12 Chapter .TIM Advanced timer
SAIUR201 6 The first 125 page
12.4.7. Open circuit function
The breaking function is the braking function controlled by the motor , When the open circuit function is enabled , Modify the output signal level according to the status of relevant control bit .
In any case ,OCx and OCxN No output can be active at the same time , This relates to the motor control commonly used H Bridge circuit structure
reason . The open source can be a clock fault event , The clock security system in the clock controller is reset internally (CSS) Generate , It can also be outside
Part of the open circuit input IO, The two are or operations . When the system is reset and started, the open circuit function is turned off by default , Set the open and dead registers
(TIMx_BDTR) Of BKE To set 1, Enable open circuit function . It can be done by TIMx_BDTR The register of BKP Bit set to open circuit
The effective level of the input pin , Set to 1 Time input BRK Effective for high level , Otherwise, the low level is effective .
When sending open circuit , It will have the following effect :
1. TIMx_BDTR The main output mode in the register is enabled (MOE) The bit is cleared , The output is in invalid 、 Idle or reset state ;
2. The output channel pin level is controlled according to the status of relevant control bit ; When enable channel complementary output , It will automatically control the output according to the situation
Channel level ;
3. take TIMx_SR In register BIF Location 1, And it can produce interruption and DMA Transmission request .
4. If TIMx_BDTR The auto output in the register enables (AOE) Location 1, be MOE The next one will happen UEV
Event automatically reset 1.
12.5. Input capture application
Input capture is generally used in two ways , One aspect is the measurement of pulse jump along time , On the other hand PWM Input measurement .
chart 12-10 Pulse width / Schematic diagram of frequency measurement
The first 12 Chapter .TIM Advanced timer
The first 126 page SAIUR2016
12.5.1. Measure the frequency
When capturing channels TIx When there is a rising edge on , The first capture happened , Counter CNT The value of is latched to the capture register
CCR in , And there's also a capture interrupt , Record a capture in the interrupt service routine ( You can use a flag variable to record ),
And read the value in the capture register to value1 in . When there is a second rising edge , A second capture occurred , Counter CNT Of
The value is latched to the capture register again CCR in , And enter capture interrupt again , In the capture interrupt , Read the value of the capture register
To value3 in , And clear the capture record flag . utilize value3 and value1 We can calculate the period of the signal ( frequency ).
12.5.2. Measure the pulse width
When capturing channels TIx When there is a rising edge on , The first capture happened , Counter CNT The value of is latched to the capture register
CCR in , And there's also a capture interrupt , Record a capture in the interrupt service routine ( You can use a flag variable to record ),
And read the value in the capture register to value1 in . Then change the capture edge to the falling edge , The aim is to capture the fall behind
Along the . When the falling edge comes , A second capture occurred , Counter CNT The value of is latched to the capture register again CCR in ,
And enter capture interrupt again , In the capture interrupt , Read the value of the capture register to value3 in , And clear the capture record flag . however
Then set the capture edge to the rising edge .
In the process of measuring pulse width, we need to switch back and forth to capture the polarity of the edge , If the measured pulse duration is long , The timer will happen
overflow , An update interrupt is generated when overflow occurs , We can record overflow in interrupt .
12.6. PWM The input mode
Another easier way to measure pulse width and frequency is to use PWM The input mode , This pattern is a special case of input capture , only
Can use channels 1 And channel 2, passageway 3 And channel 4 Can't use . Compared with the one above, only one capture register is used to measure pulse width and
Compared with the frequency method ,PWM Input mode requires two capture registers .
chart 12-11 Mapping between input and capture channels
The first 12 Chapter .TIM Advanced timer
SAIUR201 6 The first 127 page
When using PWM When you enter mode , Because an input channel (TIx) It takes up two capture channels (ICx), So a timing
It's in use PWM Only two input channels can be used for input (TIx). We use input channels TI1 Working in PWM transport
In the mode as an example to explain the specific working principle , Other channels, and so on .
PWM The signal is transmitted by the input channel TI1 Get into , the reason being that PWM The reason for the input mode , The signal will be split into two , Along the way
TI1FP1, The other way is TI2FP2. One way is the cycle , The other way is the duty cycle , Which signal corresponds to the period of
Air ratio , You have to set which signal to use as the trigger input from the program , Which signal is the trigger input corresponds to the period , The other
The road is the corresponding duty cycle . The polarity of the signal used as the trigger input also needs to be set , Is it a rising edge or a falling edge , Once set
Set the polarity of the trigger input , The other hardware is automatically configured to capture the opposite polarity , No software configuration required . In a word, it can be concluded that
yes : Select input channel , Determine the trigger signal , Then set the polarity of the trigger signal , the reason being that PWM The reason for the input , The other
The signal is configured by hardware , No software configuration required . When using PWM When entering the mode, the slave mode controller must be configured to reset
Pattern ( Configuration register SMCR Bit SMS[2:0] To achieve ), That is, when we start the trigger signal to capture , meanwhile
Put the counter CNT Reset and clear . Let's analyze it with a more specific sequence diagram PWM The input mode .
chart 12-12 PWM Input mode timing
PWM The signal is transmitted by the input channel TI1 Get into , To configure TI1FP1 It's a trigger signal , Rising edge capture . When the rising edge IC1 and
IC2 Capture at the same time , Counter CNT Zero clearing , When it comes to the falling edge ,IC2 Capture , Now the counter CNT The value of is locked to
Get register CCR2 in , At the next rising edge ,IC1 Capture , Counter CNT The value of is latched to the capture register
CCR1 in . among CCR2+1 It measures the pulse width ,CCR1+1 It measures the period . What we should pay attention to here is CCR2 and CCR1
When calculating the duty cycle and frequency, you must add 1, Because the counter is from 0 Start counting . In terms of software , use PWM
Input mode is easier to measure pulse width and period , The cost is two capture registers .
The first 12 Chapter .TIM Advanced timer
The first 128 page SAIUR2016
12.7. Output comparison application
The output comparison mode has a total of 8 Kind of , Specifically, the register CCMRx Bit OCxM[2:0] To configure . We are only going to talk about the most
frequently-used PWM Pattern , For other modes, please refer to the data manual .
12.7.1. PWM The output mode
PWM Output is the external output pulse width ( The duty cycle ) Adjustable square wave signal , The signal frequency is determined by the auto reload register ARR Of
Values determine , The duty cycle is determined by the comparison register CCR Value determination of .PWM There are two patterns ,PWM1 and PWM2, On the whole, it's
almost , It depends on how you use it , The specific differences are shown in the table 12-1.
form 12-1 PWM1 And PWM2 The difference between patterns
Now let's PWM1 Mode to explain , With a counter CNT The counting direction is also divided into edge alignment mode and center alignment mode
Pattern .PWM The signals are mainly used to control the motor , General motor control uses edge alignment mode ,FOC The motor is generally used
Center alignment mode . We're only going to analyze these two patterns in terms of signal perception ( That is, the signal waveform ) The difference between , Specific in the motor control
The difference is not discussed , You'll know when you really need to use it .
12.7.2. PWM Edge alignment mode
In incremental count mode , Counter from 0 Count to auto overload value ( TIMx_ARR The contents of the register ), And then again from 0
Start counting and generate counter overflow Events
chart 12-13 PWM1 The edge of the pattern aligns the waveform
In edge alignment mode , Counter CNT Working in only one mode , Increasing or decreasing mode . Here we have CNT Work
In incremental mode, for example , In the middle ,ARR=8,CCR=4,CNT from 0 Start counting , When CNT<CCR The value of , OCxREF by
Effective high level , At the same time , Compare interrupt registers CCxIF Set up . When CCR=<CNT<=ARR when ,OCxREF by
The first 12 Chapter .TIM Advanced timer
SAIUR201 6 The first 129 page
Invalid low level . then CNT Again from 0 Start counting and generate counter overflow Events , And so on .
12.7.3. PWM Center alignment mode
chart 12-14 PWM1 The center of the pattern aligns the waveform
In center alignment mode , Counter CNT It's a job to do / In decreasing mode . At the beginning , Counter CNT from 0 open
Start counting to auto overload minus 1(ARR-1), Generate counter overflow event ; Then count down from the auto overload value to 1 Coexist
Generating counter underflow events . After from 0 Start counting again . chart 12-14 yes PWM1 The center of the pattern aligns the waveform ,ARR=8,
CCR=4. The first stage counter CNT Working in incremental mode , from 0 Start counting , When CNT<CCR The value of ,OCxREF
For effective high level , When CCR=<CNT<<ARR when ,OCxREF Invalid low level . The second stage counter CNT Work
In decline mode , from ARR The value of begins to decrease , When CNT>CCR when ,OCxREF Invalid low level , When CCR=>CNT>=1
when ,OCxREF For effective high level .
On the waveform, we divide the waveform into two stages , The first stage is the counter CNT Waveforms working in incremental mode , This
The stage is further divided into ① and ② Two phases , The second stage is the counter CNT Waveforms working in decreasing mode , At this stage we
It is divided into ③ and ④ Two phases . If you want to talk about the characteristics of the waveform in the center aligned mode , That's it ① and ③ The stages are equal in time ,
② and ④ The stages are equal in time . Center alignment patterns are divided into center alignment patterns 1/2/3 Three , Specifically, the register CR1 position
CMS[1:0] To configure . The specific difference is to compare the interrupt flag bit CCxIF When to place 1: Central mode 1 stay CNT Decline
When counting, set 1, Center alignment mode 2 stay CNT Set... When counting up 1, Central mode 3 stay CNT When increasing and decreasing the count
All set 1.
12.8. Timer initialization structure details
In the standard library function header file stm32f10x_tim.h Four initialization structures are established for timer peripherals in , Time base respectively
Initialize structure TIM_TimeBaseInitTypeDef 、 Output comparison initialization structure
TIM_OCInitTypeDef 、 Input capture initialization structure TIM_ICInitTypeDef And open circuit and dead zone initialization structure
TIM_BDTRInitTypeDef , Advanced control timer can use all initialization structures , Universal timer cannot be used
TIM_BDTRInitTypeDef Structure , Basic timers can only use time base structures . Now let's talk about these four structures
The first 12 Chapter .TIM Advanced timer
The first 130 page SAIUR2016
body .
12.8.1. TIM_TimeBaseInitTypeDef
Time base structure TIM_TimeBaseInitTypeDef Used for timer basic parameter setting , And TIM_TimeBaseInit Function coordination
Use to complete the configuration .
Code list 12-1 Timer basic initialization structure
TIM_Prescaler: Timer prescaler settings , The prescaler is the counter clock of the timer CK_CNT, It sets
PSC Register value . The formula is : Counter clock frequency (fCK_CNT) be equal to fCK_PSC / (PSC[15:0] + 1), Can be realized
1 to 65536 frequency division .
TIM_CounterMode: Timer counting mode , Can be set to count up 、 Count down and align Center . Advanced control timer
You are allowed to choose any .
TIM_Period: Timer cycle , It's actually setting the auto overload register ARR Value ,ARR To load to the actual auto reload
Load register ( Shadow register ) Value , The settable range is 0 to 65535.
TIM_ClockDivision: The clock frequency division , Set the timer clock CK_INT Frequency and dead time generator and digital filter sampling
Clock frequency division ratio . You can choose 1、2、4 frequency division .
TIM_RepetitionCounter: Repeat counter , Only 8 position , Only in advanced timers .
12.8.2. TIM_OCInitTypeDef
Output comparison structure TIM_OCInitTypeDef For output comparison mode , And TIM_OCxInit Function is used together to complete
Set timer output channel initialization configuration . Advanced control timer has four timer channels , It must be set separately when using .
Code list 12-2 Timer compare output initialization structure
TIM_OCMode: Compare output mode selection , There are eight in all , The common one is PWM1/PWM2. It sets CCMRx register
The first 12 Chapter .TIM Advanced timer
SAIUR201 6 The first 131 page
OCxM[2:0] The value of a .
TIM_OutputState: Compare output enable , Determine the final output comparison signal OCx Whether to output through external pins . It sets
TIMx_CCER register CCxE/CCxNE The value of a .
TIM_OutputNState: Compare complementary output enable , decision OCx The complementary signals OCxN Whether to output through external pins . It sets up
set CCER register CCxNE The value of a .
TIM_Pulse: Compare the output pulse width , Actually set the comparison register CCR Value , Determine the pulse width . The settable range is 0 to
65535.
TIM_OCPolarity: Compare the output polarity , Optional OCx For high level active or low level active . It determines that the timer channel is valid
level . It sets CCER The register of CCxP The value of a .
TIM_OCNPolarity : Compare complementary output polarity , Optional OCxN For high level active or low level active . It sets
TIMx_CCER The register of CCxNP The value of a .
TIM_OCIdleState: Channel output level setting in idle state , Optional output 1 Or output 0, That is, in the idle state (BDTR_MOE
Position as 0) when , After the dead time, the timer channel outputs high level or low level . It sets CR2 The register of OISx The value of a .
TIM_OCNIdleState: Complementary channel output level setting in idle state , Optional output 1 Or output 0, That is, in the idle state
(BDTR_MOE Position as 0) when , After dead time, the complementary channel of timer outputs high level or low level , The set value must be the same as
TIM_OCIdleState contrary . It's set to be CR2 The register of OISxN The value of a .
12.8.3. TIM_ICInitTypeDef
Input capture structure TIM_ICInitTypeDef For input capture mode , And TIM_ICInit Function with the completion timer
Input channel initialization configuration . If you use PWM Input mode needs to be associated with TIM_PWMIConfig Function with the completion timer
Input channel initialization configuration .
Code list 12-3 Timer input capture initialization structure
TIM_Channel: Capture channels ICx choice , Optional TIM_Channel_1、TIM_Channel_2、TIM_Channel_3 or
TIM_Channel_4 Four channels . It sets CCMRx register CCxS The value of a .
TIM_ICPolarity: Input capture edge trigger selection , Optional rising edge trigger 、 Falling edge trigger or edge jump trigger . It sets
CCER register CCxP Bit and CCxNP The value of a .
TIM_ICSelection : Input channel selection , Capture channels ICx The signal can come from three input channels , Respectively
The first 12 Chapter .TIM Advanced timer
The first 132 page SAIUR2016
TIM_ICSelection_DirectTI 、TIM_ICSelection_IndirectTI or TIM_ICSelection_TRC , The specific differences are shown in the figure
33-15. If it's normal input capture ,4 All channels can be used , If it is PWM Input can only use channels 1 And channel
2. It sets CCRMx The register of CCxS[1:0] The value of a .
chart 12-15 Input channel and capture channel IC The map of
TIM_ICPrescaler: Input capture channel prescaler , Can be set up 1、2、4、8 frequency division , It sets CCMRx The register of
ICxPSC[1:0] The value of a . If you need to capture each valid edge of the input signal , Is set 1 Divide the frequency .IM_ICFilter: transport
Enter capture filter settings , Optional settings 0x0 to 0x0F. It sets CCMRx register ICxF[3:0] The value of a . Generally we don't make
With a filter , It is set to 0.
12.8.4. TIM_BDTRInitTypeDef
Open circuit and dead zone structures TIM_BDTRInitTypeDef It is used to set the parameters of open circuit and dead time , It belongs to advanced timer , use
Channel output status in configuration open circuit , And dead time . It is associated with TIM_BDTRConfig Function configuration uses to complete parameter configuration . this
The members of a structure only correspond to BDTR This register , Please refer to the manual for the specific use and configuration of members BDTR Register details
Describe in detail .
Code list 12-4 Open circuit and dead zone initialization structure
TIM_OSSRState: Off state selection in operation mode , It sets BDTR register OSSR The value of a .
TIM_OSSIState: Off state selection in idle mode , It sets BDTR register OSSI The value of a .
TIM_LOCKLevel: Lock level configuration , BDTR register LOCK[1:0] The value of a .
TIM_DeadTime: Configure the deadband generator , Define the duration of the dead zone , The optional setting range is 0x0 to 0xFF. It sets BDTR
register DTG[7:0] The value of a .
The first 12 Chapter .TIM Advanced timer
SAIUR201 6 The first 133 page
TIM_Break: Open circuit input function selection , It can be enabled or disabled . It sets BDTR register BKE The value of a .
TIM_BreakPolarity: Open the input channel BRK Polarity selection , Select high level active or low level active . It sets BDTR Send
Memory BKP The value of a .
TIM_AutomaticOutput: Auto output enable , It can be enabled or disabled , It sets BDTR register AOE The value of a .
12.9. PWM Complementary output experiment
There are many output comparison modes , Here we have PWM Take output as an example , And through the oscilloscope to observe the waveform . In the experiment, not only
Output waveform in main output channel , The complementary channel also outputs the complementary waveform with the main channel , And add the function of open circuit and dead time .
12.9.1. Hardware design
According to the pin usage of the development board , And refer to table 12-1 Middle timer pin information , Use advanced timers TIM1 The passage of 1
And its complementary channel is used as the waveform output channel of this experiment , Corresponding selection PA8 and PB13 Pin . Divide the two input channels of the oscilloscope into
Don't talk to PA8 and PB13 Pin connection , Used to observe waveforms , And pay attention to the common ground . In order to increase the breaking function , Need to use TIM1_BKIN
Pin , Choose here PB12 Pin . Program we set the pin to high level valid , When BKIN When the pin is set to high or low level ,
Two complementary PWM The output is stopped , It's like a brake .
12.9.2. software design
Here is just the core part of the code , Some variable settings , The inclusion of header files does not involve , For complete code, please refer to
Consider the supporting projects in this chapter . We created two files : bsp_AdvanceTim.c and bsp_AdvanceTim.h Files are used to save time
Device driver and related macro definition .
12.9.3. Programming points
1. The timer uses GP IO initialization
2. Timer time base structure TIM_TimeBaseInitTypeDef initialization
3. Timer output comparison structure TIM_OCInitTypeDef initialization
4. Timer, brake and dead zone structure TIM_BDTRInitTypeDef initialization
The first 12 Chapter .TIM Advanced timer
The first 134 page SAIUR2016
12.9.4. software analysis
Code list 12-5 Macro definition
Using macro definition is very convenient for program upgrade 、 transplant . For the specific meaning of each macro, just look at the program comments .
Code list 12-6 Timer multiplexing function pin initialization
The first 12 Chapter .TIM Advanced timer
SAIUR201 6 The first 135 page
ADVANCE_TIM_GPIO_Config() Function to initialize the timer used related GPIO, When using different GPIO Of
When , Just modify the macro definition in the header file , You don't have to modify this function .
Code list 12-7 Timer mode configuration
The first 12 Chapter .TIM Advanced timer
The first 136 page SAIUR2016
ADVANCE_TIM_Mode_Config() Three structs are initialized in the function , The specific meaning of the members of these three structures can be
Reference resources “ Timer initialization structure details ” Section , The rest of the program can be read by referring to the notes . If modification is needed PWM The cycle of
And duty cycle , Modify the... In the header file ADVANCE_TIM_PERIOD ADVANCE_TIM_PSC and
ADVANCE_TIM_PULSE These three macros will do .PWM The frequency of the signal is calculated by : F =
TIM_CLK/{(ARR+1)*(PSC+1)}, among TIM_CLK be equal to 72MHZ,ARR That is, the value of the auto reload register , Yes
Should be ADVANCE_TIM_PERIOD This macro ,PSC That is, the frequency division factor of the counter clock , Corresponding ADVANCE_TIM_PSC this
A macro .
Code list 12-8 main function
Main The function is very simple , Called ADVANCE_TIM_Init() function , This function calls
ADVANCE_TIM_GPIO_Config() and ADVANCE_TIM_Mode_Config() These two functions complete the timer GPIO lead
Initialization of foot and working mode , At this time , Corresponding GPIO Complementary outputs can be detected on the pins PWM The signal , And bring death
District time , If the program is running ,BKIN If the pin is pulled up ,PWM Output will be banned , It's like a break or a brake
It's like a car .
12.9.5. Download validation
According to the hardware design of the experiment, connect the input channel of the oscilloscope and the pins of the development board ,, Compile the experimental program and download it to the developer
On board , Adjust the oscilloscope to the appropriate parameters , In the oscilloscope display and see a complementary with dead time PWM wave form , Refer to the figure
33-16. As for the signal in the figure, there is a burr because the output pin of the signal is connected with other chips , Be affected by .
The first 12 Chapter .TIM Advanced timer
SAIUR201 6 The first 137 page
chart 12-16 PWM Complementary dead time waveform output
BKIN When the pin is connected to high level ,PWM Output is disabled , It's like a brake , See Fig 12-17.
chart 33-17 PWM Brake output
The first 13 Chapter .I2C Communications
The first 138 page SAIUR2016
The first 13 Chapter .I2C Communications
13.1. Preview before class
Find the answer in the book .
1. What is? SDA?
2. What is a data efficient protocol ?
13.2. summary
What's in this chapter :
(1)I2C Communication protocol
(2) Use I2C Reading and writing EEPROM
13.3. I2C Protocol Brief
I2C Communication protocol (Inter-Integrated Circuit) By Phiilps company-developed , Because it has few pins , The hardware implementation is simple ,
High scalability , Unwanted USART、CAN And so on , Now it is widely used in multiple sets of systems
It's a circuit (IC) Communication between . In Computer Science , Most complex problems can be simplified by layering . If the chip is divided into cores
Layers and on-chip peripherals ;STM32 The standard library is the software layer between registers and user code . For communication protocols , We also share
Layer by layer , The basic thing is to divide it into physical layer and protocol layer . The physical layer specifies that the communication system has mechanical 、 Electronic functions
Some of the features , Ensure the transmission of raw data on physical media . The protocol layer mainly specifies the communication logic , Unify the data packaging of both sender and receiver 、
Unpacking standard . Simply put, the physical layer dictates whether we use our mouth or our limbs to communicate , The protocol layer specifies whether we use Chinese or English
communication . Now we are going to do the following I2C Explain the physical layer and protocol layer of the protocol .
The first 13 Chapter .I2C Communications
SAIUR201 6 The first 139 page
13.3.1. I2C The physical layer
I2C The common connection modes between communication devices are shown in the figure 13-1.
chart 13-1 common I2C Communication system
Its physical layer has the following characteristics :
1. It's a bus that supports devices .“ Bus ” A signal line shared by multiple devices . In a I2C In the communication bus , Can connect many
individual I2C Communication equipment , Support multiple communication hosts and multiple communication slaves .
2. One I2C The bus uses only two bus lines , A two-way serial data line (SDA) , A serial clock line (SCL). data
Lines are used to represent data , The clock line is used for data synchronization .
3. Each device connected to the bus has a separate address , The host can use this address to access different devices .
4. The bus is connected to the power supply through pull-up resistor . When I2C When the device is idle , It will output a high resistance state , And when all the devices are idle , All output
In the high resistance state , Pull the bus to high level by pull-up resistor .
5. When multiple hosts use the bus at the same time , To prevent data conflicts , Arbitration will be used to decide which device will occupy the bus .
6. There are three transmission modes : The standard mode transmission rate is 100kbit/s , The fast mode is 400kbit/s , It can be reached in high speed mode
3.4Mbit/s, But at present, most of them I2C The device doesn't support high speed mode yet .
7. Connected to the same bus IC The number is affected by the maximum capacitance of the bus 400pF Limit .
The first 13 Chapter .I2C Communications
The first 140 page SAIUR2016
13.3.2. Protocol layer
I2C The protocol defines the start and stop signals for communication 、 Data validity 、 Respond to 、 arbitration 、 Clock synchronization and address broadcast .
I2C Basic reading and writing process
Have a look first I2C The basic structure of the communication process , Its communication process is shown in the figure 13-2、 chart 13-3 And graph 13-4.
chart 13-2 The host writes data to the slave
chart 13-3 The host reads data from the slave
chart 13-4 I2C Communication composite format
The shadow data is transferred from the host to the slave S : Transmission start signal SLAVE_ADDRESS: Slave address
The blank data is transferred from the slave to the host R/W: Transmission direction selection bit ,1 For reading ,0 For writing A/ A : The reply (ACK)
Or no response (NACK) The signal P : Stop transmitting signals
These diagrams show that when the master communicates with the slave ,SDA The packet sequence of lines .
among S Indicates that the I2C The transmission start signal generated by the interface (S), Now connect to I2C All slaves on the bus are
You'll receive this signal .
After the initial signal is generated , All slaves start to wait for the slave address signal broadcast by the host (SLAVE_ADDRESS).
stay I2C On the bus , The address of each device is unique , When the address broadcast by the host is the same as the address of a device , This device is just
Was chosen , Unselected devices will ignore subsequent data signals . according to I2C agreement , This slave address can be 7 Bit or 10
The first 13 Chapter .I2C Communications
SAIUR201 6 The first 141 page
position .
After the address bit , Is the selection bit of the transmission direction , This bit is 0 when , Indicates that the following data transmission direction is from the host to the slave
machine , That is, the host writes data to the slave . This bit is 1 when , On the contrary , That is, the host reads data from the slave .
After the slave receives the matching address , The host or from the opportunity returns a reply (ACK) Or no response (NACK) The signal , Only received
After answering the signal , The host can continue to send or receive data .
Writing data
If the configured directional transmission bit is “ Writing data ” Direction , That's the first picture , After the broadcast, the address , After receiving the reply signal , Lord
The slave begins to transfer data to the slave (DATA), The packet size is 8 position , Every time the host sends a byte of data , All have to wait
The slave's response signal (ACK), Repeat the process , It can be transmitted to the slave N Data , This N No size limit . When the data
At the end of the transmission , The master sends a stop signal to the slave (P), Indicates that data is no longer transmitted .
Reading data
If the configured directional transmission bit is “ Reading data ” Direction , In the second picture , After the broadcast, the address , After receiving the reply signal , from
The computer starts to return data to the host (DATA), The packet size is also 8 position , Every time the slave sends a data , Will wait for the host to respond
Answer the signal (ACK), Repeat the process , Can return N Data , This N There's no size limit . When the host wants to stop receiving
Data time , It returns a non response signal to the slave (NACK), The slave automatically stops data transmission .
Read and write data
In addition to basic literacy ,I2C More commonly used in communications are composite formats , That's the third picture , The transmission process has two starting signals
Number (S). Usually in the first transmission , The host by SLAVE_ADDRESS After finding the slave device , Send a paragraph “ data ”, This paragraph
Data is usually used to represent the internal register or memory address of the slave device ( Pay attention to distinguish it from SLAVE_ADDRESS The difference between ); In the
In the second transmission , Read or write the contents of the address . in other words , The first communication was to tell the slave to read and write the address , The second time was
The actual content of reading and writing .
The signals included in the above communication flow are decomposed as follows :
13.3.3. Start and stop signals of communication
The beginning mentioned above (S) And stop (P) Signals are two special states , See the picture 24-5. When SCL The line is at high level SDA
The line switches from high level to low level , This is the beginning of communication . When SCL It's high level SDA Line from low level to high level
Switch , Indicates the stop of communication . Start and stop signals are usually generated by the host computer .
The first 13 Chapter .I2C Communications
The first 142 page SAIUR2016
chart 13-5 Start and stop signals
Data validity
I2C Use SDA Signal lines to transmit data , Use SCL Signal line for data synchronization . See the picture 24-6.SDA The data line is in
SCL One bit of data per clock cycle . When transmitting ,SCL When it's high level SDA The data represented is valid , Is this time
Of SDA Show data for high level “1”, Show data for low level “0”. When SCL Low power level ,SDA Invalid data for ,
Usually at this time SDA Carry out level switching , Prepare for the next presentation of data .
chart 13-6 Data validity
Every data transfer is in bytes , Unlimited number of bytes per transmission .
Address and data direction
I2C Each device on the bus has its own independent address , When the host initiates communication , adopt SDA Signal line sending device address
(SLAVE_ADDRESS) To find the slave .I2C The protocol states that the device address can be 7 Bit or 10 position , In the actual 7 The address of bit should be
It is widely used . A data bit immediately following the device address is used to indicate the direction of data transmission , It's the data direction bit (R/W), The first 8 Bit or
The first 11 position . The data direction bit is “1” Indicates that the host reads data from the slave , This bit is “0” Indicates that the master writes data to the slave . See the picture
12-7.
The first 13 Chapter .I2C Communications
SAIUR201 6 The first 143 page
chart 13-7 Device address (7 position ) And data transmission direction
When reading data direction , The host will release to SDA The control of the signal line , Controlled by a slave SDA The signal line , The host receives the signal , Write
Data direction ,SDA Controlled by the host , The slave receives the signal .
Respond to
I2C The data and address of the transmission are with response . Responses include “ The reply (ACK)” and “ Non response (NACK)” Two signals . As data
At the receiving end , When equipment ( No matter the master or slave computer ) Received I2C After a byte of data or address transferred , If you want the other party to continue sending data ,
You need to send “ The reply (ACK)” The signal , The sender will continue to send the next data ; If the receiver wants to end the data transmission ,
Then send “ Non response (NACK)” The signal , The sender will generate a stop signal after receiving the signal , End signal transmission . see
chart 13-8.
chart 13-8 Responsive and nonresponsive signals
The host generates a clock during transmission , In the 9 When it's a clock , The data sender will release SDA Control right , Controlled by the data receiver SDA,
if SDA High level , Indicates a non response signal (NACK), A low level indicates a reply signal (ACK).
The first 13 Chapter .I2C Communications
The first 144 page SAIUR2016
13.4. STM32 Of I2C Features and Architecture
If we directly control STM32 Of the two GPIO Pin , Used separately for SCL And SDA, According to the sequence of the above signals, we should
seek , Direct like control LED The lamp controls the output of the pin like that ( If it receives data, it reads SDA level ), Can be realized I2C through
News . Again , If we follow USART To control the pins , Can also be realized USART Communications . So just stick to the agreement ,
It's standard communication , No matter how you implement it , Whether it's ST The controller in production is still ATMEL Production memory , can
Interact according to communication standards . Because of direct control GPIO When the pin level generates communication sequence , Need by CPU Control pins at every moment
state , So it's called “ Software emulation protocol ” The way . relatively , also “ Hardware protocol ” The way ,STM32 Of I2C Peripherals on the chip
The door is responsible for achieving I2C Communication protocol , Just configure the peripherals , It will automatically generate communication signals according to protocol requirements , Send and receive data and
cached ,CPU Just check the status of the peripheral and access the data register , You can send and receive data . This is handled by hardware peripherals
I2C The way the agreement was made eased CPU The job of , And make the software design more simple .
13.4.1. STM32 Of I2C Introduction to peripherals
STM32 Of I2C Peripherals can be used as hosts and slaves for communication , Support 100Kbit/s and 400Kbit/s Rate , the 7 position 、
10 Bit device address , Support DMA The data transfer , And it has data verification function . its I2C The peripherals are still there SMBus2.0 agreement ,
SMBus Deal with the I2C similar , It is mainly used in battery management of notebook computer , This tutorial does not expand , Interested readers can refer to
Examination 《SMBus20》 Document understanding .
The first 13 Chapter .I2C Communications
SAIUR201 6 The first 145 page
13.4.2. STM32 Of I2C Architecture analysis
chart 13-9 I2C Architecture diagram
Communication pins
I2C All of the hardware architectures are based on the left side of the figure SCL Line and SDA The line unfolds ( Among them SMBA Lines are used for SMBUS
A warning signal for ,I2C Communication is not used ).STM32 There are multiple chips I2C peripherals , Their I2C Communication signals lead to different
GPIO On the pin , These pins must be configured for use , See the picture 13-1. About GPIO The multiplexing function of pins , With specifications
The book is the standard .
surface 13-1 STM32F10x Of I2C Pin
The first 13 Chapter .I2C Communications
The first 146 page SAIUR2016
Clock control logic
SCL The clock signal of the line , from I2C The interface controls the register according to the clock (CCR) control , The main control parameters are clock frequency .
To configure I2C Of CCR Register can modify the parameters related to communication rate :
1. Can choose I2C Communicating “ standard / Fast ” Pattern , The two models are I2C Corresponding 100/400Kbit/s The communication rate of .
2. In fast mode, you can choose SCL The duty cycle of the clock , Optional Tlow/Thigh=2 or Tlow/Thigh=16/9 Pattern , We know
Avenue I2C The agreement SCL High levels are good for SDA Signal sampling ,SCL When the electricity is low SDA Prepare the next data , modify
SCL The ratio of high to low will affect the data sampling , But in fact, there is not much difference between the two models , If not very strict ,
Just choose here .
3. CCR There's another one in the register 12 Bit configuration factor CCR, It is associated with I2C The input clock sources of peripheral devices work together , produce
SCL The clock ,STM32 Of I2C Peripherals are mounted on APB1 On the bus , Use APB1 The clock source of PCLK1,SCL Letter
The output clock formula of line 1 is as follows :
The results show that CCR by 30, Write this value to this register bit to control IIC The communication rate of is 400KHz, Actually
Even if it's configured SCL The clock is not exactly equal to the standard 400KHz,IIC The correctness of communication will not be affected , Because all
Data communications are all made up of SCL Coordinated , As long as its clock frequency is not much higher than the standard .
The first 13 Chapter .I2C Communications
SAIUR201 6 The first 147 page
Data control logic
I2C Of SDA The signal is mainly connected to the data shift register , The data source and target of data shift register is data register
device (DR)、 Address register (OAR)、PEC Register and SDA cable . When sending data out , Data shift register
It's with “ Data register ” For data sources , Pass the data one by one SDA The signal line goes out ; When receiving data from the outside ,
Data shift register SDA The data sampled by the signal line is stored bit by bit in “ Data register ” in . If data verification is enabled ,
The data received goes through PCE Calculator operation , The results are stored in “PEC register ” in . When STM32 Of I2C Working in
In slave mode , When receiving the device address signal , The data shift register will match the received address with STM32 Of its own “I2C
Address register ” For comparison , In response to host addressing .STM32 Of itself I2C The address can be changed by “ Self address register ”
modify , Supports the use of both I2C Device address , The two addresses are stored separately in OAR1 and OAR2 in .
Overall control logic
The overall control logic is responsible for coordinating the entire I2C peripherals , The working mode of control logic is based on our configuration “ Control register
(CR1/CR2)” Change the parameters of the system . When working with peripherals , The control logic will be modified according to the working state of the peripheral “ Status register (SR1 and
SR2)”, We just need to read the register bits associated with these registers , You can understand I2C Working state of . besides , Control logic
And on request , Responsible for controlling the generation of I2C Interrupt signal 、DMA Requests and all kinds of I2C The communication signal of ( start 、 stop it 、 Response letter
Number, etc. ).
13.4.3. Communication process
Use I2C When peripheral communication , At different stages of communication, it's going to have an impact on “ Status register (SR1 And SR2)” Write different data bits to the parameter
Count , We know the communication status by reading these register flags .
Main transmitter
See the picture 13-10. In the picture is “ Main transmitter ” technological process , Which is the I2C When the host end of communication , The process of sending data out .
chart 13-10 Main transmitter communication process
The main transmitter sending process and event description are as follows :
1. The control generates the starting signal (S), When the start signal occurs , It produces Events “EV5”, And will be right SR1 The register of “SB” Location 1,
Indicates that the starting signal has been sent ;
The first 13 Chapter .I2C Communications
The first 148 page SAIUR2016
2. Then send the device address and wait for the response signal , If there is a slave answering , Then there is an event “EV6” And “EV8”, At this time SR1 Send
The memory's “ADDR” Bit and “TXE” The bit is set 1,ADDR by 1 Indicates that the address has been sent ,TXE by 1 Represents the data register
It's empty ;
3. The above steps are carried out normally, and ADDR After the bit is cleared , We went to I2C Of “ Data register DR” Write the data to be sent ,
At this time TXE Bit will be reset 0, Indicates that the data register is not empty ,I2C Peripherals through SDA The signal line sends out the data bit by bit
After going , And then there will be “EV8” event , namely TXE The bit is set 1, Repeat the process , You can send multiple bytes of data ;
4. When we're done sending data , control I2C The device generates a stop signal (P), This time will produce EV8_2 event ,SR1
Of TXE Bit and BTF All the positions are set 1, Indicates the end of communication . If we can I2C interrupt , All of the above events produce
when , produces I2C Interrupt signal , Enter the same interrupt service function , To I2C After interrupting the service program , Pass the inspection again
Register bit to determine which event .
Main receiver
Let's analyze the main receiver process , Which is the I2C When the host end of communication , The process of receiving data from the outside , See the picture 13-11.
chart 13-11 The main receiver process
The receiving process and event description of the main receiver are as follows :
1. Same as the main sending process , Start signal (S) Is generated by the host side , Control after the start signal , It produces Events “EV5”, And will
Yes SR1 The register of “SB” Location 1, Indicates that the starting signal has been sent ;
2. Then send the device address and wait for the response signal , If there is a slave answering , Then there is an event “EV6” At this time SR1 The register of
“ADDR” The bit is set 1, Indicates that the address has been sent .
3. After receiving the address from the client , Start sending data to the host . When the host receives the data , Will produce “EV7” event ,
SR1 The register of RXNE Be placed 1, Indicates that the receive data register is not empty , After we read the register , It can store data
It's empty , In order to receive the next data . At this point we can control I2C Send reply signal (ACK) Or non response signal (NACK),
If you answer , Then repeat the above steps to receive data , If it's not a response , Then stop transmission ;
4. After sending a non response signal , Generate a stop signal (P), End transmission . In the process of sending and receiving , Some events are not just signs
The status bits we mentioned above , It may also mark status bits such as host status , And you need to clear the sign after you read it
position , More complicated . We can use STM32 Standard library functions to directly detect the composite flags of these events , Reduce the difficulty of programming .
The first 13 Chapter .I2C Communications
SAIUR201 6 The first 149 page
13.5. I2C Initialization structure details
Like other peripherals ,STM32 The standard library provides I2C Initialization structure and initialization function to configure I2C peripherals . initial
Structure and function definition in the library file “stm32f10x_i2c.h” And “stm32f10x_i2c.c” in , When programming, we can combine these two articles
Use or refer to the library help document for comments within the document . Once we understand the initialization structure, we'll be able to I2C Peripherals are easy to use , See the code
single 13-1.
Code list 13-1 I2C Initialize structure
These structural members are described below , The text in brackets is the corresponding parameter in STM32 Macros defined in the standard library :
1. 2C_ClockSpeed
This member sets up I2C The transmission rate of , When calling the initialization function , The function will calculate according to the value we input
Write the clock factor to I2C The clock control register of CCR. The value of the parameter we write should not be higher than 400KHz. actual
Because of CCR Register cannot write clock factor of decimal type , Affect the SCL The actual frequency of may be lower than that set by this member
Parameter values for , At this time, except that the communication is a little slower , It won't be right I2C Other impacts of standard communications .
2. I2C_Mode
This member is choosing I2C How to use , Yes I2C Pattern (I2C_Mode_I2C ) and SMBus Lord 、 Slave mode
(I2C_Mode_SMBusHost、I2C_Mode_SMBusDevice ) .I2C There's no need to distinguish between master and slave modes here , Set up directly
I2C_Mode_I2C that will do .
3. I2C_DutyCycle
This member sets up I2C Of SCL The duty cycle of the line clock . There are two options for this configuration , The time of low level is longer than that of high level
Time is 2:1 ( I2C_DutyCycle_2) and 16:9 (I2C_DutyCycle_16_9). In fact, there is not much difference between the two models ,
The general requirements are not so strict , You can just choose here .
4. I2C_OwnAddress1
This member is configured with STM32 Of I2C The device's own address , Each is connected to I2C All devices on the bus have to have a self
Your address , Being a host is no exception . The address can be set to 7 Bit or 10 position ( Under the influence of I2C_AcknowledgeAddress member
decision ), As long as the address is I2C The only one on the bus .STM32 Of I2C Peripherals can use two addresses at the same time , That is to say, to two people at the same time
The first 13 Chapter .I2C Communications
The first 150 page SAIUR2016
Address response , Members of this structure I2C_OwnAddress1 The configuration is the default 、OAR1 The address of the register , If necessary
To set the second address register OAR2, You can use I2C_OwnAddress2Config Function to configure ,OAR2 I won't support it 10 position
Address , Only 7 position .
5. I2C_Ack_Enable
This member is about I2C Answer settings , Set to enable to send a response signal . This experiment is configured to allow responses
(I2C_Ack_Enable), This is what most people follow I2C Communication requirements for standard equipment , Change to no response (I2C_Ack_Disable)
It often leads to communication errors .
6. I2C_AcknowledgeAddress
This member chooses I2C The addressing mode of is 7 A still 10 Bit address . This needs to be connected to I2C Of the devices on the bus
Address selection , The configuration of this member also affects I2C_OwnAddress1 member , Only here is set to 10 Bit mode ,
I2C_OwnAddress1 To support 10 Bit address . After configuring these structure member values , Call library function I2C_Init The structure can be
Write the configuration of to the register .
13.6. I2C— Reading and writing EEPROM experiment
EEPROM It's a memory that doesn't lose data after power down , Commonly used to store some configuration information , So that when the system is powered back on
Waiting to be loaded .EEPOM The most common way of communication for chips is I2C agreement , This section uses EEPROM Reading and writing experiments for you
Explain STM32 Of I2C Usage method . In the experiments STM32 Of I2C Peripherals are in main mode , They are used as main transmitter and main receiver respectively
device , Ensure normal communication by querying events .
13.6.1. Hardware design
chart 13-12 EEPROM Hardware connection diagram
In this experiment board EEPROM chip ( model :AT24C02) Of SCL And SDA The pins are connected to STM32 Corresponding
The first 13 Chapter .I2C Communications
SAIUR201 6 The first 151 page
I2C In the pins , Combined with pull-up resistor , Constitute the I2C Communication bus , They use I2C Bus interaction .EEPROM Chip devices
The total address is 7 position , Among them high 4 The bit is fixed to :1010 b, low 3 The position is decided by A0/A1/A2 The level of the signal line determines , See the picture
13-13, In the picture R/W It's the read-write direction bit , It's not about the address .
chart 13-13 EEPROM Device address ( Excerpt from 《AT24C02》 Specifications )
Follow our link here ,A0/A1/A2 Are all 0, therefore EEPROM Of 7 Bit device address is :101 0000b , namely
0x50. because I2C In communication, the address is often connected with the direction of reading and writing to form a 8 digit , And when R/W Position as 0 when , surface
Write direction , So add 7 Bit address , Its value is “0xA0”, This value is often called I2C The equipment “ Write the address ”; When R/W Position as 1 when ,
The direction of reading , add 7 Bit address , Its value is “0xA1”, This value is often called “ Read the address ”.
EEPROM There's another one in the chip WP Pin , With write protect function , When the pin level is high , Write data forbidden , When
Pin for low level , Writable data , We're directly grounded , Don't use the write protect function .
13.6.2. software design
In order to make the project more organized , We read and write EEPROM The relevant code is stored separately , Easy to transplant later . stay “ work
The template ” On top of the new “bsp_i2c_ee.c” And “bsp_i2c_ee.h” file , These files can also be named according to your preference , They don't belong to
STM32 Content of the standard library , It is written by ourselves according to the application needs .
13.6.3. Programming points
1. Configure the target pin for communication to be in open drain mode ;
2. Can make I2C Peripheral clock ;
3. To configure I2C The mode of peripherals 、 Address 、 Rate and other parameters and enable I2C peripherals ;
4. Write basic I2C Functions that send and receive by byte ;
5. Write, read and write EEPROM Functions that store content ;
6. Write a test program , Check the read and write data .
The first 13 Chapter .I2C Communications
The first 152 page SAIUR2016
8.
13.6.4. The code analysis
We put I2C Hardware related configurations are defined in the form of macros to “bsp_i2c_ee.h” In file , See code list 13-2.
Code list 13-2 I2C Hardware configuration related macros
The above code is based on the hardware connection , with EEPROM Communication uses I2C Number 、 Pin numbers are encapsulated in macros , And set
The meaning of self I2C Address and communication rate , In order to use when configuring mode .
Use the macro above , To write I2C GPIO Initialization function of the pin , See code list 13-2.
Code list 13-3 I2C GPIO Initialization function
Turn on the relevant clock and initialize GPIO Pin , The execution flow of the function is as follows :
1. Use GPIO_InitTypeDef Definition GPIO Initializing structure variables , So that the following can be used for storage GPIO To configure ;
2. Call library function RCC_APB1PeriphClockCmd( Macro in the code EEPROM_I2C_APBxClock_FUN) Can make
The first 13 Chapter .I2C Communications
SAIUR201 6 The first 153 page
I2C Peripheral clock , call RCC_APB2PeriphClockCmd ( Macro in the code
EEPROM_I2C_GPIO_APBxClock_FUN) Enable I2C The pins use GPIO Port clock , When called, we make
use “|” Configure two pins at the same time .
3. towards GPIO Initialize structure assignment , Initialize the pins to multiplexed open drain mode , it is to be noted that I2C The pins must use this
Pattern .
4. Use the above to initialize the configuration of the structure , call GPIO_Init Function writes parameters to the register , complete GPIO The initialization .
The above is just a configuration I2C Pins used , Not really I2C Configuration of mode , See code list 13-4.
The first 13 Chapter .I2C Communications
The first 154 page SAIUR2016
Code list 13-4 To configure I2C Pattern
be familiar with STM32 I2C In terms of structure , This initialization procedure is very easy to understand , It is the I2C Peripheral communication clock SCL It's low
/ The high level ratio is set to 2, Enable response function , Use 7 Bit address I2C_OWN_ADDRESS7 And the rate configuration is
I2C_Speed( In the front bsp_i2c_ee.h Defined macro ). Finally, the library function is called I2C_Init Write these configurations to registers , And call
I2C_Cmd Functions enable peripherals . For the convenience of calling , We put I2C Of GPIO And mode configuration I2C_EE_Init Function encapsulation
get up . towards EEPROM Write a byte of data
Initialize well I2C After peripherals , You can use I2C Communications , Let's see how to EEPROM Write a byte of data ,
See code list 13-5.
The first 13 Chapter .I2C Communications
SAIUR201 6 The first 155 page
Code list 13-5 towards EEPROM Write a byte of data
The first 13 Chapter .I2C Communications
The first 156 page SAIUR2016
Let's analyze it first I2C_TIMEOUT_UserCallback function , Only macro is called in its function body
EEPROM_ERROR, This macro encapsulates printf function , It is convenient to use serial port to print debugging information to upper computer , When reading the code, put
It's like printf Function . stay I2C Many processes of communication , All events need to be detected , Only when an event is detected can we continue to the next
Step by step operation , But sometimes communication errors or I2C The bus is occupied , We can't wait endlessly , So we set everything
There is an upper limit of waiting time for each piece of inspection , If you exceed this time , We call I2C_TIMEOUT_UserCallback The output of the function is called
Try information ( Or you can add other operations yourself ), And terminate I2C Communications .
Understanding this mechanism , Another analysis I2C_EE_ByteWrite function , This function implements the I2C
Main transmitter communication flow :
1. Use library functions I2C_GenerateSTART produce I2C Start signal , Among them EEPROM_I2C Macro is the previous hardware definition
dependent I2C Number ;
2. Yes I2CTimeout Variable assignment to macro I2CT_FLAG_TIMEOUT, This I2CTimeout The variables are in the following while
Every cycle in the cycle minus 1, The loop calls library functions I2C_CheckEvent Detect events , If an event is detected , Then enter
Into the next phase of communication , If no event is detected, stay here to detect , When testing I2CT_FLAG_TIMEOUT Time
If you haven't waited for the event, you think the communication failed , Call the previous I2C_TIMEOUT_UserCallback Output debugging information , and
Out of communication ;
3. Call library function I2C_Send7bitAddress send out EEPROM The device address of , And set the data transmission direction to
I2C_Direction_Transmitter( That is, the direction of transmission ), The data transmission direction is set by I2C The correspondence follows the address
Of R/W Bit implemented . Send the address and detect it in the same way EV6 sign ;
4. Call library function I2C_SendData towards EEPROM Send the internal address to be written , The address is I2C_EE_ByteWrite
Function's input parameters , Wait after sending EV8 event . Note that the internal address follows the EEPROM Address no
equally , The above refers to I2C The independent address of the bus device , The internal address here refers to EEPROM Data organization within
Address , It can also be understood as EEPROM Memory address or I2C The register address of the device ;
5. Call library function I2C_SendData towards EEPROM Send data to be written , The data is I2C_EE_ByteWrite Letter
The input parameter of the number , Wait after sending EV8 event ;
6. One I2C The communication process is over , call I2C_GenerateSTOP Send stop signal . In this communication process ,STM32 real
On the occasion of I2C towards EEPROM Sent two data , But why was the first data interpreted as EEPROM The memory of
site ? This is from EEPROM Single byte write timing defined by ourselves , See the picture 13-14.
The first 13 Chapter .I2C Communications
SAIUR201 6 The first 157 page
chart 13-14 EEPROM Single byte write timing ( Excerpt from 《AT24C02》 Specifications )
EEPROM Single byte timing rules for , When you write data to it , The first byte is the memory address , The second byte is to write
The data content entered . So we need to understand : command 、 The essence of address is data , The interpretation of the data is different , It has a different
function .
Multi byte write and status wait
After the end of single byte write communication ,EEPROM The chip will erase the contents of the memory address according to the communication result , It takes a while
Period of time , So when we write data many times , We have to wait first EEPROM Internal erasure complete . Multiple data writing process, see code
detailed list 13-6.
Code list 13-6 Multibyte write
This code is relatively simple , Use it directly for Loop calls the previously defined I2C_EE_ByteWrite Functions are byte by byte
Geotropism EEPROM Send data to be written . It is called before each data is written to the communication I2C_EE_WaitEepromStandbyState
Function to wait for EEPROM Internal erasure complete , The definition of this function is shown in the code listing 13-7.
The first 13 Chapter .I2C Communications
The first 158 page SAIUR2016
Code list 13-7 wait for EEPROM In a state of readiness
The main implementation of the function is to EEPROM Send it device address , testing EEPROM Response , if EEPROM Received
Return the response signal after the address , said EEPROM You are ready to , You can start the next communication . Function to detect the response by reading
take STM32 Of SR1 The register of ADDR Bit and AF Bit to achieve , When I2C When the device responds to the address ,ADDR Meeting
Set up 1, If the answer fails ,AF Position meeting position 1.
EEPROM Page write
In the above data communication , Every time you write data, you need to write to EEPROM Send write address , We want to continue
When multiple data are written to the address , Just tell me EEPROM The first memory address address1, The following data is written to
address2、address3… This can save communication time , Speed up . In response to this demand ,EEPROM It defines one
Page write timing , See the picture 13-15.
chart 13-15 EEPROM Page write timing ( Excerpt from 《AT24C02》 Specifications )
According to page write timing , The first data is interpreted as the memory address to be written to address1, It can be sent continuously n Data ,
The data is written to memory in turn . among AT24C02 The chip page write timing of the model can be sent at most once 8 Data ( namely
n = 8 ), This value is also called page size , Some types of chips can transfer up to 16 Data .EEPROM Page of
Write code implementation, see the code list 13-8.
The first 13 Chapter .I2C Communications
SAIUR201 6 The first 159 page
Code list 13-8 EEPROM Page write
The main body of the page write function is the same as the single byte write function , It's just that when it's sending data , Use for Cycle control
Sending multiple data , It is generated after sending multiple data I2C Stop signal , As long as the data transmitted each time is less than or equal to EEPROM when
The first 13 Chapter .I2C Communications
The first 160 page SAIUR2016
The page size specified by the order , It can be transmitted normally . Fast write multibyte using EEPROM How to write pages , We can improve the previous “ many
Byte write ” function , Speed up transmission , See code list 13-9.
Code list 13-9 Write multibyte functions quickly
The first 13 Chapter .I2C Communications
SAIUR201 6 The first 161 page
Many readers think that the operation of this code is very complicated , Look not to understand , In fact, its main purpose is to paginate the input data ( This type
Chip number, every page 8 Bytes ) , See table 24-2 . adopt “ to be divisible by ” Calculate the data to be written NumByteToWrite Can write more
Less “ Full page ”, The calculated value is stored in NumOfPage in , But sometimes the data doesn't just fill the full page , A little more
come out , adopt “ Seeking remainder ” calculated “ Number of data less than one page ” It's stored in NumOfSingle in . After calculation, it is transmitted by page
NumOfPage Second full page data and last NumOfSing Data , Use page transfer , Faster than previous single byte data transfers
quite a lot . In addition to the basic paging transport , Also consider the first address , See table 24-3. If the first address is not exactly aligned to the top of the page
site , You'll need one count value , It is used to store the page full of the address from the first address , How much more data can be written . actual
When transmitting , Let's start with this part count Write data first , Fill in the page , And then put the rest of the data (NumByteToWrite-count), Again
Repeat the above calculation NumOPage And NumOfSingle The process of , Page by page to EEPROM.
1. if writeAddress=16, Calculated Addr=16%8= 0 ,count=8-0= 8;
2. meanwhile , if NumOfPage=22, Calculated NumOfPage=22/8= 2,NumOfSingle=22%8= 6.
3. Data transmission is shown in the table 13-2
The first 13 Chapter .I2C Communications
The first 162 page SAIUR2016
surface 13-2 When the first address is aligned to the page
4. if writeAddress=17, Calculated Addr=17%8= 1,count=8-1= 7;
5. meanwhile , if NumByteToWrite =22,
6. The first count Get rid of , Special treatment , The calculation is new NumByteToWrite =22-7= 1,
7. Calculated NumOfPage=15/8= 1,NumOfSingle=15%8= 7.
8. Data transmission is shown in the table 13-3
surface 13-3 When the first address is not aligned to the page
Last , emphasize ,EEPROM Supported page writing is just an acceleration I2C The transmission timing of , In fact, not every
Read and write in pages every time ,EEPROM It supports random access ( Read and write any address directly ), Like the previous single byte
write in . In some memory , Such as NAND FLASH, It must be in accordance with Block Written in , For example, each Block by 512 or
4096 byte , The minimum unit of data writing is Block, You need to erase the entire Block;NOR FLASH Before writing
Must be Sector/Block Erase... For units , Then it can be written in bytes . And ours EEPROM Data write and erase the most
The small unit is “ byte ” instead of “ page ”, There is no need to erase the whole page before data is written .
EEPROM Reading data
EEPROM Reading data is a composite I2C sequential , It actually includes a write process and a read process , See the picture
13-16.
The first 13 Chapter .I2C Communications
SAIUR201 6 The first 163 page
chart 13-16 EEPROM Data reading timing
In the first communication process of reading sequence , Use I2C Sending device address addressing ( Write the direction ), Then send the... To read “ In memory
site ”; In the second communication process , Again using I2C Sending device address addressing , But the data direction at this time is the reading direction ; Here
After a process ,EEPROM Will return to the host from “ Memory address ” Starting data , One byte at a time , As long as the mainframe
The response is “ Answer signal ”, It will be transmitted all the time , When the host wants to end the transmission , Is sent “ No response signal ”, And “ Stop the letter
Number ” End communication , As a slave EEPROM It will also stop transmitting . See the code list for the implementation code 13-10.
Code list 13-10 from EEPROM Reading data
The first 13 Chapter .I2C Communications
The first 164 page SAIUR2016
The first 13 Chapter .I2C Communications
SAIUR201 6 The first 165 page
The write process in this section is similar to the previous write byte function , When receiving data during reading , You need to use library functions
I2C_ReceiveData To read . The response signal goes through the library function I2C_AcknowledgeConfig To send the ,DISABLE
It is a non response signal ,ENABLE In response to the signal .
main file
EEPROM Read and write test functions
After completing the basic read and write functions , Next, we write a read-write test function to verify the driver , See code list 13-11.
Code list 13-11 EEPROM Read and write test functions
The first 13 Chapter .I2C Communications
The first 166 page SAIUR2016
Fill an array in the code first , The contents of the array are 1,2,3 to N, Then write the contents of this array to EEPROM in ,
When writing, single byte writing or page writing can be used . After writing, write from EEPROM Read data from the address of , hold
Read and write data for verification , If it is consistent, the reading and writing are normal , Otherwise, there are problems in the reading and writing process or EEPROM chip
Is not normal . The code used in it EEPROM_INFO Follow EEPROM_ERROR Macro similar , All right. printf Encapsulation of functions ,
Use and read code as if it were printf Function is good . The specific macro definition is “bsp_i2c_ee.h In file ”, In later generations
Code we often use similar macro to output debugging information .
main function
Final compilation main function , Function to initialize the serial port 、I2C peripherals , And then call the above I2C_Test Function for reading and writing test
try , See code list 13-12.
The first 13 Chapter .I2C Communications
SAIUR201 6 The first 167 page
Code list 13-12 main function
13.6.5. Download validation
use USB Line connection development board “USB TO UART” Interface and computer , Open the serial port debugging assistant at the computer end , Put the compiled program
Download to the development board . In the serial port debugging assistant, you can see EEPROM Debugging information of the test .
chart 13-17 EEPROM Test success
The first 13 Chapter .I2C Communications
The first 168 page SAIUR2016
13.7. Practice after class
1. stay EEPROM In the test procedure , Write data using single byte write and page write functions respectively , Compare the time they take .
2. Try to use EEPROM Storage int Integer variables ,float Floating point variable of type , Write programs to write data , And read out the verification .
3. Try to put I2C The mode of communication pin is changed to non open drain mode , Test whether it can communicate normally , Why? ?
4. see “bsp_i2c_ee.h” In file EEPROM_ERROR、EEPROM_INFO、EEPROM_DEBUG macro , Explain why
To use such a macro to output debugging information , Instead of using printf function .
The first 14 Chapter .SPI Communications
SAIUR201 6 The first 169 page
The first 14 Chapter .SPI Communications
14.1. Preview before class
Find the answer in the book .
1. SPI and I2C What's the difference? ?
14.2. summary
What's in this chapter :
(1)SPI Communication protocol
(2) Use I2C Read write serial FLASH
14.3. SPI Protocol Brief
SPI Protocol is a communication protocol proposed by Motorola (Serial Peripheral Interface), Serial peripheral interface , yes
A high speed full duplex communication bus . It is widely used in ADC、LCD And so on MCU between , High communication speed is required
The occasion of . When learning this chapter , But with I2C Chapter contrast reading , Experience the difference between the two communication buses and EEPROM Memory FLASH
The difference between memory . Now we are going to do the following SPI Explain the physical layer and protocol layer of the protocol .
14.3.1. SPI The physical layer
SPI The common connection modes between communication devices are shown in the figure 14-1.
The first 14 Chapter .SPI Communications
The first 170 page SAIUR2016
chart 14-1 common SPI Communication system
SPI Communication use 3 Bus and chip selection line ,3 The buses are SCK、MOSI、MISO, The selection line is SS , Their
The functions are described as follows :
1. S S ( Slave Select): Select the signal line from the device , It is often referred to as a chip selection signal line , Also known as NSS、CS, The following is used NSS Express .
When there is more than one SPI From equipment to SPI When the host is connected , Other signal lines of the equipment SCK、MOSI And MISO Parallel to at the same time
same SPI On the bus , That is, no matter how many slaves there are , All use this together 3 A bus ; And each slave has its own
This one of the NSS The signal line , This signal line monopolizes a pin of the host , How many slave devices are there , There are just as many chip selection signals
Line .I2C In the protocol, address by device address 、 Select a device on the bus and communicate with it ; and SPI There's nothing in the agreement
There's a device address , It USES NSS Signal line to address , When the host wants to select a slave device , Take this from the device's NSS The signal line is set up
Set to low level , The slave device is selected , That is, the selection is valid , Then the host starts to communicate with the selected slave device SPI Communications .
therefore SPI Communications to NSS Line set low level as start signal , With NSS The line is pulled up as an end signal .
2. SCK (Serial Clock): Clock signal line , For communication data synchronization . It is generated by the communication host , Determines the rate of communication ,
Different devices support different maximum clock frequencies , Such as STM32 Of SPI The maximum clock frequency is fpclk/2, One of the two devices
When we communicate with each other , Communication rate is limited by low speed equipment .
3. MOSI (Master Output, Slave Input): Main device output / Input from device pin . The data of the host is transmitted from this signal line
Out , The slave reads the data sent by the host through this signal line , That is, the direction of data on this line is from the host to the slave .
4. MISO(Master Input,,Slave Output): Master input / Output pin from device . The host reads data from this signal line ,
The data of the slave is output to the host by this signal line , That is, the direction of data on this line is from the host to the slave .
The first 14 Chapter .SPI Communications
SAIUR201 6 The first 171 page
14.3.2. Protocol layer
And I2C Similar ,SPI The protocol defines the start and stop signals for communication 、 Data validity 、 Clock synchronization, etc .
SPI Basic communication process
Have a look first SPI Communication sequence of communication , See the picture 14-2.
chart 14-2 SPI Communication sequence
This is the communication sequence of a host .NSS、SCK、MOSI The signals are generated by the host control , and MISO The signal from the slave machine
produce , The master reads data from the slave through the signal line .MOSI And MISO The signal is only in NSS It works when it's low ,
stay SCK Every clock cycle of MOSI and MISO Transmit one bit of data .
The signals included in the above communication flow are decomposed as follows :
Start and stop signals of communication
In the figure 14-2 The label in ① It's about ,NSS The signal line goes from high to low , yes SPI The starting signal for communication .NSS Each slave has its own
Exclusive signal line , When the slave is on its own NSS When the line detects the starting signal , I knew I was chosen by the host , Begin to prepare with the Lord
Computer communication . The label in the figure ⑥ It's about ,NSS The signal goes from low to high , yes SPI Stop signal for communication , It means the end of this communication , Slave
The selected state of is canceled .
Data validity
SPI Use MOSI And MISO Signal lines to transmit data , Use SCK Signal line for data synchronization .MOSI And MISO
The data line is in SCK One bit of data per clock cycle , And the input and output of data are carried out at the same time . When data is transmitted ,MSB First
Line or LSB There is no hard and fast rule in advance , But make sure that two SPI The same protocol is used between communication devices , In general, we use
chart 14-2 Medium MSB First mode .
Look at ②③④⑤ At the label ,MOSI And MISO Data in SCK The rising edge of the output changes during , stay SCK Of
The falling edge is sampled . That is to say SCK The falling edge of the moment ,MOSI And MISO The data is valid , High level means data “1”,
Show data for low level “0”. At other times , Invalid data ,MOSI And MISO Prepare for the next presentation of data .SPI Every time
One data transfer can 8 Bit or 16 Bit as unit , There is no limit to the number of units per transmission .
The first 14 Chapter .SPI Communications
The first 172 page SAIUR2016
CPOL/CPHA And communication mode
The picture above 14-2 The timing in is just SPI One of the communication modes in ,SPI There are four communication modes , they
The main difference is when the bus is idle SCK The clock state and the sampling time of data . For convenience , Introduce here “ Clock polarity
CPOL” and “ Clock phase CPHA” The concept of . Clock polarity CPOL Refer to SPI When the communication device is idle ,SCK The signal
Line level signal ( namely SPI Before communication starts 、NSS The line is at high level SCK The state of ).CPOL=0 when , SCK In the idle state
It's a low level when it's in state ,CPOL=1 when , On the contrary . Clock phase CPHA It refers to the sampling time of data , When CPHA=0 when ,MOSI
or MISO The signal on the data line will be SCK Clock line “ Odd edge ” Be sampled . When CPHA=1 when , The data line is in SCK
Of “ Even edge ” sampling . See the picture 14-3 And graph 14-4.
chart 14-3 CPHA=0 At the time of the SPI Communication mode
Let's analyze this CPHA=0 Sequence diagram . First , according to SCK Level in idle state , There are two cases .SCK
When the signal line is at low level in idle state ,CPOL=0; The idle state is high level ,CPOL=1. No matter what CPOL=0 still =1, because
The clock phase configured for us CPHA=0, You can see that in the diagram , Sampling time is all in SCK The odd edge of . Pay attention to when
CPOL=0 When , The odd edge of the clock is the rising edge , and CPOL=1 When , The odd edge of the clock is the falling edge . therefore SPI
The sampling time is not raised by / The falling edge determines .MOSI and MISO The valid signal of the data line is SCK The odd edge of is not
change , The data signal will be in SCK Odd edges are sampled , At non sampling times ,MOSI and MISO It's only when the signal is valid that the switch takes place .
Similarly , When CPHA=1 when , Not subject to CPOL Influence , The data signal is in SCK Even edges of are sampled , See the picture 14-4.
The first 14 Chapter .SPI Communications
SAIUR201 6 The first 173 page
chart 14-4 CPHA=1 At the time of the SPI Communication mode
from CPOL And CPHA Different states of ,SPI It's divided into four patterns , See table 25-1, The master and slave need to work in the same
Normal communication can only be achieved in the mode of , In practice, it is more used “ Pattern 0” And “ Pattern 3”.
surface 14-1 SPI Four models of
14.4. STM32 Of SPI Features and Architecture
And I2C It's the same with peripherals ,STM32 The chip is also integrated specifically for SPI Protocol communication peripherals .
14.4.1. STM32 Of SPI Introduction to peripherals
STM32 Of SPI Peripherals can be used as hosts and slaves for communication , Support the highest SCK The clock frequency is fpclk/2(STM32F103
The default chip model is fpclk1 by 72MHz,fpclk2 by 36MHz), Fully support SPI Agreed 4 Patterns , Data frame length
Can be set to 8 Bit or 16 position , Data can be set MSB Go ahead or LSB Go ahead . It also supports two-wire full duplex ( In the previous section
SPI Pattern CPOL CPHA Idle SCK Clock sampling time
0 0 0 Low level odd edge
1 0 1 Low level even edge
2 1 0 High level odd edge
3 1 1 High level even edge
The first 14 Chapter .SPI Communications
The first 174 page SAIUR2016
It's all this model )、 Two line one-way and one line mode . The two-line one-way mode can be used at the same time MOSI And MISO Data line direction
Transmitting data in one direction , It can double the transmission speed . Single line mode can reduce hardware wiring , Of course, this rate will be affected by
influence . We only talk about two-wire full duplex mode .
14.4.2. TM32 Of SPI Architecture analysis
chart 14-5 SPI Architecture diagram
Communication pins
SPI All of the hardware architectures are shown in figure 14-5 Middle left MOSI、MISO、SCK And NSS The line unfolds .STM32 The chip has
Multiple SPI peripherals , Their SPI Communication signals lead to different GPIO On the pin , You must configure these specified indexes when using them
foot , See table 14-2.
surface 14-2 STM32F10x Of SPI Pin
among SPI1 yes APB2 Equipment on , The highest communication rate is 36Mbtis/s,SPI2、SPI3 yes APB1 Equipment on , most
The high communication rate is 18Mbits/s. Except for the communication rate , There is no difference in other functions . among SPI3 The pin of the download interface is used ,
The default function of these pins is to download , The second function is IO mouth , If you want to use SPI3 Interface , The program must first disable this
The first 14 Chapter .SPI Communications
SAIUR201 6 The first 175 page
How many? IO The download function of the port . Generally, when resources are not very tight , These are a few IO The port is designed for downloading and debugging programs
order , Will not be reused as SPI3.
Clock control logic
SCK The clock signal of the line , By baud rate generator according to “ Control register CR1” Medium BR[0:2] Bit control , That's right fpclk
The division factor of the clock , Yes fpclk The result of frequency division is SCK The output clock frequency of the pin , The calculation method is shown in table 14-3.
surface 14-3 BR You are right fpclk Frequency division of the system
Among them fpclk Frequency means SPI Where APB Bus frequency ,APB1 by fpclk1,APB2 by fpckl2. By matching
Set up “ Control register CR” Of “CPOL position ” And “CPHA” You can put SPI Set to the previous analysis 4 Kind of SPI Pattern .
Data control logic
SPI Of MOSI And MISO All connected to the data shift register , Data source and target receiving of data shift register 、
Send buffer and MISO、MOSI Line . When sending data out , Data shift register to “ Send buffer ” For data sources ,
Send the data bit by bit through the data line ; When receiving data from the outside , The data shift register samples the data line to
The data is stored bit by bit in “ Receive buffer ” in . By writing SPI Of “ Data register DR” Fill in the data to send F buffer
In the area , Communication reading “ Data register DR”, You can get the contents of the receive buffer . The data frame length can be determined by “ Control deposit
device CR1” Of “DFF position ” configure 8 Bit and 16 Bit mode ; To configure “LSBFIRST position ” Can choose MSB First or LSB First
That's ok .
Overall control logic
The overall control logic is responsible for coordinating the entire SPI peripherals , The working mode of control logic is based on our configuration “ Control register
(CR1/CR2)” Change the parameters of the system , The basic control parameters include the ones mentioned above SPI Pattern 、 Baud rate 、LSB Go ahead 、 A master-slave mode 、
One way, two-way and so on . When working with peripherals , The control logic will be modified according to the working state of the peripheral “ Status register (SR)”, We just need to read
Take the register bit related to the status register , You can understand SPI I'm in a better working state . besides , The control logic is also required , negative
Responsibility control produces SPI Interrupt signal 、DMA Request and control NSS The signal line . Practical application , We don't usually use STM32 SPI
The standard of peripherals NSS The signal line , It's easier to use the normal GPIO, The software controls its level output , And that creates communication
Start and stop signals .
14.4.3. Communication process
STM32 Use SPI When peripheral communication , At different stages of communication, it's going to have an impact on “ Status register SR” Write different data bits to the parameter
Count , We know the communication status by reading these register flags . chart 14-6 Is in the “ Main mode ” technological process , namely STM32 As SPI
The process of sending and receiving data at the host end of communication .
The first 14 Chapter .SPI Communications
The first 176 page SAIUR2016
chart 14-6 Main transmitter communication process
The main mode sending and receiving process and event description are as follows :
1. control NSS The signal line , Generate the starting signal ( There is no picture of );
2. Write the data to be sent to “ Data register DR” in , The data is stored in the send buffer ;
3. Communication begins ,SCK The clock starts to run .MOSI The data in the transmit buffer is transmitted bit by bit ;MISO Then put
The data is stored bit by bit in the receive buffer ;
4. When one frame of data is sent ,“ Status register SR” Medium “TXE Sign a ” Will be placed 1, It means that one frame has been transmitted , Hair
Send buffer is empty ; Similarly , When receiving a frame of data ,“RXNE Sign a ” Will be placed 1, It means that one frame has been transmitted ,
The receive buffer is not empty ;
5. Waiting to arrive “TXE Sign a ” by 1 when , To continue sending data , Then go to “ Data register DR” Write data ;
Waiting to arrive “RXNE Sign a ” by 1 when , By reading the “ Data register DR” You can get the contents of the receive buffer .
If we can TXE or RXNE interrupt ,TXE or RXNE Set up 1 It's going to produce SPI Interrupt signal , Enter the same
An interrupt service function , To SPI After interrupting the service program , You can check the register bits to see which event , And then separately
Handle . You can also use DMA The way to send and receive “ Data register DR” Data in .
The first 14 Chapter .SPI Communications
SAIUR201 6 The first 177 page
14.5. SPI Initialization structure details
Like other peripherals ,STM32 The standard library provides SPI Initialization structure and initialization function to configure SPI peripherals . initial
Structure and function definition in the library file “stm32f10x_spi.h” And “stm32f10x_spi.c” in , When programming, we can combine these two articles
Use or refer to the library help document for comments within the document . Once we understand the initialization structure, we'll be able to SPI Peripherals are easy to use , See the code
single 14-1.
Code list 14-1 SPI Initialize structure
These structural members are described below , The text in brackets is the corresponding parameter in STM32 Macros defined in the standard library :
1. SPI_Direction
This member setup SPI The direction of communication , Can be set to 2-wire full duplex (SPI_Direction_2Lines_FullDuplex), Two lines only connect
closed (SPI_Direction_2Lines_RxOnly) , One line only receives (SPI_Direction_1Line_Rx) 、 Single line send only mode
(SPI_Direction_1Line_Tx).
2. SPI_Mode
This member setup SPI Working in host mode (SPI_Mode_Master) Or slave mode (SPI_Mode_Slave ), These two models
The biggest difference is SPI Of SCK The timing of the signal line ,SCK The time sequence of is generated by the host in the communication . If it is configured as a slave
Pattern ,STM32 Of SPI Peripherals will accept external SCK The signal .
3. SPI_DataSize
This member may choose SPI The data frame size of communication is 8 position (SPI_DataSize_8b) still 16 position
(SPI_DataSize_16b).
4. SPI_CPOL and SPI_CPHA
These two member configurations SPI The polarity of the clock CPOL And clock phase CPHA, These two configurations affect SPI The communication mode of
type , About CPOL and CPHA Please refer to the previous “ Communication mode ” Section . Clock polarity CPOL member , Can be set to high level
(SPI_CPOL_High) Or low level (SPI_CPOL_Low ). Clock phase CPHA Can be set to SPI_CPHA_1Edge( stay
The first 14 Chapter .SPI Communications
The first 178 page SAIUR2016
SCK The odd edge of the data collection ) or SPI_CPHA_2Edge ( stay SCK Even edge of the data collection ) .
5. SPI_NSS
This member configures NSS The mode of use of pins , You can choose hardware mode (SPI_NSS_Hard ) And software patterns
(SPI_NSS_Soft ), In hardware mode SPI The selection signal is from SPI The hardware automatically generates , And the software model needs us to put
Corresponding GPIO When the port is set high or low, non chip select and chip select signals are generated . In practice, the application of software mode is more .
6. SPI_BaudRatePrescaler
This member sets baud rate frequency division factor , The clock after frequency division is SPI Of SCK Clock frequency of signal line . This member parameter
Can be set to fpclk Of 2、4、6、8、16、32、64、128、256 frequency division .
7. SPI_FirstBit
All serial communication protocols have MSB Go ahead ( The high data is at the top ) still LSB Go ahead ( The low data is in the front ) The problem of , and
STM32 Of SPI Modules can be organized through this structure member , Program control for this feature .
8. SPI_CRCPolynomial
This is a SPI Of CRC Polynomials in validation , If we use CRC When checking , Just use the parameters of this member ( polynomial ),
To calculate CRC Value . After configuring these structure members , We're going to call SPI_Init Function writes these parameters to the register ,
Realization SPI The initialization , And then call SPI_Cmd Enable SPI peripherals .
14.6. SPI— Read write serial FLASH experiment
FLSAH Memory is also called flash memory , It is associated with EEPROM They are all memories that don't lose data after power failure , but FLASH Memory capacity
In general, the quantity is more than EEPROM, Now it has basically taken its place . What we use in our lives U disc 、SD card 、SSD Solid state disk
And us STM32 A device inside a chip that stores programs , All are FLASH Type of memory . In storage control , Most importantly
The difference is FLASH Chips can only be scratched one by one , And in the “I2C chapter ” We learned that EEPROM Can be a single
Byte erasure . This section uses SPI Serial communication FLASH Memory chip read and write experiment for you to explain STM32 Of
SPI Usage method . In the experiments STM32 Of SPI Peripherals are in main mode , Ensure normal communication by querying events .
The first 14 Chapter .SPI Communications
SAIUR201 6 The first 179 page
14.6.1. Hardware design
chart 14-7 SPI Serial FLASH Hardware connection diagram
In this experiment board FLASH chip ( model :W25Q64) It's a use SPI Communication protocol NOR FLASH Memory ,
its CS/CLK/DIO/DO The pins are connected to STM32 Corresponding SPI Pin
NSS/SCK/MOSI/MISO On , among STM32 Of NSS Although the pin is on the chip SPI Hardware pins of peripherals , But actually
The following program just takes it as a normal GPIO, Use software to control NSS The signal , So in SPI The hardware design of
In the middle of the plan ,NSS You can choose the ordinary GPIO, Don't worry about choosing hardware NSS The signal .FLASH There are also WP and
HOLD Pin .WP The pin can control the write protection function , When the pin is low , Write data forbidden . We connect it directly to the power supply ,
Don't use the write protect function .HOLD Pins can be used to pause communication , The pin is at low level , Communication is suspended , The data output pin outputs
High impedance state , Invalid clock and data input pins . We connect it directly to the power supply , Don't use the communication pause function . About FLASH chip
For more information , Please refer to its data manual 《W25Q64》 To get to know . If you use a test board FLASH The model or control pin of is not
equally , Just modify it according to our project , The control principle of the program is the same .
14.6.2. software design
In order to make the project more organized , We read and write FLASH The relevant code is stored separately , Easy to transplant later . stay “ engineering
Templates ” On top of the new “bsp_spi_flash.c” And “bsp_spi_ flash.h” file , These files can also be named according to your preference , They don't belong to
STM32 Content of the standard library , It is written by ourselves according to the application needs .
The first 14 Chapter .SPI Communications
The first 180 page SAIUR2016
14.6.3. Programming points
1. Initialize the target pin and port clock for communication ;
2. Can make SPI Peripheral clock ;
3. To configure SPI The mode of peripherals 、 Address 、 Rate and other parameters and enable SPI peripherals ;
4. Write basic SPI Functions that send and receive by byte ;
5. Write right FLASH Functions for erase and read / write operations ;
6. Write a test program , Check the read and write data .
14.6.4. The code analysis
We put SPI Hardware related configurations are defined in the form of macros to “bsp_spi_ flash.h” In file , See code list 14-2.
Code list 14-2 SPI Hardware configuration related macros
The above code is based on the hardware connection , with FLASH Communication uses SPI Number 、GPIO And so on are encapsulated in macros , And define
I've got control of CS(NSS) Macro of pin output level , So that it can be used when generating start and stop signals . initialization SPI Of GPIO utilize
The macro above , To write SPI Initialization function for , See code list 14-3.
The first 14 Chapter .SPI Communications
SAIUR201 6 The first 181 page
Code list 14-3 SPI Initialization function for (GPIO Initialization part )
With all the uses to GPIO The peripherals are the same , We need to use them first GPIO Pin mode initialization , Configure the reuse function .
GPIO The initialization process is as follows :
1. Use GPIO_InitTypeDef Definition GPIO Initializing structure variables , So that the following can be used for storage GPIO To configure ;
2. Call library function RCC_APB2PeriphClockCmd Enable SPI The pins use GPIO Port clock .
3. towards GPIO Initialize structure assignment , hold SCK/MOSI/MISO The pins are initialized to multiplex push-pull mode . and CS(NSS) lead
The foot is controlled by software , We configure it as a normal push-pull output mode .
4. Use the above to initialize the configuration of the structure , call GPIO_Init Function writes parameters to the register , complete GPIO The initialization .
To configure SPI The pattern of
The above is just a configuration SPI Pins used , Yes SPI Configuration of peripheral mode . In the configuration STM32 Of SPI Before mode , I
The first 14 Chapter .SPI Communications
The first 182 page SAIUR2016
We need to know about the slave terminal first SPI Pattern . according to FLASH Description of the chip , It supports SPI Pattern 0 And mode 3, Support double line
full duplex , Use MSB First mode , The maximum communication clock supported is 104MHz, The data frame length is 8 position . We are going to put STM32
Of SPI The configuration of these parameters in peripherals is consistent . See code list 14-4.
Code list 14-4 To configure SPI Pattern
In this code , hold STM32 Of SPI The peripheral is configured as the host side , Two line full duplex mode , The data frame length is 8 position , Use
SPI Pattern 3(CPOL=1,CPHA=1),NSS The pins are controlled by software and MSB First mode . In the code SPI The clock frequency of
The rate is configured as 4 frequency division , It can actually be configured to 2 Frequency division to improve communication speed , Readers can try it for themselves . The last member
by CRC Calculation formula , Because of our relationship with FLASH Chip communication doesn't need CRC check , It's not enabled SPI Of CRC function ,
At this time CRC The member value of the expression is invalid . After the assignment is finished, the library function is called SPI_Init Write these configurations to registers , And tune
use SPI_Cmd Functions enable peripherals .
Use SPI Send and receive one byte of data
Initialize well SPI After peripherals , You can use SPI Communication , Complex data communication is composed of a single byte of data
Of , Let's look at the code implementation , See code list 14-5.
The first 14 Chapter .SPI Communications
SAIUR201 6 The first 183 page
Code list 14-5 Use SPI Send and receive one byte of data
SPI_FLASH_SendByte The send single byte function contains timeout processing for waiting events , This part of the principle is similar to I2C One of them
sample , No more details here .SPI_FLASH_SendByte The function implements the “SPI Communication process ”:
1. This function does not contain SPI Start and stop signals , It's just the main process of sending and receiving , So start before and after calling this function
And stop signal operation ;
2. Yes SPITimeout Variable assignment to macro SPIT_FLAG_TIMEOUT. This SPITimeout The variables are in the following while Follow
Every cycle in the ring minus 1, The loop calls library functions SPI_I2S_GetFlagStatus Detect events , If an event is detected , be
Into the next phase of communication , If no event is detected, stay here to detect , When testing SPIT_FLAG_TIMEOUT
If you haven't waited for the first time, the communication fails , Called SPI_TIMEOUT_UserCallback Output debugging information , And back
Out of communication ;
3. By testing TXE sign , Get the status of the send buffer , If the transmit buffer is empty , It means the last number that may exist
It's been sent ;
The first 14 Chapter .SPI Communications
The first 184 page SAIUR2016
4. Wait until the send buffer is empty , Call library function SPI_I2S_SendData Send the data to “byte” Write to SPI Of
Data register DR, write in SPI The data in the data register is stored in the transmit buffer ,SPI Peripherals send out ;
5. Wait after writing RXNE event , That is, the receive buffer is not empty . because SPI In 2-wire full duplex mode MOSI And
MISO Data transmission is synchronous ( Please compare “SPI Communication process ” read ), When the receive buffer is not empty , Represents the data above
sent , And the receive buffer also receives new data ;
6. Wait until the receive buffer is not empty , By calling library functions SPI_I2S_ReceiveData Read SPI Data register for DR,
You can get the new data in the receive buffer . Use keywords in your code “return” Take the received data as
SPI_FLASH_SendByte The return value of the function , So we can see what's defined below SPI Receive data function
SPI_FLASH_ReadByte, It simply calls SPI_FLASH_SendByte Function to send data “Dummy_Byte”,
And then get its return value ( Because I don't care about the data sent , So the input parameters at this point “Dummy_Byte” It can be any value ).
The reason why this can be done is SPI The process of receiving and sending is essentially the same , Send and receive simultaneously , The key is that we
In the upper application of , Focus on the data sent or received .
control FLASH Instructions
Get it done SPI After the basic transceiver unit , Also need to know how to FLASH The chip reads and writes .FLASH The chip is customized
A lot of instructions , We control STM32 utilize SPI The bus goes to FLASH The chip sends instructions ,FLASH When the chip is received, it will
Perform the corresponding operation . And these instructions , On the host side (STM32) Come on , It's just that it abides by the most basic SPI Communication protocol sent out by
data , But on the device side (FLASH chip ) Interpret the data into different meanings , That's why it's a directive . See table 14-4.
The first 14 Chapter .SPI Communications
SAIUR201 6 The first 185 page
surface 14-4 FLASH Common chip instruction list
The first column in the table is the instruction name , The second column is instruction encoding , Third to third N The specific content of the column varies according to the instruction
The same meaning . Where the bracketed byte parameter , Direction is FLASH Transfer to host , Command response , Without brackets, the host
towards FLASH transmission . In the table “A0~A23” finger FLASH The address of the memory organization inside the chip ; “M0~M7” It's the manufacturer number
(MANUFACTURER ID);“ID0-ID15” by FLASH Chip ID;“dummy” It can be any data ;“D0~D7”
by FLASH The contents of the internal storage matrix . stay FLSAH Inside the chip , Store a fixed vendor number (M7-M0) And different types of
FLASH The unique number of the chip (ID15-ID0), See table 14-5.
The first 14 Chapter .SPI Communications
The first 186 page SAIUR2016
surface 14-5 FLASH Data book equipment ID explain
By reading in the instruction list ID Instructions “JEDEC ID” You can get these two numbers , The instruction is encoded as “9F h”, among “9F h” yes
finger 16 Hexadecimal number “9F” ( amount to C In language 0x9F). The three bytes immediately following the instruction encoding are FLASH The output of the chip is
“(M7-M0)”、“(ID15-ID8)” And “(ID7-ID0)” . Here we take this instruction as an example , With its instruction sequence diagram to explain , See the picture
14-8.
chart 14-8 FLASH read ID Instructions “JEDEC ID” The temporal
The host first passes through MOSI Line direction FLASH The first byte sent by the chip is “9F h”, When FLASH The chip receives the number
After that , It's interpreted as if the host sent it “JEDEC Instructions ”, Then it responds to the command : adopt MISO The thread takes its
manufacturer ID(M7-M0) And chip type (ID15-0) Send to host , The host can check after receiving the command response . A common application is the main
Through the reading device ID To test if the hardware is connected properly , Or used to identify devices . about FLASH Other instructions on the chip ,
It's all similar , It's just that some instructions contain multiple bytes , Or the response contains more data .
actually , There are certain rules to follow when writing device drivers . First of all, we need to determine what communication protocol is used by the device . Such as
FLASH Model, manufacturer number (M7-M0) FLASH model (ID15-ID0)
W25Q64 EF h 4017 h
W25Q128 EF h 4018 h
The first 14 Chapter .SPI Communications
SAIUR201 6 The first 187 page
The previous chapter, EEPROM It uses I2C, This chapter FLASH It uses SPI. So let's start with the protocol ,
Choose good STM32 The hardware module of , And carry out the corresponding I2C or SPI Module initialization . next , We need to know the phase of the target device
Turn off the order , Because different devices , There will be different instructions . Such as EEPROM The first data is interpreted as internal storage in
The address of the matrix ( The essence is instruction ). and FLASH More instructions are defined , There are write instructions , Read command , read ID Orders, etc .
Last , According to the format requirements of these instructions , Use the communication protocol to send instructions to the device , Achieve the goal of controlling equipment .
Definition FLASH Instruction code table
For ease of use , We put FLASH The common instruction codes of chips are encapsulated in macros , We need to send instruction code later
We can use these macros directly when we use them , See code list 14-6.
Code list 14-6 FLASH Instruction code table
Read FLASH chip ID
according to “JEDEC” The timing of instructions , We read FLASH ID The process of writing into a function , See code list 14-7.
Code list 14-7 Read FLASH chip ID
The first 14 Chapter .SPI Communications
The first 188 page SAIUR2016
This code uses control CS Macro of pin level “SPI_FLASH_CS_LOW/HIGH” As well as the previous preparation of the single byte transceiver
Count SPI_FLASH_SendByte, It's very clear that “JEDEC ID” The timing of instructions : Send a byte of instruction encoding
“W25X_JedecDeviceID”, Then read 3 Bytes , obtain FLASH The chip's response to the instruction , Finally, read this
3 Merge data into one variable Temp in , And then return the value as a function , Compare the return value with the macro we defined “sFLASH_ID”
contrast , You know FLASH Is the chip working properly .
FLASH Write enable and read current state
In the FLASH Before the chip memory matrix writes data , First, enable write operations , adopt “Write Enable” Command can write enable ,
See code list 14-8.
Code list 14-8 Write enabling commands
EEPROM equally , because FLASH It takes a certain amount of time for the chip to write data to the internal memory matrix , It's not on the bus
At the end of the communication , So you need to confirm after the write operation FLASH chip “ Free ” Can be written again . in order to
Show your working state ,FLASH The chip defines a status register , See the picture 14-9.
The first 14 Chapter .SPI Communications
SAIUR201 6 The first 189 page
chart 14-9 FLASH The status register of the chip
We only focus on the second part of the status register 0 position “BUSY”, When this bit is “1” when , indicate FLASH The chip is busy
state , It may be working on the internal storage matrix “ erase ” or “ Data writing ” The operation of . Use... In the instruction list “Read Status
Register” Instructions can be obtained FLASH The contents of the chip status register , The time sequence is shown in the figure 14-10.
chart 14-10 Read the timing of the status register
Just ask FLASH The chip sends an instruction to read the status register ,FLASH The chip will continue to return the latest status to the host
Register contents , Until receipt SPI Stop signal for communication . Based on this, we write a program with waiting function FLASH Chip write end function
function , See code list 14-9.
Code list 14-9 Wait by reading the status register FLASH The chip is idle
The first 14 Chapter .SPI Communications
The first 190 page SAIUR2016
This code sends the instruction code to read the status register “W25X_ReadStatusReg” after , stay while Keep getting the register in the loop
The content of the device and verify its “WIP_Flag sign ”( namely BUSY position ), Wait until this flag indicates the end of writing before exiting this letter
Count , In order to continue with FLASH The data communication of the chip .
FLASH Sector erase
because FLASH The characteristics of memory decide that it can only change the original memory into “1” The data bits of are rewritten to “0”, And it turned out to be “0” Data bits of
It can't be rewritten as “1”. So here's the data “ erase ” The concept of , Before writing , The target memory matrix must be erased
operation , Erase the data bits in the matrix to “1”, When data is written , If you want to store data “1”, Then don't modify the storage matrix ,
To store data “0” when , To change the bit . Usually , The basic operation unit of erasing the memory matrix is multiple bytes , As in this case
In the son FLASH Chip support “ Sector erase ”、“ Block erase ” as well as “ Erase the whole piece ”, See table 14-6.
surface 14-6 This experiment FLASH The erasure unit of the chip
FLASH The minimum erasing unit of a chip is sector (Sector), And a block (Block) contain 16 Sectors , Its internal storage matrix is divided into
See the picture 14-11..
The first 14 Chapter .SPI Communications
SAIUR201 6 The first 191 page
chart 14-11 FLASH The memory matrix of the chip
Use the sector erase instruction “Sector Erase” Controllable FLASH The chip starts erasing , The instruction sequence is shown in the figure 14-14.
chart 14-12 Sector erase timing
The first byte of the sector erase instruction encodes the instruction , And then it was sent 3 Bytes are used to represent the memory matrix address to be erased . want
Note that before the sector erase instruction , You need to send “ Write enable ” Instructions , After the sector erase instruction is sent , By reading registers
State wait for sector erase operation to finish , The code implementation is shown in the code list 14-10.
The first 14 Chapter .SPI Communications
The first 192 page SAIUR2016
Code list 25-10 Erase sectors
The functions called by this code have been explained before , As long as you pay attention to the high bit before sending the erasure address . Call sector erase instruction
Note that the input address should be aligned to 4KB.
FLASH Page write
After the target sector is erased , You can write data to it . And EEPROM similar ,FLASH The chip also has a page write life
Make , Use the page write command to write to at most once FLASH transmission 256 Bytes of data , Let's take this unit as page size .
FLASH The timing of page writing is shown in the figure 14-13.
chart 14-13 FLASH Chip page write
The first 14 Chapter .SPI Communications
SAIUR201 6 The first 193 page
We can see from the sequence diagram that , The first 1 Bytes to “ Page write instruction ” code ,2-4 The byte is to be written “ Address A”, The next thing is to write
What's in it , You can send up to 256 Bytes of data , The data will come from “ Address A” Start , Write to in order FLASH Of
Storage matrix . If the data sent exceeds 256 individual , The data previously sent will be overwritten . Unlike erase instructions , Page write instruction
The address is not required to be 256 Byte alignment , Just confirm that the target storage unit is in erase state ( That is, it has not been written after being erased ).
therefore , If yes “ Address x” After executing the page write instruction , Sent 200 Terminate communication after a byte of data , The next page write refers to
Make , from “ Address (x+200)” Start writing 200 There's no problem with one byte ( Less than 256 All possible ). Only in practical application, because of
The basic erasing unit is 4KB, Generally read and write in sectors , Want to know more about , We can learn from our “FLASH file system ”
Related examples . Encapsulating page write timing as a function , The implementation is shown in the code listing 14-11.
Code list 14-11 FLASH Page write
The first 14 Chapter .SPI Communications
The first 194 page SAIUR2016
The content of this code is : Send... First “ Write enable ” command , Then start page write timing , Then send the instruction code 、 Address ,
And then send out the data to be written one by one , End the communication after sending , Check FLASH Status register , wait for FLASH
End of internal write . When we write non quantitative data to applications, we often write non quantitative data , Call directly “ Page write ” Function Union
It's not particularly convenient , So we wrote... On the basis of it “ Indefinite data writing ” Function of , See the code listing for the base implementation 14-12.
Code list 14-12 Indefinite data writing
The first 14 Chapter .SPI Communications
SAIUR201 6 The first 195 page
This code is associated with EEPROM In chapter “ Write multibytes fast ” The principle of function is the same , The operation process will not be repeated here .
The difference is the size of the page and when the actual data is written , It's for FLASH The chip's page write function , And in the actual call
This “ Indefinite data writing ” Function time , Also note that the target sector is in the erase state .
from FLASH Reading data
Relative to writing ,FLASH It's much easier to read data from a chip , Use the read command “Read Data” that will do , The instruction sequence is shown in
chart 14-14.
The first 14 Chapter .SPI Communications
The first 196 page SAIUR2016
chart 14-14 SPI FLASH Read data sequence
After sending the instruction code and the starting address to read ,FLASH The chip will return the contents of the memory matrix by increasing the address ,
There is no limit to the amount of data read , As long as communication doesn't stop ,FLASH The chip will always return data . The code implementation is shown in the code list
14-13.
Code list 14-13 from FLASH Reading data
Since there is no limit to the amount of data read , So after sending the read command, I always receive NumByteToRead Data to the end .
The first 14 Chapter .SPI Communications
SAIUR201 6 The first 197 page
main function
Finally, let's write main function , Conduct FLASH Chip read and write verification , See code list 14-14.
Code list 14-14 main function
The first 14 Chapter .SPI Communications
The first 198 page SAIUR2016
Function initializes LED、 A serial port 、SPI peripherals , Then read FLASH Chip ID check , if ID Check pass
If you pass, you will go to FLASH Write test data to a specific address of , And then read data from that address , Test whether reading and writing are normal .
Be careful : Because of the FLASH By default, the chip has stored data for a specific purpose , If you erase these data, it will affect
To the operation of some programs . So we reserved FLASH Chip “ The first 0 A sector (0-4096 Address )” It is specially used in this experiment , If not
necessary , Do not erase the contents of other addresses . If erased , It can be found in the supporting materials “ Brush the outside FLASH Content ” Program , According to its
Explain to FLASH Re write factory contents .
14.6.5. Download validation
use USB Line connection development board “USB TO UART” Interface and computer , Open the serial port debugging assistant at the computer end , Put the compiled program
Download to the development board . In the serial port debugging assistant, you can see FLASH Debugging information of the test .
14.7. Practice after class
1. stay SPI Peripheral initialization part ,MISO Can the pin be set to input mode ? Why? ? What is the actual test phenomenon ?
2. Try to use FLASH Chip storage int Integer variables ,float Floating point variable of type , Write programs to write data , And read out the verification .
3. If a sector is written without erasing , What are the consequences ? Please do experiments to verify .
4. sketch FLASH Memory and EEPROM The difference between memory .
The first 15 Chapter . Gyroscope attitude detection
SAIUR201 6 The first 199 page
The first 15 Chapter . Gyroscope attitude detection
15.1. Preview before class
Find the answer in the book .
1. MPU6050 What is the function of the module ?
15.2. summary
What's in this chapter :
(1)MPU6050 Module introduction
(2) Use MPU6050 Module for attitude detection
15.3. Attitude detection
15.3.1. Basic knowledge
In the aircraft , Flight attitude is a very important parameter , See the picture 50-1, Set up a coordinate system with the center of the plane itself , When the plane goes around
When the axis rotates , It will affect the yaw angle respectively 、 Roll angle and pitch angle .
The first 15 Chapter . Gyroscope attitude detection
The first 200 page SAIUR2016
chart 15-1 Represents the yaw angle of the aircraft attitude 、 Roll angle and pitch angle
If we know that the aircraft was initially in the upper left corner , Just find a way to measure the change of three attitude angles based on the original state
The amount , And then stack it , You can get its real-time attitude .
15.3.2. Coordinate system
In the abstract , The gesture is “ Carrier coordinate system ” And “ Geographic coordinate system ” The transformational relationship between .
chart 15-2 The earth coordinate system 、 Geographic coordinate system and carrier coordinate system
Let's start with three common coordinate systems :
1. The earth coordinate system : Take the center of the earth as the origin ,Z The axis is along the axis of the earth's rotation ,X、Y The coordinate system of the axis in the equatorial plane .
2. Geographic coordinate system : Its origin is on the surface of the earth ( Or the point where the carrier is located ),Z The axis is perpendicular to the local geography ( Acceleration of gravity
The first 15 Chapter . Gyroscope attitude detection
SAIUR201 6 The first 201 page
Direction ),XY The axis is tangent to the local longitude and latitude . Depending on the direction of each axis , Optional “ Northeast sky ”、“ Southeast sky ”、
“ Northwest sky ” Equicoordinate system . This is the coordinate system we use in our daily life , The direction of southeast, northwest and east of this coordinate system
The concept of South and northwest is the same .
3. Carrier coordinate system : The carrier coordinate system takes the center of mass of the carrier as the origin , Generally, the coordinate system is constructed according to the structural direction of the carrier itself , Such as Z
The axis points from the origin to the top of the carrier ,Y The axis points to the head of the carrier ,X The axis is along both sides of the carrier . It says that the plane based ride
A coordinate system is a carrier coordinate system , It's analogous to cars 、 Warship 、 human body 、 Animals or cell phones and all kinds of things .
Both geographic coordinate system and carrier coordinate system take carrier as origin , So they can be transformed by simple rotation , The attitude of the carrier
The angle is determined according to the angle between the carrier coordinate system and the geographical coordinate system . Matching diagram 50-1, Use your spatial imagination , Let's assume that the initial
In state , Of the plane Z Axis 、X Axis and Y The axis is the sky axis of the geographic coordinate system 、 The north axis 、 The East axis is parallel . For example, when an airplane circles itself
“Z” Shaft rotation , It will make itself “Y” The axis direction is related to the geographical coordinate system “ north and south ” The direction deviates from a certain angle , This angle is called yaw angle
(Yaw); When the carrier goes around its own “X” Shaft rotation , It will make itself “Z” The axis direction is related to the geographical coordinate system “ Heaven and earth ” The direction deviates from a certain angle ,
This angle is called the pitch angle (Pitch); When the carrier goes around its own “Y” Shaft rotation , It will make itself “X” The axis direction is related to the geographical coordinate system “ thing ”
The direction deviates from a certain angle , This angle is called roll angle .
surface 50-1 The relationship between attitude angles
These angles are also called Euler angles , It's a very intuitive angle used to describe posture .
15.4. Using gyroscopes to detect angles
The most intuitive angle detector is the gyroscope , See the picture 50-3, It can detect the rotation of objects around the coordinate axis “ angular velocity ”, Like
Integrating speed with time can get the same distance , By integrating the angular velocity with time, we can calculate the rotation “ angle ”.
chart 15-3 Schematic diagram of gyroscope detection
The first 15 Chapter . Gyroscope attitude detection
The first 202 page SAIUR2016
Defects detected by gyroscope
Because the gyroscope measures the angle using integral , There will be integral errors , See the picture 50-4, If integral time Dt The smaller it is , The more the error is
Small . It's very easy to understand , For example, when calculating the distance , Suppose the travel time is 1 Hours , We randomly choose a moment in the process of driving
Speed Vt multiply 1 Hours , The distance error is very large , Because in the process of driving, not every moment is equal to the speed at that moment
Degree , If we each 5 The speed is measured every minute , available Vt1、Vt2、Vt3-Vt12 this 12 The speed of a moment , To each
The speed of the moment multiplied by the time interval (5 minute ), And 12 The sum of two results , Then we can get a relatively accurate driving distance ,
Continuously increase the sampling frequency , You can make the integral time Dt smaller , Reduce the error .
chart 15-4 Integral error
similarly , Increase the sampling frequency of gyroscope sensor , It can reduce the integral error , At present, the development of very common gyroscope sensor
The sample frequency can reach 8KHz, It can meet the accuracy requirements of most applications . What is more difficult to solve is the problem caused by the error of the device itself .
for example , What is the error of some gyroscope 0.1 degree / second , When the gyroscope is stationary , The ideal angular velocity should be 0, No matter how long it's still ,
The angle of rotation measured by integrating it is 0, This is the ideal state ; And because there is 0.1 degree / Second error , When the gyroscope
When stationary , It's always sampling angular velocity 0.1 degree / second , If it's still 1 minute , The angle of rotation measured by integrating it
Degree is 6 degree , If it's still 1 Hours , The angle of rotation measured by integrating the gyroscope is 360 degree , That is to say, we have turned a whole circle , this
It becomes unbearable . Only when the positive and negative errors just cancel each other out , To eliminate this cumulative error .
15.5. Use the accelerometer to detect the angle
Because the angle is directly measured by gyroscope, the accumulated error will be produced in long time measurement , So we introduce the sensor to detect the inclination angle
device .
chart 15-5 T Font level
The first 15 Chapter . Gyroscope attitude detection
SAIUR201 6 The first 203 page
The most common example of measuring inclination is the level used in buildings , Under the influence of gravity , The bubbles in the level can roughly reflect the water column
The angle between the line and the direction of gravity , Use pictures 15-5 Medium T Font level , You can detect the graph 15-1 The horizontal
Roll angle and pitch angle , But the yaw angle cannot be detected in this way . In electronic equipment , Acceleration sensors are generally used to detect
dip angle , It samples the stress data by detecting the deformation of the device in all directions , according to F=ma transformation , The sensor directly sends
We'll get the acceleration data , So it's called acceleration sensor . Because of the earth's gravitational field , So gravity acts on transmission at any time
Sensilla , When the sensor is stationary ( In fact, the acceleration is 0), The sensor detects acceleration in that direction g, You can't think of gravity as
The acceleration measured in the direction is g, It means that the acceleration of the sensor in this direction is g The movement of . When the attitude of the sensor is different , It's in
The acceleration of gravity detected by each axis is different , Using measurements in all directions , According to the principle of force decomposition , Ask for
Figure out the angle between each axis and gravity , See the picture 15-6.
chart 15-6 Gravity detection
Because the direction of gravity is related to the geographical coordinate system “ Heaven and earth ” The shaft is fixed , So by measuring the distance between each axis of the carrier coordinate system and the direction of gravity
The angle rotation relationship between it and geographical coordinate system can be obtained , So as to know the attitude of the carrier . The defect of acceleration sensor detection is due to this
Tilt angle detection is based on gravity , It can't detect the yaw angle (Yaw), Principle follows T It's the same as a level , Whatever
He designed the level , Bubbles can't even indicate this angle . Another drawback is that acceleration sensors don't distinguish between gravitational acceleration and external acceleration
Force acceleration , When objects move , It also detects acceleration in the direction of motion , Especially in the state of vibration , The number of sensors
There's going to be very big data changes , It is difficult to reflect the actual value of gravity at this time .
15.6. Use the magnetic field to detect the angle
In order to make up for the acceleration sensor can not detect yaw angle (Yaw) The problem of , Let's introduce a magnetic field sensor , It can detect
The size of the magnetic field in all directions , By detecting the earth's magnetic field , It can realize the function of compass , So it's also called the electronic compass . because
The relationship between geomagnetic field and geographical coordinate system “ north and south ” The shaft is fixed , Using the compass function of the magnetic field detection sensor , You can measure the yaw angle (Yaw)
了 . The defect of the magnetic field detector is the same as that of the compass , Using a magnetic field sensor can be disturbed by an external magnetic field , Such as the electricity of the carrier itself
The first 15 Chapter . Gyroscope attitude detection
The first 204 page SAIUR2016
Magnetic interference , Magnetite interference of different geographical environment and so on .
15.7. utilize GPS Detection angle
Use GPS It can directly detect the coordinates of the carrier on the earth , If the coordinates of the carrier measured at a certain time are A, At another moment
Coordinate for B, Using two coordinates, we can find its course , That is, the yaw angle can be determined , And not affected by the magnetic field , But this kind of testing method
The formula is only valid when the carrier has a large range of displacement (GPS The civil accuracy is about 10 Meters ).
15.8. Attitude fusion and quaternion
You can find , When using gyroscope to detect angle , There are defects at rest , And influenced by time , And the accelerometer detects
Angle , Defects in motion , And not affected by time , It's just complementary . If we use both sensors at the same time , And set up
Consider a filtering algorithm , When an object is at rest , Increase the weight of acceleration data , When an object is in motion , Increase the gyroscope
Weight of data , So as to obtain more accurate attitude data . Empathy , Check the yaw angle , When the carrier is at rest , Can increase the magnetic field detection
The weight of the data , When the carrier is in motion , Increase the gyroscope and GPS Weight of test data . These use a variety of sensor data
The processing algorithm to detect attitude is called attitude fusion . It is often used in attitude fusion “ Four yuan number ” To show posture , It consists of
Three real numbers and one imaginary number , So it's called quaternion . It's not intuitive to use quaternions to represent posture , But because of the Euler angle ( namely
The yaw angle mentioned above 、 Roll angle and pitch angle ) When it comes to gesture, there will be “ Universal joint deadlocks ” problem , And the operation is complicated , therefore
Generally, quaternions are used in data processing , After processing, the quaternion is converted to Euler angle . Here we just need to know four yuan
Number is another way to express posture , If you are interested, please refer to the relevant information .
15.9.MPU6050 Module introduction
15.9.1. MPU6050 Module function and appearance
Next, we use the sensor example to explain how to detect the attitude of an object . There are leads on our development board I2C Bus interface ,
Convenient for extended use I2C Sensor module for protocol communication , In this section we'll expand on the board MPU6050 Gyroscope module ,
See the picture 50-9. It's a six axis sensor module , use InvenSense The company's MPU6050 As the main chip , It can detect three at the same time
Axial acceleration 、 Three axis gyroscope ( Three axis angular velocity ) The motion data and the temperature data . utilize MPU6050 Internal to the chip DMP modular
(Digital Motion Processor Digital motion processor ), The sensor data can be filtered 、 Fusion processing , It goes directly through I2C
The interface outputs the attitude data after attitude calculation to the master controller , Reduce the computation of the main controller . The frequency of attitude calculation is up to 200Hz,
It is very suitable for the field of high real-time attitude control requirements . It's commonly used in mobile phones 、 Smart Bracelet 、 Four axis aircraft and pedometer, etc
Attitude detection .
The first 15 Chapter . Gyroscope attitude detection
SAIUR201 6 The first 205 page
chart 15-9 MPU6050 Module appearance
15.9.2. MPU6050 Module pin function description
This module leads to 8 The function of each pin is shown in the table 15-3.
Among them SDA/SCL、XDA/XCL The communication pins are divided into two groups I2C The signal line . When the module communicates with an external host , Use
SDA/SCL, Such as and STM32 Chip communication ; and XDA/XCL For MPU6050 Chips and others I2C When the sensor communicates, make
use , For example, use it to connect to a magnetic field sensor ,MPU6050 The module can take the slave from the host SDA/SCL The data or command received by
XDA/XCL Pin forward to magnetic field sensor . But in fact, this function is rather weak , Control is cumbersome and inefficient , It's usually done directly
Magnetic sensors and things like that I2C The sensor is directly connected to MPU6050 Mounted on the same bus ( That is, they are all connected to SDA/SCL), send
It's directly controlled by the mainframe .
15.9.3. MPU6050 Hardware schematic diagram of the module
MPU6050 The hardware schematic diagram of the module is shown in the figure 15-10.
chart 15-10 MPU6050 Module schematic diagram
Its hardware is very simple ,SDA And SCL Be drawn out of convenience with the outside I2C Host connection , Look at the top right corner of the picture , We can see that the module
The first 15 Chapter . Gyroscope attitude detection
The first 206 page SAIUR2016
The block I2C Communication pins SDA And SCL The pull-up resistor has been connected , So it's connected to the outside I2C The communication host is directly used for communication
Just connect the wires ; and MPU6050 The module communicates with other sensors XDA、XCL The pin is not connected with pull-up resistor ,
Attention should be paid when using . The module itself I2C The device address can be accessed through AD0 Level control of pins , When AD0 When grounded , equipment
The address is 0x68( Seven addresses ), When AD0 When connected to the power supply , The device address is 0x69( Seven addresses ). in addition , When the sensor has new data
When will it pass INT Pin notification STM32. because MPU6050 The detection is based on its own central coordinate system , See the picture 50-11,
The coordinate system and rotation symbol it represents indicate MPU6050 Sensors XYZ The acceleration of the axis has a positive direction of angular velocity . So in
When installing the module , You need to consider the relationship between it and the coordinate system of your device .
chart 15-11 MPU6050 The coordinates and direction of the sensor
15.10. MPU6050 The characteristic parameters of the module
MPU6050 The parameters of sensor module are shown in table 15-4.
surface 15-4 MPU6050 The characteristic parameters of
The first 15 Chapter . Gyroscope attitude detection
SAIUR201 6 The first 207 page
The table shows , Acceleration and gyro sensor's ADC Are all 16 position , Their range and resolution can be selected in many modes , see
chart 15-13, The larger the range is , Lower resolution .
chart 50-12 The relationship between acceleration configuration and range
chart 15-13 Several range configurations of gyroscope
It can also be seen from the table that the acceleration of the sensor and the sampling frequency of the gyroscope are respectively 1000Hz And 8000Hz, They mean acceleration
Sampling frequency of degree and angular velocity data , We can use STM32 The controller reads these data and then performs attitude fusion
count , To get the current attitude of the sensor ( That is to find the yaw angle 、 Roll angle 、 Pitch angle ). And if we use the inside of the sensor DMP single
We need to solve the problem , It can directly calculate the attitude of the acceleration and angular velocity , The result of the solution is then output to the
STM32 controller , namely STM32 No need to calculate , Yaw angle can be obtained directly 、 Roll angle and pitch angle , The DMP You can lose per second
Out 200 Secondary attitude data .
15.11. MPU6050— Get raw data, experiment
In this section we learn how to use STM32 control MPU6050 The sensor reads the acceleration 、 Angular velocity and temperature data . stay
When controlling sensors , Using the STM32 Of I2C drive , It's like control STM32 equally , Yes MPU6050 The sensor doesn't work
Writing different contents in the same register can realize different control modes , The measurement data can be obtained by reading from a specific register , This part
About MPU6050 We will not expand the contents of specific registers , Please refer to 《MPU-60X0 register 》 The manual was informed that .
15.11.1. Hardware design
Before the experiment , Let's start with DuPont wire STM32 Development board and the MPU6050 The modules are connected , See the picture 15-14 And table
15-5.
The first 15 Chapter . Gyroscope attitude detection
The first 208 page SAIUR2016
chart 15-14 STM32 And MPU6050 The hardware connection of
surface 15-5 MPU6050 Module pin description
15.11.2. Brief introduction of supporting procedures
This chapter MPU6050 There are four routines in the module , Users can choose the appropriate program to learn according to their needs , Each routine
The basic functions of are shown in table 15-6.
surface 15-6 MPU6050 Introduction to the basic functions of module matching program
The first 15 Chapter . Gyroscope attitude detection
SAIUR201 6 The first 209 page
among , routine 1 and 2 Similar function of , It's all about simply getting data , But because of the hardware I2C LCD screen is not supported at the same time ,
So the back 2、3、4 Routines use software by default I2C To drive MPU6050, The underlying software I2C Drive with EEPROM The base
The book agrees with the book , This chapter focuses on the upper MPU6050 Application and interface .
15.11.3. software design
This section is about “ Hardware STM32-MPU6050” experiment , Please open the supporting code project to read and understand . For the convenience of display
And transplantation , We put STM32 Of I2C Driver related code is written to “bsp_i2c.c” And “bsp_i2c.h” In file , And
MPU6050 The code related to the sensor is written to “mpu6050.c” And “mpu6050.h” In file , These documents were written by ourselves ,
Content that does not belong to the standard library , Name the file as you like .
15.11.4. Key points of programming
1. initialization STM32 Of I2C;
2. Use I2C towards MPU6050 Write control parameters ;
3. Time reading acceleration 、 Angular velocity and temperature data .
15.11.5. The code analysis
In this experiment I2C Driving and MPU6050 The main reason for driving separation is to consider the generality of extending other sensors , If you use magnetism
Field sensors 、 You can use the same pressure sensor I2C drive , This driver only gives simultaneous interpreting for different sensors
Just write the interface . This chapter explains I2C Driver is mainly for interface encapsulation , No more details . In this experiment I2C Hardware definition
See code list 15-1.
Code list 15-1 I2C The hardware definition of (bsp_i2c.h file )
These macros are based on the I2C The hardware is packaged . initialization I2C Next, use these macros to I2C Do the initial
turn , The initialization process is similar to I2C Reading and writing EEPROM It's the same in the world , See code list 15-2.
The first 15 Chapter . Gyroscope attitude detection
The first 210 page SAIUR2016
Code list 15-2 initialization I2C(bsp_i2c.c file )
After the encapsulation and initialization of the read-write function is completed, the program is written I2C Read and write functions , This part is related to EERPOM The same as , Mainly
call STM32 Standard library functions read and write data registers and flag bits , This part of the experiment is edited
Write in ST_Sensors_I2C_WriteRegister And ST_Sensors_I2C_ReadRegister It's in , On top of them , And then it's packaged as
了 Sensors_I2C_WriteRegister And Sensors_I2C_ReadRegister, See code list 15-3.
The first 15 Chapter . Gyroscope attitude detection
SAIUR201 6 The first 211 page
Code list 15-3 Encapsulation of read write function (i2c.c file )
The first 15 Chapter . Gyroscope attitude detection
The first 212 page SAIUR2016
The encapsulated function mainly adds error retrial mechanism , If there is an error in reading and writing , You'll try many times , Many attempts failed
The error code will be returned . This function is used as I2C Driving external interfaces , Other uses I2C The sensor called this function to
Read and write registers .
MPU6050 Register definition of
MPU6050 There are various registers used to control the operating mode , We put the addresses of these registers 、 Register bits are determined by macro
It's time mpu6050.h It's in the document , See code list 15-4.
Code list 15-4MPU6050 Register definition of (mpu6050.h)
initialization MPU6050
according to MPU6050 Register function definition of , We use I2C Write specific control parameters to the register , See code list
15-5.
Code list 15-5 initialization MPU6050(mpu6050.c)
The first 15 Chapter . Gyroscope attitude detection
SAIUR201 6 The first 213 page
This code starts with MPU6050_ReadData And MPU6050_WriteRed Function encapsulates I2C The underlying read / write driver of
dynamic , Next, use them in MPU6050_Init Function is directed to MPU6050 Register write control parameters , Set up MPU6050 Of
Sampling rate 、 range ( The resolution of the ). Read the sensor ID After the initialization , By reading its “WHO AM I” Register content to detect hardware
If there is something wrong , This register stores ID Number 0x68, See code list 15-6.
Code list 15-6 Reading sensor ID(mpu6050.c)
Read raw data
If the sensor detects normal , You can read its data register to get the sampling data , See code list 15-7.
Code list 15-7 Read sensor data (mpu6050.c)
The first 15 Chapter . Gyroscope attitude detection
The first 214 page SAIUR2016
The first three functions are used to read the three-axis acceleration respectively 、 Angular velocity and temperature values , These are all primitive ADC The number (16
Bit length ), For acceleration and angular velocity , Read what you get ADC Value divided by resolution , Then we can get the actual physical quantity . the last one
function MPU6050_ReturnTemp It shows the temperature ADC The conversion between the temperature value and the actual temperature value , It is based on MPU6050 Say
The conversion formula given in this paper is used for conversion , Note that the temperature detected by the gyroscope is affected by the heating of its own chip , Strictly speaking, it measures
It's the temperature of the chip itself , So it's not very accurate to use it to measure the temperature . We don't convert acceleration and angular velocity values ,
In the next section, we'll use this data directly to DMP unit , Find out the attitude angle .
The first 15 Chapter . Gyroscope attitude detection
SAIUR201 6 The first 215 page
main function
Finally, let's look at main function , See code list 15-8.
Code list 15-8 main function
In this experiment, we control MPU6050 No interrupt detection is used , We are using Systick The timer does the timing , Every once in a while
Read between MPU6050 The data register of the , The code uses Task_Delay Variable to control the timing time , stay
Systick There will be every 1ms Subtract... From the value of the variable 1, So when its value is 0 Time is up .
stay main In the function , call I2C_Bus_Init、MPU6050_Init And MPU6050ReadID After the function , It's just whlie Follow
The timing time is determined in the ring , Read the acceleration when the timing time is up 、 Angular velocity and temperature values , And use the serial port to print information to the computer .
15.11.6. Download validation
Use DuPont cable to connect development board and module , use USB Line connection development board “USB TO UART” Interface and computer , On the computer side
The first 15 Chapter . Gyroscope attitude detection
The first 216 page SAIUR2016
Open the serial debugging assistant , Download the compiled program to the development board . In the serial port debugging assistant, you can see MPU6050 Debugging from sampling
Information .
15.12. MPU6050— utilize DMP Carry out attitude calculation
In the last section we just used MPU6050 Collected raw data , If you have deep research on the algorithm of attitude calculation , You can do it yourself
Line write attitude algorithm , And use that data , Use STM32 Carry out attitude calculation , After the calculation, the attitude angle is output . And because the
MPU6050 Internal integration DMP, Unwanted STM32 Participate in the solution , It can output attitude angle directly , There is no need to modify the algorithm
Further study of , Very convenient , This chapter explains how to use DMP Do the calculation . The main body of the code used in the experiment is from MPU6050 Officer,
The driver provided by the party 《motion_driver_6.12》 Transplanted , The package provides information based on STM32F4 Controller source code
( This project is using this code to transplant to STM32F1 Upper ) And use python Language of the host computer , There's also attached
documentation , Please make full use of the official materials .
15.12.1. Hardware design
The hardware design is exactly the same as the experiment in the previous section , And the software uses INT The interrupt signal generated by the pin , In this section
The code uses software by default I2C.
15.12.2. software design
This section is about “MPU6050_python Upper computer ” experiment , Please open the supporting code project to read and understand . This project is from
The official code was transplanted (IAR The project was transplanted to MDK), Not many changes , We mainly explain the design idea of the driver to the readers
road , Easy to use . Because the code of this project is very large , When we talk about some functions , Please make good use of it MDK Search function of , thus
Find the corresponding code in the project .
15.12.3. Key points of programming
1. Provide I2C Read write interface 、 Time service and INT Interrupt handling ;
2. Get the raw data from the gyroscope and process it ;
3. Update data and output .
15.12.4. The code analysis
The main driving force of the government is MPL Software library (Motion Processing Library), To migrate the library, we need to provide
I2C Read write interface 、 Time service and MPU6050 Data update flag for . If you need to output debugging information to the upper computer , I still need to mention
For serial interface .
The first 15 Chapter . Gyroscope attitude detection
SAIUR201 6 The first 217 page
I2C Read write interface
MPL The inside of the library is right I2C Read and write with i2c_write And i2c_read function , In the file “inv_mpu.c” It's given in
Your interface format , See code list 15-1.
Code list 15-9 I2C Read write interface (inv_mpu.c file )
The format of these interfaces is similar to what we wrote in the previous section I2C Read and write functions Sensors_I2C_ReadRegister And
Sensors_I2C_WriteRegister Agreement , So you can use macro to replace . Provide time service MPL Delay is used in the software library
And time stamp function , Demand needs to be provided delay_ms Function to achieve millisecond delay , Provide get_ms Get millisecond timestamps ,
Their interface formats are also “inv_mpu.c” The document gives , See code list 15-2.
Code list 15-10 Timing service interface (inv_mpu.c file )
What we provide for the interface Delay_ms And get_tick_count Function defined in bsp_SysTick.c file , We use
SysTick An interrupt is generated every millisecond , time , See code list 15-11.
The first 15 Chapter . Gyroscope attitude detection
The first 218 page SAIUR2016
Code list 15-11 Use Systick Timing (bsp_SysTick.c)
In the above code TimingDelay_Decrement and TimeStamp_Increment The function is in Systick Service interruption letter for
Called in the number , See code list 50-12.systick Configured to generate an interrupt every millisecond , And every interrupt will be right
TimingDelay Variable minus 1, Yes g_ul_ms_ticks Variable plus 1. They are respectively used for Delay_ms Functions use TimingDelay
Block delay with the value of , and get_tick_count The timestamp obtained by the g_ul_ms_ticks Value .
The first 15 Chapter . Gyroscope attitude detection
SAIUR201 6 The first 219 page
Code list 15-12 Systick The interrupt service function of (stm32f10x_it.c file )
Provide serial port debugging interface
MPL The debugging information output functions of the code base are all concentrated in log_stm32.c In file , We can provide serial ports for these functions
Output interface , In order to output the information to the upper computer , See code list 15-3.
Code list 15-13 Serial debugging interface (log_stm32.c file )
The first 15 Chapter . Gyroscope attitude detection
The first 220 page SAIUR2016
In the above code fputcc Function is our own serial output interface , It's with us printf Function definition
fputc Functions are very similar . Below eMPL_send_quat The function is MPL The original function in the library , It's for printing “ Quaternion letter
Rest ”, In this log_stm32.c There are also output log information in the file _MLPrintLog function , Output the original information to the special upper computer
Of eMPL_send_data function , They all call fputcc For the output .MPU6050 The interrupt interface of
Different from the basic experiment in the previous section , In order to process sampling data efficiently ,MPL Code base used MPU6050 Of INT in
Break the signal , For this reason, we need to provide interrupt interface for , See code list 15-4.
Code list 15-14 Interrupt interface (stm32f10x_it.c file )
In the project, we put MPU6050 And STM32 The connected pins are configured in interrupt mode , The above code is the interrupt of this pin
Service functions , Called in interrupt MPL Code base gyro_data_ready_cb function , It sets the flag variable
hal.new_gyro, To inform MPL The library has new data , Its function definition is shown in the code list 15-15.
Code list 15-15 Set the flag variable (main.c file )
main Function execution flow
understand MPL After porting the interfaces that need to be provided , Let's see main Function to learn how to use MPL Library to get attitude data ,
See code list 15-5.
The first 15 Chapter . Gyroscope attitude detection
SAIUR201 6 The first 221 page
Code list 15-16 Use MPL The process of attitude calculation
The first 15 Chapter . Gyroscope attitude detection
The first 222 page SAIUR2016
The first 15 Chapter . Gyroscope attitude detection
SAIUR201 6 The first 223 page
The first 15 Chapter . Gyroscope attitude detection
The first 224 page SAIUR2016
As you can see ,main The function is very long , And we just excerpted some , There's a lot of code in the original project code , And No
Conditional branch in the same mode , For example, add magnetic field data to use 9 The function of solving axis data ( This is a MPU9150 The function of ,
MPU6050 I won't support it ) And other control examples related to working mode . Above main The main execution process of the function is summarized as follows :
1. initialization STM32 The hardware , Such as Systick、LED、 Debug serial port 、INT Interrupt pin and I2C Initialization of peripherals ;
2. call MPL Library function mpu_init Initialize the basic working mode of the sensor ( Most of the following procedure calls are MPL library
function , No longer stressed );
3. call inv_init_mpl Function initialization MPL Software library , After initialization, the solution can be performed normally ;
4. Set various operation parameters , Such as quaternion operation (inv_enable_quaternion) 、6 Axis or 9 Axis data fusion
(inv_enable_9x_sensor_fusion) wait ;
5. Set the working mode of the sensor (mpu_set_sensors) 、 Sampling rate (mpu_set_sample_rate) 、 The resolution of the
(inv_set_gyro_orientation_and_scale) wait ;
6. When STM32 drive 、MPL library 、 Sensor working mode 、DMP Work mode and all initialization work are completed
while loop ;
7. stay while Loop to detect the input of the serial port , If the serial port has input , Call handle_input According to the characters input through the serial port ( life
Make ), Switch working mode . This part is mainly to support the upper computer to input commands , According to the different treatment , Rukai 、
It is related to the collection of acceleration information or the output of debugging information ;
8. stay while Check whether there is data update in the loop (if (hal.new_gyro && hal.dmp_on)), When there are data updates
raw INT interrupt , Can make hal.new_gyro Set up 1 Of , To carry out if The condition code in ;
9. Use dmp_read_fifo Read the data to FIFO, This FIFO Refer to MPL A buffer defined by the software library , use
To buffer the latest collected data ;
10. call inv_build_gyro、inv_build_temp、inv_build_accel And inv_build_quat Function to process data angular velocity 、
temperature 、 Acceleration and quaternion data , And for flag variables new_data Set up 1;
11. stay while Detection in the loop new_data Sign a , Execute when new data is available if The condition code in ;
12. call inv_execute_on_data Function to update all data and status ;
13. call read_from_mpl Function to output the latest data to the host .
The first 15 Chapter . Gyroscope attitude detection
SAIUR201 6 The first 225 page
Data output interface
on top main The last call in read_from_mpl Function demonstrates how to call MPL Data output interface , Through these
Interface we can get the data we want , Its function definition is shown in the code list 15-17.
Code list 15-17 MPL Data output interface of (main.c)
The first 15 Chapter . Gyroscope attitude detection
The first 226 page SAIUR2016
The above code shows how to use inv_get_sensor_type_quat 、inv_get_sensor_type_accel 、
inv_get_sensor_type_gyro、inv_get_sensor_type_euler And dmp_get_pedometer_step_count Function to get four
Element number 、 The acceleration 、 angular velocity 、 Euler angle and pedometer data . In code eMPL_send_data Function is to use serial port according to
PYTHON Host computer format to submit data , The upper computer rotates the 3D model according to the data . In addition, we are in
Code to add the LCD code (#ifdef USE_LCD_DISPLAY The code in the macro ), It outputs this data to the test board
On your LCD screen . You can use it according to your own data needs , Refer to this read_from_mpl Function to the caller of the data output interface
type , Write your own application .
15.12.5. Download validation
Download this program directly to the development board , You can see the attitude angle on the LCD screen 、 temperature 、 Pedometer data , Change the posture of the development board ,
The data will be updated ( Pedometer data will not be updated until it simulates walking ), If you directly connect to the serial port debugging assistant , Will receive a series of garbled messages
Rest , This is normal , These data need to be decoded by upper computer .
The first 15 Chapter . Gyroscope attitude detection
SAIUR201 6 The first 227 page
15.13. MPU6050— Using a third-party host computer
The experiment in the previous section must be used with the official host computer to see the 3D model , And the function is relatively simple , therefore
In the section, we demonstrate how to output the data to a third-party host computer , Visually observe the posture of the device . In the experiment we used “ Hide
Flight control ground station 0512” Version of the PC , For the communication protocol of upper computer, please refer to 《 Flight control communication protocol 》 file , Or to them
Learn about .
15.13.1. Hardware design
The hardware design is exactly the same as the experiment in the previous section , Interrupt is also used INT Pin get data status , Software is used by default
I2C Communications .
15.13.2. software design
This section is about “MPU6050_DMP Test routine ” experiment , Please open the supporting code project to read and understand . In this section
The main body is the same as the last section , The main difference is when you get the data , This experiment is based on “ Anonymous flight control ” The data format of upper computer should be
Please upload data .
15.13.3. Key points of programming
1. Understand the communication protocol of the upper computer ;
2. Upload data to PC according to protocol format ;
15.13.4. The code analysis
Communication protocol
Upload data according to the format of the upper computer , First of all, we need to understand its communication protocol , The host computer protocol in this experiment is shown in table 15-7.
The first 15 Chapter . Gyroscope attitude detection
The first 228 page SAIUR2016
surface 15-7 Communication protocol of anonymous host computer ( part )
Two data frames are shown in the table , Namely STATUS Frame and SENSER frame , The data frame contains the frame header 、 Function words 、 length 、
Main data and checksums .“ Frame head ” Used to indicate the beginning of a packet , Both use two bytes of 0xAA Express ;“ Function words ” Used to distinguish
The type of data frame ,0x01 Express STATUS frame ,0x02 Express SENSER frame ;“ length ” A byte that represents the content of the following body data
Count ;“ The checksum ” Used to verify , It's the sum of all the previous content . Among them STATUS The frame is used to transmit the roll angle to the host computer 、 pitch
Angle and yaw angle (100 times ),SENSER Frames are used to transmit acceleration 、 Raw data of angular velocity and magnetic field strength . Send packet root
According to the above data format requirements , We defined two functions , They are used to send STATUS Frame and SENSER frame , See the code
single 15-2.
Code list 15-18 Send packet (main.c file )
The first 15 Chapter . Gyroscope attitude detection
SAIUR201 6 The first 229 page
The first 15 Chapter . Gyroscope attitude detection
The first 230 page SAIUR2016
The function is relatively simple , It's based on the input , Packaged byte by byte in format , Then the serial port is sent to the host
machine .
send data
Same as in the previous section , We use read_from_mpl Function output data , Due to the use of different upper computers , So we
The specific content of it has been modified , See code list 15-3.
Code list 15-19 read_from_mpl function (main.c file )
Call in code inv_get_sensor_type_euler Get the Euler angle , And then call Data_Send_Status The format is uploaded to the upper computer
machine , And the raw data of acceleration and angular velocity are directly from sensors Structure variables can be obtained , Get the post tone end_Data Send out .
The first 15 Chapter . Gyroscope attitude detection
SAIUR201 6 The first 231 page
15.13.5. Download validation
Download this program directly to the development board , You can see the attitude angle on the LCD screen 、 temperature 、 Pedometer data , Change the posture of the development board ,
The data will be updated ( Pedometer data will not be updated until it simulates walking ), If you directly connect to the serial port debugging assistant , Will receive a series of garbled messages
Rest , This is normal , This data needs to be used “ Anonymous flight control ground station ” The upper computer decodes . If you know from the information on the LCD screen
MPU6050 The module is working properly , It can be further used on the computer “ANO_TC Anonymous flight control ground station -0512.exe”( hereinafter referred to as
“ Anonymous host computer ”) Software view visualization data . The experimental steps are as follows :
1. Confirm the development board's USB TO USART The interface is connected to the computer , Make sure that the computer can view the serial device .
2. Open the... In the supporting materials “ Anonymous host computer ” Software , Open the serial port corresponding to the development board in the software interface ( The baud rate is 115200),
hold “ Basic code collection ”、“ Advanced code collection ”、“ Flight control waveform ” The function is set to on state . Click on basic transceiver in the figure above 、 Waveform display
in 、 Flight control status icon , It will pop up . See the software configuration diagram below for details .
3. In the software “ Basically ”、“ Waveform display ”、“ Flight control status ” Page can see scrolling data 、 Waves that change as the module wobbles
Shape and module attitude 3D Visual graphics .
The first 15 Chapter . Gyroscope attitude detection
The first 232 page SAIUR2016

Embedded MCU STM32 applied technology ( textbook ) More articles about

  1. The embedded Linux The debugging technology of

    In this section we study embedded Linux The debugging technology of , For complex Linux Drive and HAL And so on , It needs to be debugged in a variety of ways . At the beginning, I talked about Printing kernel debugging information :printk, The usage of this function is similar to printf Function similar to , It's just p ...

  2. Single chip microcomputer PWM Modulation technology

    We can look at the figure below , Here is a typical PWM Oscillogram of . T It's a cycle ,T1 It's the time taken by the high level ,T2 It's the time taken up by the low level . As shown in the figure above T1 Is the pulse width ( It's the turn-on time ), The period is T, Then the average output voltage is U ...

  3. AVR Interrupt system of embedded single chip microcomputer chip

    body, table{font-family: Microsoft YaHei ; font-size: 13.5pt} table{border-collapse: collapse; border: solid gra ...

  4. The embedded 02 STM32 experiment 07 Serial port communication

    STM32 Serial port communication (F1 Series contains 3 individual USART and 2 individual UART) One . SCM and PC The purpose and significance of serial communication between computers : Since the birth of single chip microcomputer, with its stable performance , The price is low . Powerful . In Intelligent Instruments . Industrial equipment and consumer electronics ...

  5. The embedded 02 STM32 experiment 01 Port reuse and remapping

    Inside and outside : Both port reuse and port remapping need to understand the internal and external devices , So what is built-in ? What are peripherals ? Built in : The integrated functions of single chip microcomputer generally include : Serial port module .SPI modular (Serial Peripheral Interface  ...

  6. Chapter ten The embedded Linux The debugging technology of

    Brief introduction of debugging tools .Linux Provides a class of tools , With these tools, you can track the program's code line by line , For testing user space programs gdb.gdbserver And debugging kernel space programs kgdb. use gdb Debugging user space programs :gdb Can follow ...

  7. Embedded system Boot Loader Technology insider

    Reprint :http://www.ibm.com/developerworks/cn/linux/l-btloader/index.html   1. introduction Run on a dedicated embedded board GNU/Linux System ...

  8. Single chip microcomputer stm32 Xiaobai's entry level learning route “ chart ”

      Study stm32 It's true that there are more and more , Of course, I'm also one of the languages , So for stm32 I'm very interested in your study route , So I want to share    Although it's stealing pictures    But it's also sharing  , There are some good videos below    I also offer   (stm ...

  9. 【 turn 】 Embedded system Boot Loader Technology insider , Take you to know Boot Loader

    Run on a dedicated embedded board GNU/Linux Systems have become more and more popular . An embedded Linux From the perspective of software, the system can be divided into four levels : 1.  Boot loader . Including curing in firmware (firmware) Medium boo ...

Random recommendation

  1. I have to look for TXT? Do it yourself TXT It's the right way to open it

    Preface I read a novel in the post bar and was deleted after several days , So I found the title of the book , I'm going to download it , As a result, it needs to be recharged , Or not available for download . As an ape , How can I bear it . Fortunately, novel websites are full of bullshit , Some use js Loading text to prevent collection , Some use css chart ...

  2. Chap5: question 35 - 37

    35. The first character that appears only once char firtNotRepeat(char *s) { if(s == NULL) return 0; int i = 0; while(s[i] != '\0') ...

  3. BZOJ-1067 rainfall Line segment tree + Classification of discussion

    This way B topic , Just can't , All kinds of broken points are easy to ignore , I can't stand birds any more 1067: [SCOI2007] rainfall Time Limit: 1 Sec Memory Limit: 162 MB Submit: 2859 ...

  4. Entity Framework with MySQL Study note 1 ( install )

    Statement :   The database is Mysql, I'm only good at writing sql sentence ( No savings process ), c# It will be basic ADO.NET Database access ,LINQ Basics . This is just a personal study | Review function . Novices can refer to , Please correct your mistakes , ...

  5. Mobile rem,scale Dynamic setting

    pt: Physical pixel ( The number of pixels on the capacitive screen ) px: Logical pixels . Device independent pixel HD screen :1px = 4pt Normal screen :1px = 1pt dpr: Device pixel ratio :( In a certain direction ) Physical pixel / Logical pixels Usually set 1rem= The screen ...

  6. Lucene.Net 2.3.1 Development Introduction —— Two 、 participle ( 5、 ... and )

    original text :Lucene.Net 2.3.1 Development Introduction -- Two . participle ( 5、 ... and ) 2.1.3  Binary participle In the previous section, we transformed the query expression to meet the requirements , But in practice , If you query like that , There will be another problem , because , Search like that , Only ...

  7. (PMP) The first 2 Chapter ----- Project operation environment

    1. Business environment factors :( Objective existence , May help or hinder , The project manager must comply with ) Inside : Culture , structure , government : Geographical distribution of facilities and resources , infrastructure , It software , Resource availability , Employee competence external : Market conditions , Society and culture , Legal restrictions , merchant ...

  8. bootstrap Front end template

    https://colorlib.com/wp/free-bootstrap-admin-dashboard-templates/

  9. ImageButton and ImageView Set the click transparent area not to respond

    Ideas ImageView and ImageButton All can be set background And set up src, The difference between the two is self-evident . Because of the difference between the two , The way to get their image resources is also different . If the setting is background, Then you need to ...

  10. [VC6,VC9] [ts,nts,deb] [rpm,msi] What format of file do you need to download

    1.VC6 And VC9 The difference between VC6 Version is using Visual Studio 6 Compiler compiled , If your PHP Yes, it is Apache To set up , Then you choose VC6 edition . VC9 Version is using Visual Studio 200 ...