News
News
MCU’s strongest popular science summary [recommended collection] (2)
2022-03-17 230

6

Microcontroller programming


 

There is a big difference between MCU program writing and PC program writing. Although C-based MCU development tools are becoming more and more popular, for designers who have efficient program code and like to use assembly, assembly language is still the most concise and effective programming language.


For MCU programming, the basic framework can be said to be roughly the same, which is generally divided into three parts: the initialization part (this is the biggest difference between MCU programming and PC), the main program loop body and the interrupt handler, which are explained as follows:
  1. Initialization:For the design of all MCU programs, initialization is the most basic and important step, which generally includes the following:
  Mask all interrupts and initialize the stack pointer:The initialization part generally does not want any interrupts to occur.  
  Clear the system's RAM area and display Memory:Although sometimes it may not be completely necessary, from the perspective of reliability and consistency, especially to prevent unexpected errors, it is recommended to develop good programming habits.  
  Initialization of IO port:According to the application requirements of the project, set the input and output mode of the relevant IO port. For the input port, you need to set its pull-up or pull-down resistor; for the output port, you must set its initial level output to prevent unnecessary errors.  
  Interrupt settings:For all interrupt sources that need to be used in the project, they should be turned on and the trigger conditions for the interrupt should be set, while redundant interrupts that are not used must be turned off.  
  Initialization of other functional modules:For all peripheral function modules of the MCU that need to be used, the corresponding settings must be made according to the requirements of the project application. For example, for UART communication, the Baud Rate, data length, verification method, and Stop Bit length need to be set. For the Programmer Timer, its clock source, frequency division number, and Reload Data must be set.  
  Initialization of parameters:After completing the initialization of the MCU hardware and resources, the next step is to initialize some variables and data used in the program. The initialization of this part needs to be designed according to the specific project and the overall arrangement of the program. For some applications that use EEPROM to save project prefabricated data, it is recommended to copy the relevant data to the RAM of the MCU during initialization to improve the program's access speed to data and reduce the power consumption of the system (in principle, accessing external EEPROM will increase the power consumption of the power supply).  
  2. Main program loop body:Most MCUs run continuously for a long time, so their main program bodies are basically designed in a loop. For applications with multiple working modes, there may be multiple loop bodies, which are converted through status flags. For the main program body, the following modules are generally arranged:
  Calculation procedure:Calculation programs are generally time-consuming, so we are firmly opposed to processing them in any interrupt, especially multiplication and division operations.  
Processing programs with low or no real-time requirements;
 
  Show transfer procedure:Mainly aimed at applications with external LED and LCD Drivers.  
  3. Interrupt handler:Interrupt programs are mainly used to handle tasks and events with high real-time requirements, such as detection of external sudden signals, detection and processing of buttons, timing counting, LED display scanning, etc.  
Under normal circumstances, the interrupt program should keep the code as concise and short as possible. For functions that do not need to be processed in real time, the trigger flag can be set in the interrupt, and then the main program will perform specific transactions. This is very important, especially for low-power, low-speed MCUs, which must ensure timely response to all interrupts.  
  4. For the arrangement of different task bodies, different MCUs have different processing methods:  
 For example, for low-speed, low-power MCU (Fosc=32768Hz) applications, considering that such projects are handheld devices and use ordinary LCD displays, the response to key presses and display response requires high real-time performance, so timed interrupts are generally used to process key presses. Actions and data display; for high-speed MCUs, such as Fosc>1MHz applications, since the MCU has enough time to execute the main program loop body at this time, it can only set various trigger flags in the corresponding interrupts and put all tasks in the main program body for execution.  
  5. In MCU programming, one thing that needs special attention is:

It is necessary to prevent the same variable or data from being accessed or set in the interrupt and main program bodies at the same time. An effective prevention method is to arrange the processing of such data in a module, and determine whether to perform related operations on the data by judging the trigger flag; in other program bodies (mainly interrupts), only set trigger flags where the data needs to be processed. --This ensures that data execution is predictable and unique.

7

Engineer's summary of microcontroller programming



 

1、Develop a good habit of summarizing. Summarizing is not only a summary of your own learning, but also a review and deepening of the learning process. It can also avoid making mistakes the second time.


  2、Before writing a program, you must first have a familiar understanding of the project, be aware of it, and outline a general framework. It is very important to carefully consider how to lay out and what is the most reasonable layout. It is necessary to analyze which module to do first, the specific steps of this module, how to name each function, the connection with other modules, etc. It’s a good idea to get a piece of paper and jot down important processes.  
  3、For modular programming in C language, you must first divide each module, program module by module, determine a sequence, follow the sequence, and then write the next module after the module is successful. For header files, write the module's header file after the module is written.  
  4、Do not ignore warnings when they appear. It means that there must be something unreasonable about the program. It is necessary to understand its source and find a solution. Be specific when looking for sources. You can search the Internet for information in this area, or ask others for advice. For example, the main function in another project was actually added to this project. There are actually duplicate function names. There are also reasons to analyze the experimental phenomena and progress step by step. There was also the wrong interface selected when defining the port. Sometimes, it’s good to take a break and think about it if you really can’t solve it. No matter how simple it is, you should pay attention to it, as there may be mistakes.   
In the development of microcontroller applications, problems such as code usage efficiency, anti-interference performance and reliability of microcontrollers are still troubled. Now we summarize several basic skills that should be mastered in the development of microcontroller.        
         

8

Microcontroller development skills


   
       

1.How to reduce bugs in programs

Regarding how to reduce program bugs, you should first consider the following out-of-range management parameters that should be considered during system operation.


  • Physical parameters: These parameters are mainly input parameters of the system, which include excitation parameters, operating parameters during acquisition processing and result parameters at the end of processing.

  • Resource parameters: These parameters are mainly the resources of circuits, devices, and functional units in the system, such as memory capacity, storage unit length, and stacking depth.

  • Application parameters: These application parameters often appear as application conditions of some microcontrollers and functional units. Process parameters: refers to the parameters that change in an orderly manner during system operation.


2.How to improve the efficiency of C language programming code

Using C language for microcontroller programming is an inevitable trend in the development and application of microcontrollers. If you want to achieve maximum efficiency when programming in C, it is best to be familiar with the C compiler you are using. First test the number of lines of assembly language statements corresponding to each C language compilation, so that you can clearly know the efficiency. When programming in the future, use the statement with the highest compilation efficiency. Each C compiler will have certain differences, so the compilation efficiency will also be different. The code length and execution time of an excellent C compiler for embedded systems are only 5-20% longer than the same function written in assembly language.


For complex projects with tight development time, C language can be used, but the prerequisite is that you are very familiar with the C language and C compiler of the MCU system. Pay special attention to the data types and algorithms supported by the C compilation system. Although C language is the most common high-level language, different MCU manufacturers have different C language compilation systems, especially in the operation of some special function modules. Therefore, if you do not understand these features, there will be many problems during debugging, which will lead to lower execution efficiency than assembly language.


       3.How to solve the anti-interference problem of microcontrollerThe most effective way to prevent interference is to remove the interference source and block the interference path, but it is often difficult to do so, so we can only see whether the anti-interference ability of the microcontroller is strong enough. While improving the anti-interference ability of hardware systems, software anti-interference is receiving more and more attention because of its flexible design, saving of hardware resources, and good reliability.  
The most common phenomenon of microcontroller interference is reset. As for the program running away, software traps and watchdogs can actually be used to bring the program back to the reset state. Therefore, the most important thing for microcontroller software to resist interference is to handle the reset state.  
Generally, microcontrollers will have some flag registers that can be used to determine the cause of reset; in addition, you can also bury some flags in RAM yourself. Each time the program is reset, different reset causes can be determined by judging these flags; you can also jump directly to the corresponding program based on different flags. This allows the program to run continuously, and the user will not notice that the program has been reset when using it.  
       4.How to test the reliability of microcontroller systemWhen a microcontroller system design is completed, there will be different test items and methods for different microcontroller system products, but some must be tested:
 
  • Test the completeness of the microcontroller software function
  • Power on and power off test
  • Aging test
  • Tests such as ESD and EFT

Sometimes, we can also simulate the damage that may occur during human use. For example, deliberately rub the contact port of the microcontroller system with the human body or clothing fabric to test the anti-static ability. Use a high-power electric drill to work close to the microcontroller system to test the ability to resist electromagnetic interference.  
In summary, single-chip microcomputer has become an important aspect of computer development and application. The important significance of single-chip microcomputer application is that it fundamentally changes the traditional control system design ideas and design methods.  
Most functions that previously had to be implemented by analog circuits or digital circuits can now be implemented through software methods using microcontrollers. This kind of control technology in which software replaces hardware is also called micro-control technology, which is a revolution in traditional control technology.  
In addition, during the development and application process, we must master skills and improve efficiency so that it can be used for a wider range of purposes.  
         

9

Chip operation summary


 
 

The operations on the chip are mainly operations on the registers in the chip. The registers in the chip have their own unique addresses mapped on the memory, which is the operation on the corresponding address. When looking at the chip, first look at the timing diagram, then understand the corresponding registers, understand how they operate, define the required ports (which can be identified by the program), and write write operation procedures and read operation procedures.


How to write data into the chip, how to read data, and which port to input or read through (the most important thing).  
When connecting chips through a bus, you must first understand the protocol of the bus. The chip connected to the I2C bus mainly controls the chip through this bus.  
  1、One 74hc595 in the lattice is used for column selection, and the other two are used for color selection. The lattice is equivalent to a collection of diodes,
Only when one end is given a high level and the other end is given a low level can the diode light up. It's just that when one end is selected differently, different colors will light up.  
Selection of timer working mode: The high four bits set the timer T1, and the low four bits set T0. Then the last two digits of each mode set the working mode. When setting two timers, be careful to use or (|). When using interrupts, pay attention to clearing the ones that should be cleared after entering the interrupt.  
  2、Serial port transceiver: The baud rate is generally set in mode 2 (automatic reloading to initial value). Because different devices have different data processing capabilities, setting the baud rate is mainly to take care of low-speed devices and to communicate with each other. The interrupt flag bit must be cleared by software. When setting the serial port interrupt, no matter which one is generated by sending or receiving, it can enter the interrupt function, so pay attention to setting the interrupt function. (Self-feeling generally sets a function, as a host computer or a slave computer).  
If you use an interrupt to send, you have to figure out how to enter the interrupt for the first time, so you have to send it once first, and then you can enter the interrupt. Only one byte can be sent at a time, and the next bit can only be sent after TI is set.  
  3、Pcf8591ad conversion has four channels of input. When reading pcf8591, which channel is selected, the voltage input by that channel is read. The converted data is stored in the chip and then read out. When reading, first write the address of the chip, then write the sub-address of the device (0x40|channel number), and then the read data.  
  4、Da conversion is to first write the device address into the chip, then write the sub-address (0x40), and then write the digital quantity to be converted. Device address chip information is introduced.  
  5、For the LCD display, after the data is written and displayed, it will always be displayed without continuous refresh. If you want to change it, you can only re-enter it.  
  6、For the ds1302 clock chip, when reading data, the first data is read at the falling edge of the eighth clock when writing data, and then prepares for the next output. Pay attention to the writing method of the program and the location of the return value.  
  7、In Ds1302, first specify the register and then write data to it. The register on the chip data indicates the address. (I still don’t quite understand the write protection program. Isn’t there always writing? Why is the write protection still turned on?)
(According to the previous hero, you can set a flag after the initialization time. If there is this flag, there is no need to initialize the time. However, if the power is turned off, the MCU's RAM cannot save this flag, so you can use the DS1302's RAM to save the flag, and read the flag after powering on. I am also a beginner, and I plan to use DS1302 recently. I don't know if this is correct, and I haven't implemented it yet. Please share more)
  8、It is best to write down the initialization in case you forget it later. Sometimes pay attention to whether the lowest bit or the highest bit is operated first when reading or writing, which can be judged according to the timing diagram.  
  9、For infrared transceiver, when receiving, it determines whether it is a high level or a low level based on the time between two falling edges. When writing a program, first use a timer to determine the time, save it, and then convert it into binary (read more about how to write this program, it is very good).  
  10、Stepper motor: Mainly used for switching. The torque of the stepper motor decreases as the rotational speed increases. It is mainly used for automatic feeding of parts processed on machine tools. It can also be used in control places with higher precision.  
Stepper motor is an open-loop control element stepper motor device that converts electrical pulse signals into angular displacement or linear displacement. Under non-overload conditions, the motor's speed and stop position only depend on the frequency and number of pulses of the pulse signal, and are not affected by load changes. When the stepper driver receives a pulse signal, it drives the stepper motor to rotate in the set direction at a fixed angle, called the "step angle". Its rotation runs step by step at a fixed angle. The angular displacement can be controlled by controlling the number of pulses to achieve accurate positioning; at the same time, the speed and acceleration of the motor rotation can be controlled by controlling the pulse frequency to achieve speed regulation.  
  11、Servo motor: (servo motor) refers to the engine that controls the operation of mechanical components in the servo system. It is an indirect transmission device that assists the motor. Servo motors can control speed and position accuracy very accurately, and can convert voltage signals into torque and rotational speed to drive control objects. The rotor speed of the servo motor is controlled by the input signal and can respond quickly. In the automatic control system, it is used as an actuator and has the characteristics of small electromechanical time constant, high linearity, starting voltage, etc. It can convert the received electrical signal into the angular displacement or angular velocity output on the motor shaft. They are divided into two categories: DC and AC servo motors. Their main feature is that there is no rotation when the signal voltage is zero, and the rotational speed decreases at a constant speed as the torque increases. DC motor: Large range, all on small cars.


Disclaimer: This article is reproduced from "International Electronic Business Information". This article only represents the author's personal views and does not represent the views of Sacco Micro and the industry. It is only for reprinting and sharing and supports the protection of intellectual property rights. Please indicate the original source and author for reprinting. If there is any infringement, please contact us to delete it.

Company phone number: +86-0755-83044319
Fax/FAX: +86-0755-83975897
Email: 1615456225@qq.com
QQ: 3518641314 Manager Li

QQ: 332496225 Manager Qiu

Address: Room 809, Building C, Zhantao Technology Building, No. 1079 Minzhi Avenue, Longhua New District, Shenzhen

whatsapp

Service Hotline

tel: +86 755 83044319

WhatsApp

Whatsapp:+8618073002950