Application of RT thread in the double car relay group of the 16th smart car competition

Zhuo Qing 2021-08-12 23:29:58 阅读数:636

本文一共[544]字,预计阅读时长:1分钟~
application rt thread double car

learn school : Shandong University ( weihai )
Team name : Haiyun team 2 competes
team member : Ren Jialin Guo Kai Wang Shouchao Miao Shuming takes
Team teacher : Wang Xiaoli

Jane Medium : In the 16th National College Students' intelligent car competition , Officials have designated different for different question groups MCU type , Including Infineon Infineon, Smart MindMotion, NXP NXP, Hongjing Technology STC, Qin Heng WCH. As the task becomes more and more complex , The difficulty of traditional bare metal development is also increasing , And they are no longer competent for some tasks that need to accurately control time . In the development of intelligent vehicle control system RT-Thread Real time embedded operating system , It can not only give full play to the performance of different chips , Make the smart car run more smoothly , It also shields the bottom hardware details of different MCU to a certain extent , Enhance the portability of the program , It improves the development efficiency of software . meanwhile , Use RT-Thread Automatic initialization in the kernel 、 Thread scheduling 、 Event set 、 Mailbox and other functions , It can also simplify the task of the smart car and enhance the real-time performance of the task performed by the smart car .

This paper is based on RT-Thread The application of three wheel vehicle model and vertical vehicle model in double vehicle relay group is studied , Firstly, this paper analyzes and expounds the structural characteristics of the car model specified for the double car set and the production of intelligent vehicles in our team , Combined with the traditional construction method and flying sample vehicle, this paper analyzes the innovation and advantages of our team's vehicle model construction , This paper briefly introduces the development and application of intelligent vehicle bare metal RT-Thread Differences in function implementation ; It introduces RT-Thread Real time embedded operating system , Illustrates the RT-Thread Official and zhufei technology on smart MM 32 Chip migration support , The results after transplantation are shown RT-Thread+ Fly by fly open source library MM32F3277 Project directory ; It specifies our team RT-Thread Application in intelligent vehicle development , Will use RT-Thread Compare intelligent vehicle development with intelligent vehicle bare metal development , It shows RT¬Thread Functions realized in the development of intelligent vehicles , That is, using thread scheduling 、 Mailbox and event set are used to replace the traditional timer to realize information collection 、 Motion control 、 Key scan 、 Screen display, etc , It shows its unique role in the development of intelligent vehicles ; Last , Through the actual commissioning of the trolley , Discover the use of RT¬Thread The application of the program in human-computer interaction is optimized ( Screen display 、 Key scan 、 Beeper On ) Use of , The correctness of timing is ensured in information acquisition and motion closed-loop control , It makes the attitude settlement of vertical car complementary filtering have good dynamic characteristics , The system has high stability and real-time response ability .

key word RT-Thread, The smart car race , Two car relay

 

§01 lead said


One 、 Smart car production

1、 Round F Structural characteristics of vehicle model

The mechanical structure of the three wheel system intelligent vehicle is mainly composed of a front double row universal wheel and a rear double row universal wheel RS380 Motor drive composition , The mechanical structure of the model is characterized by the combination of driving wheel and steering wheel , The steering control is realized through the differential speed of the left and right wheels , The double row universal wheels are used to drive and support the bottom plate of the vehicle model . [1] When debugging the car model, we summarized some control features of the car :

▲ chart 1.1 Round F Differential turning structure model of vehicle model

▲ chart 1.1 Round F Differential turning structure model of vehicle model

1. Good foresight , The left and right wheels responsible for driving and steering are at the tail of the whole model , Whether it's using a camera or inductive tracking , The track information collected by the sensor is far in front of the two wheels , It makes the control system have good foresight and predictability .

2. In the initial construction and commissioning of the car model , Put the battery 、 Circuit board 、 The camera and its bracket are fixed on the base plate in front of the wheel , The overall center of gravity of the trolley is forward , Because of the low speed , The requirements for steering torque generated by two wheel differential are not high , When the vehicle speed increases , because F The distance between the two wheels is small ( Compare with D vehicle ), Center of gravity forward , The steering torque generated by the two wheel differential is small , It is easy to cause the problem of curve sideslip and steering lag . Therefore, the tricycle system has high requirements for the overall center of gravity of the vehicle model .

The universal wheel in front of the tricycle is passive steering , All steering outputs are achieved by rear wheel differential , So if all the weight is in front of the motor , It's equivalent to the rear wheel pushing all the weight in front , Steering will be very difficult , If you put part of the weight behind the axle , Try to keep the front and rear weight balanced , Then its steering can be as flexible as a vertical car .

2、 Round F Production of vehicle model

Characteristics of vehicle model construction : According to the above three rounds F Structural characteristics and commissioning experience of vehicle , We use 3D The printing battery bracket is fixed at the rear of the car model , Fix the integrated board of main control drive, operation and amplifier above the support and the rear of the vehicle model , Secure the camera lever to the rear of the motor , And put the camera 、 Ultrasonic module 、 The infrared ranging module is fixed on the camera rod from top to bottom , Solenoid rod and 3D The printing ball feed seat is fixed on the head of the car model . The overall center of gravity of the model is backward , It is beneficial to the three wheel differential steering control system .

▲ chart 1.2 Round F Top view of vehicle model

▲ chart 1.2 Round F Top view of vehicle model

▲ chart 1.3 Round F Side view of car model

▲ chart 1.3 Round F Side view of car model

Innovation of vehicle model construction :

According to our handover strategy , Tricycle as ball delivery vehicle , In this way, the tee must be fixed on the head , In addition, the electromagnetic rod must be located at the head of the model because of its foresight and consider the three wheels in the competition rules F Limitation of vehicle model length , Although the battery bracket is used to fix the motherboard and battery at the rear of the model , The overall center of gravity of the model is still ahead , Generally, the construction of tricycle is to fix the camera rod on the bottom plate in the middle of the model , The flying sample car is to fix the camera rod on the head of the model car . In order to keep the center of gravity of the whole vehicle back , Differential steering system , We fixed the camera rod in the middle and back of the two motors , Despite the sacrifice of a little camera foresight , But it makes the overall center of gravity of the model backward , And the camera itself looks far ahead , The actual debugging has no great impact .

▲ chart 1.4 Fly the sample car one by one and fix the camera dry on the head of the model car

▲ chart 1.4 Fly the sample car one by one and fix the camera dry on the head of the model car

▲ chart 1.5 Fixing method of battery bracket and camera

▲ chart 1.5 Fixing method of battery bracket and camera

▲ chart 1.6 Use Solidworks Modeling battery support

▲ chart 1.6 Use Solidworks Modeling battery support

3、 Erect D Structural characteristics of vehicle model

What we use is D auto salon girls , The car model consists of half of the chassis of a normal car model and a rear double RS380 Motor drive , Than ordinary car models (C Vehicle model and F auto salon girls ) The track width is larger , It is beneficial to realize vertical self balance and steering . On the basis of maintaining self balance, the vertical vehicle model needs to use two wheel differential speed to realize tracking, and it also needs to keep upright when turning at high speed and on slopes , This requires that the center of gravity of the model must be reasonable .

First of all, we need to keep the center of gravity of the model as low as possible , In this way, the model will be more stable ; Secondly, a large pitch angle needs to be reserved in the structure , In this way, there is more space for attitude adjustment , It is conducive to crossing the ramp , Then you need to keep the weight as concentrated as possible , Try to stay near the axle ; Finally, ensure the balance of front and rear weight , Try not to appear The phenomenon that balance can only be maintained by counterweight .

In the course of debugging , Because our main tracking method is camera tracking , So the position of the camera lever 、 Camera angle and its variation range during movement , Will affect the image processing and control effect. At the same time, the change of vertical vehicle speed will produce the change of attitude angle, resulting in the change of camera angle , So we have tried many times to build different positions and angles of the camera pole .

4、 Erect D Production of vehicle model

Comprehensive consideration of handover strategy ( The upright needs to be used as a receiving car to wait for the ball in three fork roads ) And commissioning experience , We finally chose the car chassis to face the rear and tilt up , Fix the battery with a ready-made metal battery support. The camera rod is fixed in the middle of the two wheel motors , The middle gap of the main control drive operational amplifier integrated board is fixed above the trolley motor through the camera rod , With the electromagnetic rod trolley V Font structure .

▲ chart 1.7 Erect D Model car V Font structure

▲ chart 1.7 Erect D Model car V Font structure

Innovation of vehicle model construction :

It is best to keep the camera rod vertical to the ground when driving at the normal speed of the vertical model , At the same time, the center of gravity is reasonable and compact, and the appropriate attitude control algorithm will make the attitude angle change caused by the vertical vehicle in other speed states or elements, such as the ramp, as small as possible , This will minimize the impact on camera angle changes , Image processing and steering control will have good adaptability .

So we'll be in charge 、 drive 、 The operational amplifier is drawn into an integrated board , And make holes , Fixed in D Above the model motor , The camera rod is fixed between the two motors and passes through the opening , In this way, the overall center of gravity of the model falls on the motor , And the structure is compact .

▲ chart 1.8 Opening treatment on integrated plate

▲ chart 1.8 Opening treatment on integrated plate

5、 Fabrication of handover structure

We use three wheels F The car is a ball delivery car , Erect D The car is a receiving car , In order to shorten the handover time , The vertical model stays upright in the three fork road waiting for the ball , The handed over ball is a table tennis ball with magnets of different volumes and strengths pasted before and after use , Use of ball delivery vehicle 3D Print ball feed socket , A magnet is used to fix the table tennis ball in the seat , A long baffle plate is installed behind the model chassis and a magnet is used + Fix the ball by Velcro , This fixing method makes the small ball not easy to fall in the process of transmission and driving .

▲ chart 1.9 Table tennis ball with magnets pasted front and rear

▲ chart 1.9 Table tennis ball with magnets pasted front and rear

▲ chart 1.10 Use SolidWorks Three rounds of modeling F Ball feed socket of car

▲ chart 1.10 Use SolidWorks Three rounds of modeling F Ball feed socket of car

▲ chart 1.11 Ball receiving structure behind vertical model chassis

▲ chart 1.11 Ball receiving structure behind vertical model chassis

Two 、 Application in smart car competition RT-Thread Embedded system

1、 Introduction to embedded system

After the advent of microprocessors , Embedded computers have been developed .1971 year , The arithmetic unit and controller circuit are successfully integrated , Introduced the first microprocessor , Since then, various manufacturers have launched 8 position 、16 Bit microprocessor . The system based on these microprocessors is widely used in instruments and meters 、 Medical equipment 、 robot 、 Home appliances and other fields . The wide application of microprocessor has formed a broad embedded application market .20 century 80 years , With the improvement of microelectronic technology , Integrated circuit manufacturers began to integrate microprocessors needed in embedded computer applications 、I /O Interface 、A/D converter 、D/A converter 、 serial interface , as well as R AM、R OM And other components are all integrated into one VLSI in , So as to create a face-to-face I/O Designed microcontroller , Commonly known as single chip microcomputer . Single chip microcomputer has become a rising star in embedded computer .20 century 9 0 years , In distributed control 、 flexible manufacturing 、 Driven by the huge demand for digital communication and information appliances , Embedded system is developing rapidly . Research on real-time signal processing algorithm DSP Products towards high speed 、 High precision 、 The direction of low power consumption .21 The 21st century is an era of Internet prevalence , The application of embedded system to all kinds of networks is an important direction of its development .

2、 Real-time operating system

Real-time operating system 〔Real Time Operating System) It refers to external events or data products When I was born , Can withstand and dispose of quickly enough , The result of its disposal can quickly respond to the processing system or control the production process within the specified time , Scheduling all available resources to complete real-time tasks , And control the operating system of all real-time tasks running coordinately , Providing timely response and high reliability are its main features . If the timing and logic of the real-time operating system deviate , It will have serious consequences for the operation of the system , Therefore, the real-time operating system is required to have very strict timing and logic. The real-time operating system is divided into hard real-time system and soft real-time system . In hard real-time systems , Not only is the task response required to be met under any conditions , And it is required to complete the event processing within the specified time . Soft real-time system only requires the event response to be real-time , It is not required to limit how long a task must be completed . Will not cause catastrophic errors . Usually , Most real-time systems are a combination of the two . The key technology of real-time system is how to ensure the real-time performance of the system . The real-time operating system mainly has the following three characteristics :

  • The real time : Usually , Most of the systems with high real-time performance are processed by real-time operating system . It can detect and control the action of system equipment in real time . such as , Applied to control missile engine 、 Medical devices, motors and other embedded systems , The of the control object must have strict timing , And have a faster reaction speed , It has good switching timing for multiple control objects , Otherwise, it may cause the tragedy of aircraft destruction and human death . The non real-time operating system cannot complete the task in such an environment . Therefore, the core of embedded system is to have RTOS Real-time operating system , It is also its biggest advantage .
  • Tailorability : For the diversification of embedded system environment , Real time operating system is object-oriented . Facing customers 、 Product oriented 、 For application , Must have strong adaptability , Developers can according to the characteristics and requirements of the system . Flexible tailoring and configuration of the operating system . There are many functions of the operating system, but in a certain embedded device , The functional requirements of the operating system are also determined , So just leave the functions you need . Tailorability is achieved through software configuration “ Plug and play ”.
  • reliability : Facing the changeable running environment of embedded system 、 Poor operating environment, etc . The embedded operating system is required to have strong reliability . After the embedded device is designed , The system generally operates automatically . Nobody intervened . This not only requires the embedded operating system to have strong stability and reliability , Moreover, it is also required that the real-time operating system has good compatibility with the application software .

3、 Development and application of intelligent vehicle bare metal RT-Thread Comparison in function realization

Before , We often use the open source library of flying by flying for bare metal development in the software development of intelligent vehicles , Write programs directly on bare metal . here , The program is divided into two parts : Front and back systems , Such a program includes a dead cycle and several interrupt service programs : An application is an infinite loop , A function is called in the loop to complete the required operation , This big loop is the background system . The foreground system is the interrupt service program , Used to handle asynchronous events of the system . We often use interrupt to realize timing function in smart car competition , such as PID Calculation 、 Sensor acquisition data 、 Steering gear motor PWM Output and so on , Through different interrupt timings , Use global variables to exchange data between interrupts .

▲ chart 1.12 Logic operation flow chart of intelligent vehicle

▲ chart 1.12 Logic operation flow chart of intelligent vehicle

however , The real-time performance of bare metal development is low 、 Poor code readability . Imagine a scenario , MCU is executing task1 when , Suddenly need to execute task2, But the foreground and background programs can only ta sk1 After execution , To perform task2, This greatly affects MCU Real time performance of tasks , Not conducive to special tasks ( Such as entering the ring 、 Put in storage 、 Camera patching, etc ) Real time execution of .

While using RT-Thread after , We can make full use of MCU resources , Improve MCU Real time performance of tasks . We will write the main function processing functions to each thread , Reuse mailbox 、 The semaphore function realizes the communication between threads , Send the collected or calculated data to the total thread , The total thread identifies the data collected by processing , So as to complete the operation task of Intelligent Vehicle .

▲ chart 1.13 RT-Thread Operation flow chart

▲ chart 1.13 RT-Thread Operation flow chart

 

§02 RT-Thread The embedded OS


One 、RT-Thread brief introduction

RT-Thread Full name Rea l Time-Thread, It is an embedded real-time operating system developed and maintained by the domestic team (RT OS), It was born in 200 6 year , With complete independent intellectual property rights . After nearly 1 5 Years of precipitation , With the rise of the Internet of things , It's evolving into a powerful 、 Rich components 、 Highly scalable 、 Simple development 、 Ultra-low power consumption 、 High security Internet of things operating system .

RT-Thread Have a IoT OS All the key components required for the platform , for example GUI、 Network protocol stack 、 Secure transport 、 Low power components and so on . after 11 Years of cumulative development ,RT-Thread It has the largest embedded open source community in China , At the same time, it is widely used in energy 、 vehicle 、 Medical care 、 Consumer electronics and many other industries , The cumulative installed capacity exceeds 8 One hundred million units , To be developed independently by Chinese people 、 The most mature and stable open source with the largest installed capacity in China RTOS.

RT-Thread And others RTOS( FreeRTOS、 uC/OS) The main difference is :RT-Thread Since its inception, positioning has been more than just a RTOS kernel , It's a network 、 file system 、 GUI Middleware platform of interface and other components , It has strong expansibility .

RT-Thread Have a good software ecosystem , Support all the mainstream compiler tools on the market, such as GCC、 Keil、I AR etc. , Perfect tool chain 、 friendly , Support all kinds of standard interfaces , Such as POSIX、CMSIS、C++ Application environment 、Javascript Execution environment, etc , It's convenient for developers to transplant all kinds of applications . Business supports all mainstream MCU framework , Such as ARM Cortex-M/R/A, MIPS, X86, Xtensa, C-Sky, RISC-V, Almost all the mainstream MCU and Wi-Fi chip .

Two 、RT-Thread framework

RT-Thread With many others RTOS Such as F reeRTOS、 uC/OS One of the main differences is , It's not just a real-time kernel , It also has rich middle tier components , As shown in the figure .

▲ chart 2.1 RT-Thread System architecture

▲ chart 2.1 RT-Thread System architecture

It includes three parts , Kernel layer 、 Component and service layer 、RT-Thread software package .

The kernel layer includes RT-Thread Kernel and libcpu/BSP. among ,RT-Thread The kernel is related to software functions , Is the core part of the embedded operating system , And the realization of the features and functions of the system , Such as multithreading scheduling 、 Message queue 、 mailbox 、 Semaphore 、 Dynamic memory management, etc . and libcpu/BSP Related to hardware functions , It contains the files required for migration and board level support package , Driven by peripherals and CPU Transplant composition .

Component and service layer based RT-Thread structure , Including virtual file system 、 Network framework 、FinSH Other upper layer software . Each part of it is built with modularization , Achieve high cohesion within components , Low coupling between components , It is convenient for users to call specific functions alone .

RT-Thread The package runs on RT-Thread Internet of things operating system platform , Including common software components in different fields , By description information 、 Composed of source code or library files .RT-Thread It provides an open software package platform , There are software packages provided by the official or developers , The platform provides developers with many choices of reusable software packages , This is also RT-Thread An important part of Ecology . Software package ecology is very important for the choice of an operating system , Because these software packages are highly reusable , High degree of modularity , It is very convenient for application developers to , Create the system you want .

3、 ... and 、RT-Thread Functional features

1、 Thread scheduling and idle threads

Thread is the carrier of task implementation , It is RT-Thread The most basic dispatching unit in the system , It describes the running environment of a task execution , It also describes the priority of the task . Compared with bare metal development in task processing ,RT-Thread The biggest feature is the multi-threaded processing scheduling function .

In bare metal development logic , When MCU call de lay When the function is delayed , Pauses the execution of the current task , And make MCU Idle , To some extent, it wasted this time MCU Calculation power .

And when introduced RT-Thread After the thread scheduling function , stay ta sk0 Time delay ,RT OS Can call priority lower than task0 Of ta sk1、ta sk2 To run the , stay ta sk0 Continue after the delay task0, It realizes the control of idle MCU Utilization of performance , Improved MCU Operational efficiency , The overall running time is reduced under the same amount of tasks , As shown in the figure below .

▲ chart 2.2 Logic and RTOS Processing task mode comparison

▲ chart 2.2 Logic and RTOS Processing task mode comparison

in addition , In order to achieve MCU Maximize performance ,RT-Thread Idle thread function is also added . Idle thread is a special system thread , It has the lowest priority , When there are no other ready threads in the system to run ,RT-Thread The scheduler will schedule to an idle thread . Besides , Idle threads are also responsible for some system resource recycling and removing some closed threads from the thread scheduling list , It is an infinite loop structure in form , And never be suspended .

stay RT-Thread Real time operating system , Idle threads provide the user with hook functions , The idle thread hook function allows the system to perform some non urgent transactions when idle , For example, the system operation indicator flashes ,CPU Usage statistics and so on .

2、 Semaphore 、 Message queue 、 mailbox

stay RT-Thread in , The communication between threads is mainly through semaphores 、 Message queue 、 Mailbox module implementation . among , Semaphore is a lightweight kernel object used to solve the synchronization problem between threads , Threads can get it or release it , So as to achieve the purpose of synchronization or mutual exclusion ; Message queuing is another common way of inter thread communication , It can receive messages of variable length from threads or interrupt service routines , And cache messages in your own memory space . Other threads can also read corresponding messages from the message queue , And when the message queue is empty , The read thread can be suspended . When a new message arrives , The suspended thread will be awakened to receive and process messages . Mailbox is a simple way of messaging between threads RT-Thread The implementation of the operating system can pass 4 Byte mail , And the mailbox has a certain storage function , A certain number of messages can be cached .

In bare metal development logic , We usually use global variables to store the data collected by sensors , Read global variables between output calculations . such as , take ad c The collected inductance data is stored in ad _val Array , Then, it is converted into the normalized value through operation , Store in ad c_normalized In the array . When special element judgment is required, directly read the value stored in the current array , As shown in the figure below .

▲ chart 2.3 Use ad_val The data is stored in the collected inductance value

▲ chart 2.3 Use ad_val The data is stored in the collected inductance value

▲ chart 2.4 Special element judgment directly reads the value

▲ chart 2.4 Special element judgment directly reads the value

When we carry out the actual intelligent vehicle engineering development , It often involves a thread updating the value of a global variable , Then another thread reads the global variable value , Perform different operations according to the value of this global variable . stay RT-Thread operating system in , mailbox 、 Message queue 、 Semaphore these functions can be used as tools to help the system transfer information between different threads , It provides more implementation methods for intelligent vehicle operation .

3、 Event set

RT-Thread The event function in is mainly used for synchronization between threads , Different from semaphore , Its characteristic is that it can realize one to many , Many to many synchronization . Another feature of events is , The receiving thread can wait for a variety of events , That is, multiple events correspond to one thread or multiple threads . At the same time, according to the parameters that the thread waits for , Optional yes “ Logic or ” Trigger or “ Logic and ” Trigger .

RT-Thread Defined events have the following characteristics :

Events are thread related only , Events are independent of each other : Each thread has 32 Event markers , Use a 32 bit Unsigned integers are recorded , every last bit For an event . Several events form an event set ;

Events are used for synchronization only , Data transmission function is not provided ;

Event non queueing , That is, send the same event to the thread multiple times ( If the thread has not had time to read ), The effect is equivalent to sending only once .

In bare metal development logic , We often use global variables to represent the flag bits of special elements . For example, the camera completes the acquisition 、 Location stages of roundabouts and ramps 、 Rush out of the track and stop 、 Completion of tasks, preparation for warehousing, etc . While using RT-Thread After the event set function , We can write flag bits of the same type as an event set , It contains different events , Use different parameters when reading , Achieve the purpose of triggering the judgment result according to the specified task , If you encounter acceleration and deceleration at different positions of the ramp during operation , Long straight acceleration, etc .

▲ chart 2.5 Event set judgment ramp flag bit

▲ chart 2.5 Event set judgment ramp flag bit

Four 、RT-Thread Yes, smart MM32 Chip migration support

1、RT-Thread Transplant to intelligent automobile chip platform

initial stage , Flying one by one NXP、 Smart 、 Qinheng three chip manufacturers and RT-Thread Transplant well with the technical support of the company RT-Thread operating system .RT-Thread The engineer is responsible for the modification RT-Thread The underlying file of the operating system , To fit InfineonTriCore Kernel MCU and AURIX Development Studio IDE Software . Zhufei technology will be modified RT-Thread Migrate the underlying files of the operating system to the existing Infineon open source library , And do a good job in the adaptation of relevant peripherals for intelligent vehicle application . At the initial stage, it mainly supports the following chip platforms : RT1064、RT 1021、MM 32SPIN27、MM 32F3277、CH 32V103.

after , Zhufei further completes the peripheral drive required by the peripheral of the intelligent vehicle , 2 To the end of 3 Based on RT-Thread Open source library , adopt gitee And open it to all participating students .

Zhufei technology also depends on the different characteristics of the chip , Adapted for special chip platform RT-Thread nano edition , Such as small memory MM32SPIN27、CH32V103. and RT1064、RT 1021、MM 32F3277、TC 2644、TC 364、TC 377 Chip resources are relatively rich , So it fits RT-Thread The full version of . 6 month 25 Japan , Zhufei Technology launched Infineon TC 264、TC 364、TC377 Platform RT¬Thread operating system , Three groups related to Infineon MCU ( Basic four wheel set 、AI Electromagnetic off-road group 、 Energy saving beacon group ) Finally, it can be used RT-Thread operating system .

Besides , Zhufei technology also provides 10 A kernel example is convenient for students participating in the smart car competition to get started quickly , Help students who have not touched the embedded development operating system to learn to use RT-Thread This powerful tool . Zhufei technology also specially compiled a program based on RT-Thread Smart car frame example , Students who avoid participating in smart car competitions continue to use bare metal ideas to build the whole framework .

2、RT-Thread+ Fly by fly open source library MM32F3277 Project introduction

MM32F3277 Of RT-Thread The open source library continues to follow the code style of other open source libraries of zhufei Technology , Simple and easy to understand , Easy to use . The open source library uses the official S DK As the bottom layer . Then the registers used by each module are encapsulated again , Improved ease of use .

▲ chart 2.6 RT-Thread+ Fly by fly open source library MM32F3277 Project directory

▲ chart 2.6 RT-Thread+ Fly by fly open source library MM32F3277 Project directory

The full directory of the open source library is shown in the figure above .

The following is a directory of the open source library :

  • Project/CODE The code files added by the user are placed under the folder ;
  • Project/USER Under the folder is main.c、i sr.h、i sr.c file ;
  • Project/IAR Under the folder is IAR Engineering documents of ;
  • Project/MDK Under the folder is MDK Engineering documents of ;
  • Libraries/Device What is placed under the folder is official S DK The basement ;
  • Libraries/doc Under the folder is the open source library version 、 Recommended pin assignment description ;
  • rtthread_libraries Under the folder is RTT Related source files ;
  • Libraries/board Under the folder is the version document description ;
  • Libraries/seekfree_libraries Under the folder is the bottom driver carefully written by zhufei technology , The bottom drive is provided by smart microelectronics MM 32F3277 Of S DK Secondary packaging , To simplify the use of each module , It's more convenient to use ;
  • Libraries/seekfree_peripheral Under the folder are various commonly used module drivers , When using these modules, you only need to call functions to realize the corresponding functions , Very simple and convenient . Linearity is currently achieved CC D、 Small drill air hardware binary camera 、 Global shutter gray value of total drilling air 、 1.8 " TFT、ICM 20602 Six axis gyroscope 、IIC Communication protocol ( simulation IO)、 1.14 " IPS LCD screen 、 2 " IPS LCD screen 、MPU 6050 Six axis gyroscope 、OLED display 、 Virtual oscilloscope communication protocol 、 Wireless to serial port module .

3、 Intelligent automobile bare metal engineering transplantation to RT-Thread Open source library process

▲ chart 2.7 RT-Thread In the open source library Smart_Car_Demo engineering

▲ chart 2.7 RT-Thread In the open source library Smart_Car_Demo engineering

Above, RT-Thread Open source library S mart_Car_Demo engineering main.c file , It can be seen that , The open source library style follows the flying open source library style used in bare metal development , It is convenient for us to transplant intelligent automobile engineering . We first put the old project Pro ject/CODE Under the .c and .h Copy and paste all the files into the corresponding folder of the new project , And then in M DK Corresponding is added to the engineering structure .c and .h file , And in headfi le.h Use in in clude Write your own .h The file contains , The file migration is completed .

After transplantation, we compiled the whole project , It is found that there are problems in the project error, After investigation , We found that function. Multiple library functions and seekfree_fun.c Middle phase coincidence , Duplicate definitions were generated , So we comment out the duplicate library functions , Solved the problem .

meanwhile , Because the image array collected by the general wind drilling camera is stored in the new library of flying by flying mt9v03x_image Not in the old library i mage in , Our image processing files i mage.c The error display variable is undefined , So we use M DK Find replace tool for , stay seekfree_peripheral\SEEKFREE_MT9V03X.c All mt9v03x_image Replace with image, That solved the problem . such , We completed the engineering transplant .

After engineering migration , Let's try to join a little bit RT-Thread The function of the kernel , For example, the flag bit can be replaced by an event set , The buzzer can use the mailbox to control the duration of the beep , In the past, interrupt loop execution statements can be placed in threads and implemented by thread scheduling , wait . We also use a combination of traditional timers and threads , To achieve the best running state of intelligent vehicles .

 

§03 RT-Thread application


RT-Thread Application of in double car relay group

One 、 Overview of the characteristics of the two car relay group in the intelligent car competition

In the double car relay group of the 16th National College Student intelligent car competition , Each team consists of up to 5 The composition of people , Three rounds need to be made (F auto salon girls )、 Erect (D,E auto salon girls ) Two smart cars . In the game , Both smart cars need to complete their own track element tasks , And in 16 New element —— Complete the transfer of the ball in the three fork intersection .

say concretely , At the beginning of the game , A model car stopped in the middle of a fork in the road . A model car starts from the garage , When reaching the middle model position , One dimension on the vehicle shall not be less than 40 Mm square sphere passed to the second car model , Then stop waiting in place .

The second model car took the ball around the track again and stopped at another fork at the third fork , As long as it is more than one meter away from the third fork of the road . The first model car can be restarted and returned to the garage .

Compared with other groups , Because the double car relay group needs to realize the ball passing and receiving between two cars on the basis of tracing , The role of the mechanical structure is amplified , Reasonable mechanical structure is the key to passing and receiving the ball , In addition, the motion attitude and control characteristics of three wheeled and upright models are different , The tracking tasks of the receiving car and the sending car are also different , Therefore, it is very important to select the passing strategy according to its characteristics to complete the competition task .

Two 、 adopt RT-Thread The automatic initialization function of simplifies the code

1、RT-Thread Introduction to startup process of

RT-Thread Startup process , It can be roughly divided into four parts :

1. Initialize system related hardware ;
2. Initializing system kernel objects , For example, timer 、 Scheduler 、 The signal ;
3. main Threads , stay main Various modules are initialized in turn in the thread ;
4. Initialize timer thread 、 Idle Thread , And start the scheduler .

As shown in the figure below :

▲ chart 3.1 RT-Thread Start flow chart

▲ chart 3.1 RT-Thread Start flow chart

Generally speaking , When adding new functional modules to the system , Must be initialized before use , The usual approach is to manually add and call initialization functions before the main program runs . and RT-Thread It provides another initialization method with low coupling and high cohesion , It does not require us to manually add and call initialization functions , It can automatically complete the initialization of each module before the system runs .

2、 Use of automatic initialization function

In the development of traditional intelligent vehicle engineering , We usually run after the car is powered on main Start calling the initialization function of each part in the function , To realize the initialization of trolley function .

▲ chart 3.2 Initialization function of traditional logic development

▲ chart 3.2 Initialization function of traditional logic development

▲ chart 3.3 In logic development main Function call initialization function

▲ chart 3.3 In logic development main Function call initialization function

Use RT-Thread after , We can use its automatic initialization function to realize the automatic initialization of each component , No need to main Call function directly in .
Use automatic initialization function , Need to call RT-Thread Of INIT Macro interface .

stay RT-Thread in , There are six INIT Macro interface , As shown in the figure below .

▲ chart 3.4 RT-Thread Six of them INIT Macro interface

▲ chart 3.4 RT-Thread Six of them INIT Macro interface

When using , You only need to call the corresponding macro interface , Write the function in init Below the function , Automatic initialization can be completed when the system is running , As shown in the figure below .

▲ chart 3.5 Reference HTC to the effect of automatic initialization

▲ chart 3.5 Reference HTC to the effect of automatic initialization

Compared to all init The function is in main Traditional practices in functions , This can no doubt reduce the amount of function called in the main function , Make the code more concise and intuitive .

however , Each initialization function needs to be called in a certain order , such as board_init, That is, the core board initialization should be executed first , The second is peripheral components , The last part is the application part . here , We can call different INIT Macro interface , To realize the sequential initialization from the bottom layer to peripherals and then to applications .

In practice , We use INIT _BOARD_EXPORT(board_init), Install the core board at the beginning Initial place 1 The order of , Hardware initialization , Other initializations are placed in 3 The order of ( Such as camera 、 Screen display 、 Key 、ADC modular 、 Encoder 、 A serial port ), That is, peripheral driver initialization .

such , When we use RT-Thread after , Can be simplified main Code in function , At the same time, it can realize the sequential initialization operation of each component .

3、 ... and 、RT-Thread Thread scheduling in three wheel differential control 、 Application of in upright posture adjustment

1、 Round F Overview of vehicle model control characteristics

Round F The vehicle control strategy is to turn using angular speed PI -- Centerline deviation PD Cascade , The speed is incremental PI control , Use cascade PID The angular velocity of steering shaft collected by control and gyroscope as the input of steering inner loop can make the response of steering closed-loop control system faster , A more stable . Because we use the camera as the main tracking method , The camera usually takes a long time to process image information , Therefore, it is very important to coordinate the operation sequence of each part , During normal debugging, we found three rounds F Because of the structural characteristics of the car , The two motors need to adjust the differential speed in time according to the deviation of the center line of the track to realize high-speed steering , So we need the camera to process the track information and update it in time , In addition, the amount of computation of closed-loop control is less , Therefore, the priority of image processing function should be higher than that of control closed-loop function .

▲ chart 3.6 Round F auto salon girls PID Control flow chart

▲ chart 3.6 Round F auto salon girls PID Control flow chart

2、 Erect D Overview of vehicle model control characteristics

Erect D In terms of vehicle attitude control, we use a more mature cascade PID, That is, attitude speed control is used “ Angular velocity loop - Angle ring - Speed loop ”, Cascade PID There are three links , One is the velocity loop 、 One is the angle ring 、 The last one is the angular velocity loop , The connection between them is , The output of the speed loop represents the desired angle and is then fed into the angle loop , The output of the angle loop represents the desired angular velocity and is then fed into the angular velocity loop , The output of the angular velocity loop is directly used to control the motor . Cascade PID It has the advantages of easy understanding and convenient debugging , Can be quickly debugged than a single loop PID Good effect . The steering uses the same three wheels F The same control method as the vehicle , Deviation outer loop and angular velocity inner loop cascade .

During normal debugging, we found that , Because the number of vertical closed loops is more than that of three wheel control, and gyroscopes need to be used for high-frequency data acquisition and attitude calculation , Because of the characteristics of its vertical structure center of gravity , More flexible steering , The requirements for track deviation update speed are not high , Therefore, the priority of attitude data acquisition and control closed-loop processing function should be greater than that of image processing function .

▲ chart 3.7 Erect D auto salon girls PID Control flow chart

▲ chart 3.7 Erect D auto salon girls PID Control flow chart

3、 Three wheel differential control is realized by thread scheduling function

Compared with the previous use of fly by fly open source library for bare metal development of intelligent vehicle control program PIT Timer to complete the key scanning of smart car 、 Sensor information collection 、 Output calculation 、 Output control , Use RT-Thread after , We use threads + Timer instead of traditional PIT Regularly modularize each task during the operation of the intelligent vehicle , Divide it into ADC Electromagnetic acquisition + Infrared ranging module acquisition thread 、 Gyroscope steering angular velocity information acquisition thread 、 Encoder two wheel speed acquisition thread 、 Five axis key scanning thread 、 The screen shows five small threads of image parameter thread , And process the data + The differential output function is placed in a separate timer , To achieve precise timing control .

▲ chart 3.8 Logic development program flow chart

▲ chart 3.8 Logic development program flow chart

Use RT-Thread Before , Our team's project will run_realize() The motion control processing function is placed in a period of 1ms Of PIT In interruption , Through global variables cnt_1ms Self addition and zero clearing to realize each closed loop PID Timing control of , Achieve the goal of intelligent vehicle executing tasks in a certain sequence .

▲ chart 3.9 Intelligent vehicle logic development tweets monk ah global variables as counters to achieve timing control

▲ chart 3.9 Intelligent vehicle logic development tweets monk ah global variables as counters to achieve timing control

This method should be used by smart car competitors all the time , But this method has many disadvantages :

Program readability is not strong , More comments are needed to help understand the program structure .

Each closed loop PID Calculation tasks are executed sequentially , There is no concept of priority , When performing a general task, if it is necessary to perform a task urgently ( Such as camera patching 、 Special element identification ), The real-time performance of the task will be greatly reduced , It may cause trolley identification error , Even out of the track .

Program modularization is not implemented , When something goes wrong in a part of the program, you need a little debugging to find , It will directly affect the overall task execution of the trolley .

Use RT-Thread After the thread scheduling function , Each task can be modularized , Split into separate threads , It not only enhances the readability of the program , And greatly increases the real-time performance of the overall program of the car .

▲ chart 3.10 Round F Vehicle model thread Division

▲ chart 3.10 Round F Vehicle model thread Division

The picture above shows the use of RT-Thread Thread division of rear three wheel trolley , Be clear at a glance , The program is readable , When a module has a problem , You can switch threads directly and individually , It does not affect the normal execution of other functions . meanwhile , Each thread has its own timing ti ck, Set the priority of each function , It can be made up of RT-Thread The kernel realizes the automatic scheduling of each thread .

The following figure shows the use of RT-Thread System flow chart of rear three wheel trolley .

▲ chart 3.11 Use RT-Thread Operation flow chart of rear trolley

▲ chart 3.11 Use RT-Thread Operation flow chart of rear trolley

4、 The thread scheduling function is used to adjust the upright posture

Use RT-Thread Before , Our project is to turn to the control function turn_realize()、 Motor output pwm function motor_pwm_Calculate(Speed_L_Result, Speed_R_Result) Put it separately in a timer interrupt , The attitude solution function AD_Calculate()、 Speed calculation function Speed_Calculate(g_fCarAngle,angle_dot) Put in another timer interrupt , And inductance 、 The data acquisition of infrared and gyro sensors are also placed in these two interrupts , from cnt_Av as well as cnt_speed To achieve timing control , To realize the attitude control of vertical vehicle 、 speed control 、 Steering control and other functions .

Attitude control of upright vehicle , Similar to the idea of three wheel control , Use PIT Timer to complete the information acquisition and output control of the car , Use RT-Thread after , We use threads to modularize each task and divide it into ADC Electromagnetic acquisition + Infrared ranging module acquisition thread 、 Gyroscope information acquisition and complementary filtering 、 Encoder two wheel speed acquisition thread 、 Five axis key scanning thread 、 Screen display image parameter thread 、 Camera image processing thread six small threads , The data processing and output functions are placed in two different timers to execute , To achieve reasonable and accurate timing control .

▲ chart 3.12 Erect D Thread division of vehicle

▲ chart 3.12 Erect D Thread division of vehicle

Four 、 adopt RT-Thread The mailbox function of cooperates with the thread function to realize the buzzer assignment

1、 Duration phonation

During intelligent vehicle debugging , The method widely used by contestants is to make the buzzer sound when identifying a special element or a flag is established , Observe whether the trolley recognizes special elements and the position of special elements in real time . That is, use... In the corresponding track information processing function if function , Judge whether the value of the flag bit meets the requirements , And then call gpio_set() Function to operate the buzzer .

however , When there are multiple special elements to be identified , Like a fork in the road 、 Roundabout , We can't know which special element is recognized according to the sound of the buzzer . Because the system cycle is relatively short , The traditional method is difficult to use the delay function to make the buzzer sound for a specified time , Moreover, using the delay function in the camera processing function to realize the fixed length sound generation of the buzzer will cause many timing problems , Can only be achieved as in the sign position 1 Time chirp , At sign position 0 Do not chirp when , This makes it very difficult to distinguish a variety of different elements with a buzzer .

adopt RT-Thread Mailbox function of , We can call the buzzer thread when we need to use the buzzer , At this point, the buzzer thread sends mail to the mailbox , The buzzer starts to beep . After a specified length of time , Suspend the thread , Mail sending stops at this time , The buzzer stops , In this way, the buzzer can sound for a specified time , Create buzzer individual thread .

▲ chart 3.13 Buzzer thread

▲ chart 3.13 Buzzer thread

5、 ... and 、 adopt RT-Thread The event set function realizes the flag bit function

In the development of intelligent vehicle bare metal , We often use global variables as flag bits for special elements , For example, judge the roundabout according to the collected track information characteristics 、 Different stages of elements such as ramps , Assign corresponding flag bits respectively 0123 Other specific values , Then, in the motion control function, according to the different states of the flag bit , To control the trolley to enter and exit the roundabout 、 Straight curve 、 Speed control of up and down ramps 、 Camera look ahead setting 、 Buzzer prompt and other special operations , So as to successfully complete the track operation task .

Use RT-Thread after , We can take advantage of the event set function , Round the island 、 The flag bits of elements such as ramps are classified into the same event set .

▲ chart 3.14 There are several different events after meeting different conditions

▲ chart 3.14 There are several different events after meeting different conditions

▲ chart 3.15 Ramp event detected 2 Rear adjustment of three wheel car's foot kick

▲ chart 3.15 Ramp event detected 2 Rear adjustment of three wheel car's foot kick

When reading status , We can use it according to different occasions , Modify the conditions for event triggering . such as , Before the smart car enters the formal operation mode , We often hold the car in our hands , Use the screen and five axis keys to adjust and preset parameters , However, at this time, each sensor of the trolley has been initialized and entered the operation mode , If no special treatment , The trolley is likely to enter the flag bit of a special element during parameter adjustment , Cause problems in the running process of the trolley and rush out of the track .

In this case , We can use it RT-Thread The event set function of . for example , For ramp identification , We used the ramp state event set , And put the creation statement of the event set after the trolley switches to the formal operation mode , That is, when the trolley officially starts running , Only then can the identification and output processing of the ramp be carried out normally , If the trolley is not running , Even if ultrasonic ranging meets a specific threshold, ramp recognition will not be triggered . such , We'll go through RT-Thread The event set function of realizes the flag bit function , And compared with the method of using global variables as flag bits alone , Undoubtedly played a better role .

 

§04 total junction


One 、 Summary of research work

Because our team has not been in contact with two wheel differential steering system and self balancing system before , Before building the model for the first time, it refers to the construction methods of traditional three wheel model and vertical model , Then, according to the actual commissioning and handover task requirements , Adjust the construction method for many times , Circuit board our team independently designed the integrated board of main control drive operational amplifier , And use it according to actual needs 3D Print and make the relevant part structure , And try innovative ways to build , Adjust the hardware system in time according to the structural characteristics of the vehicle model and the characteristics of software control , The built car model hardware system can well overcome the hardware shortcomings of the original car model , The upper limit of vehicle model is further improved .

Software aspect , Early stage of preparation , Vertical control is difficult , Our team consulted and learned the open source excellent project of smart car forum 、 Complementary filtering scheme for live broadcast training of flight by flight technology 、CS DN Excellent vertical control blog , Cascade is used PID Scheme control attitude and steering , The differential steering closed-loop control system of three wheeled vehicle model also draws lessons from the steering control of vertical vehicle model , The sectional parameters are used according to the actual commissioning and the structural characteristics of the vehicle model 、 Index P etc. PI D Control ideas , Finally, our team passed the debugging of dual vehicle handover task 、 Improvement of camera algorithm 、PI D Parameter setting , Achieved the basic competition task .

After the traditional bare metal debugging can smoothly complete the competition task , Our team used the transplant provided by zhufei Technology RT-Thred Of MM 32F3277 Open source library , By studying relevant training videos 、 Read RT-Thread API Reference manual and relevant technical documents 、 Consulted and collected relevant information RT-Thread Operating system literature and similar engineering codes using the operating system , I understand RT-Thread Basic characteristics of operating system 、 Kernel architecture 、 Thread management 、 Clock management 、 Characteristics and basic operation of synchronization and communication between threads . After that, we refer to the project examples and similar open source projects to migrate the bare metal code project to RT¬Thread Is it in the open source library , According to the characteristics of tricycle and vertical vehicle control system , Give information collection 、 Buzzer 、 human-computer interaction ( Key scan 、 Screen display )、 Tasks such as motion control are assigned different threads and timers , By debugging the thread stack 、 Time slice and priority , All functions of bare metal development are basically realized .

Two 、RT-Thread Summary of its role in the production of intelligent vehicles

According to the structural characteristics and control characteristics of three wheeled vehicle model and vertical vehicle model used in the double vehicle relay group of the 16th National College Student intelligent vehicle competition , Closed loop control of vertical vehicle model PID Multiple control tasks 、 More control quantity , It requires high real-time performance for sensors to obtain attitude, track and other information and attitude settlement , Simultaneous cascade PID It is also necessary to control the task and execute it according to the precise timing , The three wheeled vehicle model has high requirements for the execution frequency of the closed-loop control function , At the same time, the image processing algorithm is required to update the track information in time , Easy closed-loop control , Traditional bare metal development , Only timer interrupts can be used to implement various tasks , Number of timers required by the system 、 Interrupt cycle and priority are set reasonably , This increases the difficulty of bare metal development to a certain extent . So use RT-Tread Operating system development , For intelligent vehicle system, this task is multiple and independent 、 Systems with high requirements for accurate implementation of timing have more advantages .

Used RT-Thread After operating system , Using thread division and timer to perform information collection 、 Attitude settlement 、 Motion control and human-computer interaction ( Key scan in debug mode + The screen displays information )、 Buzzer prompt and other different tasks , According to the actual commissioning , We found that compared with bare metal development , The realization of human-computer interaction task has obvious optimization , Compared with bare metal development , Displaying images and debugging information will occupy some timing resources , This will lead to lag or even confusion in image processing and camera acquisition timing , So that you can't trace normally , But for human-computer interaction tasks and image processing 、 After the motion allocates different threads and timers , Ensure the correctness and accuracy of priority and timing , It is convenient for subsequent parameter setting and program debugging .

According to the actual commissioning , The current research work basically meets the competition task .

3、 ... and 、 Deficiencies of current research work

RT-Thread The main function of the kernel is to manage all hardware resources down , Provide upward for applications A PI Interface and software services , All tasks are managed in the kernel 、 Orderly operation under synchronization and scheduling . And this time the team used RT-Thread Although the thread of sensor acquisition is established , Also used. RT-Thread The timer function to run the data processing function , But yes CPU There is a slight lack of resource scheduling , There are some unreasonable places in the allocation of resources , In thread planning 、 Not proficient in code writing . There are many repetitions and traversals in software design , Yes CPU The clock configuration is not friendly enough . meanwhile ,RT-Thread When applied to intelligent vehicle system , Its advantages in the Internet of things have not been well reflected . Besides , We use RT-Thread Relative emphasis on individual system control of each vehicle , The traditional serial port interrupt is still used to receive data in the way of two vehicle information transmission , Although there is very little content to be transmitted in this project , However, in the case of more data in the future, the optimization of communication is more necessary .

Four 、 Job outlook

The 16th National College Student intelligent car competition was established RT-Thread Special Award , It has attracted the majority of smart car competition contestants to use RT-Thread Carry out intelligent vehicle engineering development . future , With RT¬Thread Used by more players , The engineering of smart cars will be more standardized 、 Unification 、 modularization , At the same time, portability and code readability are also greatly increased .

Modularization of Intelligent Vehicle Engineering , It is beneficial for the contestants to carry out partial evaluation of the project ; The standardization of Engineering , It is helpful for the majority of contestants to understand the code structure of open source project , So as to improve the efficiency of mutual communication and sharing among smart car contestants , Improve the overall level of smart car contestants , Application RT-Thread after , While lowering the entry threshold of smart car competition , It also increases the upper limit of intelligent vehicle operation .

future , With the increasing diversification of intelligent vehicle tasks 、 complicate ,RT-Thread More functions of embedded development system will be excavated by contestants , Applied to smart car competition , Help smart cars run faster and better .

 

ginseng Research literature ※


[1] Wei Lei , Li xingxu , Gaoqin , Zhang Meng . Sensor arrangement scheme and control strategy of intelligent vehicle based on electromagnetic three wheel system [J]. Technology and innovation ,2019(02):21-23.

[2] Zhen Yun Wang . be based on RT-Thread and STM32 Design and implementation of two wheeled self balancing robot based on [D]. North China University ,2016.

[3] RT-Thread. RT-Thread API Reference manual [DB/OL]. https://www.rt-thread.org/document/api/index.html


● Related chart Links :

版权声明:本文为[Zhuo Qing]所创,转载请带上原文链接,感谢。 https://car.inotgo.com/2021/08/20210812230425199y.html