Comprehensive Guide to Microcontroller Units

Comprehensive Guide to Microcontroller Units
MCU stands for Microcontroller Unit, which is commonly known as a single-chip microcontroller. It reduces the CPU’s frequency and specifications appropriately and integrates memory, counters, USB, A/D conversion, UART, PLC, DMA, and other peripheral interfaces, even LCD driver circuits, into a single chip, forming a chip-level computer. This allows for different combinations of control for various applications, such as mobile phones, PC peripherals, remote controls, and even automotive electronics and industrial applications like stepper motors and robotic arms.
Comprehensive Guide to Microcontroller UnitsClassification and Applications of Microcontrollers
MCUs can be categorized into non-chip ROM type and chip ROM type based on their memory type. For non-chip ROM type chips, external EPROM must be connected for use (typical example: 8031); chip ROM type chips are further divided into internal EPROM type (typical chip: 87C51), MASK internal ROM type (typical chip: 8051), and internal Flash type (typical chip: 89C51).
Based on usage, they can be divided into general-purpose and special-purpose; according to the width of the data bus and the length of data bytes that can be processed at one time, they can be categorized into 8, 16, and 32-bit MCUs.
Currently, the most widely used application market for MCUs in China is the consumer electronics sector, followed by the industrial sector and automotive electronics market. Consumer electronics include home appliances, televisions, game consoles, and audio-visual systems. The industrial sector includes smart homes, automation, medical applications, and new energy generation and distribution. The automotive sector includes powertrains and safety control systems.
Comprehensive Guide to Microcontroller Units
Basic Functions of Microcontrollers
For the vast majority of MCUs, the following functions are the most common and basic. The way they are described may vary for different MCUs, but they are essentially the same:
1. Timer: There are many types of timers, but they can be summarized into two main categories: fixed interval timers, which have a timing interval set by the system that cannot be controlled by user programs, and the system only provides a few fixed intervals for user programs to select from, such as 32Hz, 16Hz, 8Hz, etc. This type of timer is common in 4-bit MCUs and can be used to implement clock and timing functions.
The other type is the Programmable Timer, which, as the name suggests, allows the user program to control the timing interval. Control methods include selecting the clock source, prescale selection, and preset value settings. Some MCUs may have all three features, while others may have one or two. This type of timer is very flexible in application, and its actual use can vary widely. The most common application is to implement PWM output.
Since the clock source can be freely selected, this type of timer is generally combined with an Event Counter.
2. I/O Ports: Every MCU has a certain number of I/O ports. Without I/O ports, the MCU loses its communication channels with the outside world. Based on the configurability of I/O ports, they can be divided into the following types:
Pure input or output ports: These I/O ports are determined by the MCU hardware design and can only be either input or output; they cannot be set in real-time by software.
Direct read/write I/O ports: For example, the I/O ports of MCS-51 belong to this type. When executing the read I/O port instruction, it is an input port; when executing the write I/O port instruction, it automatically becomes an output port.
Programmable direction input/output ports: The input or output of these ports is set by the program according to actual needs, making them quite flexible for applications such as bus-level applications like I2C bus, various LCD, and LED driver control buses.
When using I/O ports, it is crucial to remember: for input ports, there must be a clear level signal to ensure it is not floating (this can be achieved by adding pull-up or pull-down resistors); for output ports, the output state levels must consider their external connections to ensure that there is no pull current or sink current in standby or static states.
3. External Interrupts: External interrupts are also a basic function possessed by the vast majority of MCUs, generally used for real-time signal triggering, data sampling, and status detection. Interrupts can be triggered by rising edges, falling edges, or level triggering. External interrupts are generally implemented through input ports; if they are I/O ports, the interrupt function will only be enabled when set as input; if they are output ports, the external interrupt function will be automatically disabled (some exceptions exist in ATMEL’s ATiny series, where output ports can also trigger interrupt functions). Applications of external interrupts include:
Detection of external trigger signals: One type is based on real-time requirements, such as controlling thyristors or detecting sporadic signals, while the other type is for power-saving needs.
Measuring signal frequency: To ensure that signals are not missed, external interrupts are the ideal choice.
Data decoding: In remote control applications, to reduce design costs, it is often necessary to use software methods to decode various encoded data, such as Manchester and PWM encoding.
Button detection and system wake-up: For MCUs that enter sleep mode, external interrupts are generally required to wake them up. The most basic form is through buttons, where the action of pressing a button causes a change in level.
4. Communication Interfaces: The communication interfaces provided by MCUs generally include SPI interfaces, UART, I2C interfaces, etc., which are described as follows:
SPI Interface: This type of interface is a basic communication method provided by most MCUs, where data transmission is controlled by a synchronous clock. Signals include: SDI (Serial Data Input), SDO (Serial Data Output), SCLK (Serial Clock), and Ready signal; in some cases, there may be no Ready signal; this type of interface can operate in Master or Slave mode, meaning it depends on who provides the clock signal—the one providing the clock is the Master, and the other is the Slave.
UART (Universal Asynchronous Receive Transmit): This is the most basic asynchronous transmission interface, with only two signal lines, Rx and Tx. The basic data format is: Start Bit + Data Bit (7-bits/8-bits) + Parity Bit (Even, Odd, or None) + Stop Bit (1~2 Bits). The time taken for one data bit is called Baud Rate.
For most MCUs, the length of data bits, data parity methods (odd parity, even parity, or no parity), the length of stop bits, and Baud Rate can be flexibly set through programming. This interface is most commonly used for data communication with the serial port of a PC.
I2C Interface: I2C is a data transmission protocol developed by Philips, which also uses two signals: SDAT (Serial Data Input/Output) and SCLK (Serial Clock). Its greatest advantage is that multiple devices can be connected on this bus, identified and accessed via addresses; one of the biggest benefits of the I2C bus is that it is very convenient to implement via software through I/O ports, and the data transmission rate is entirely controlled by SCLK, allowing for flexible speeds, unlike UART interfaces, which have strict rate requirements.
5. Watchdog Timer: The Watchdog is also a basic configuration for most MCUs (some 4-bit MCUs may lack this function). Most MCUs allow the program to reset the Watchdog but not disable it (some are set during the program burning process, such as Microchip’s PIC series MCUs), while others may determine whether it is enabled through specific methods, such as Samsung’s KS57 series, where accessing the Watchdog register automatically enables it and cannot be turned off. Generally, the reset time for the Watchdog can be set through programming. The most basic application of the Watchdog is to provide a self-recovery capability for the MCU in case of unexpected failures leading to a freeze.
Comprehensive Guide to Microcontroller Units
Major Microcontroller Manufacturers Worldwide
Below is a list of major microcontroller manufacturers (there may be some omissions), ranked in no particular order.
North America and Europe
1. Freescale + NXP: Netherlands, primarily provides 16-bit and 32-bit MCUs. Application areas: automotive electronics, LED and general lighting, healthcare, multimedia integration, home appliances and power tools, building automation motor control, power and power converters, energy and smart grids, automation, computer and communication infrastructure.
2. Microchip + Atmel: United States, primarily provides 16-bit and 32-bit MCUs. Application areas: automotive electronics, industrial use, motor control, automotive, building automation, home appliances, home entertainment, industrial automation, lighting, IoT, smart energy, mobile electronic devices, and computer peripherals.
3. Cypress + Spansion: United States, primarily provides 8-bit, 16-bit, and 32-bit MCUs. Application areas: automotive electronics, home appliances, medical, consumer electronics, communications and telecommunications, industrial, and wireless.
4. ADI (Analog Devices): United States, primarily provides 8-bit, 16-bit, and 32-bit MCUs. Application areas: aerospace and defense, automotive applications, building technology, communications, consumer electronics, energy, healthcare, instrumentation and measurement, motors, industrial automation, and security.
5. Infineon: Germany, primarily provides 16-bit and 32-bit MCUs. Application areas: automotive electronics, consumer electronics, engineering, commercial and agricultural vehicles, data processing, electric transport, industrial applications, medical devices, mobile devices, motor control and drive, power, solutions for motorcycles, electric bicycles, and small electric vehicles, smart grid, lighting, solar system solutions, and wind energy system solutions.
6. ST Microelectronics: Italy/France, primarily provides 32-bit MCUs. Application areas: LED and general lighting, transportation, healthcare, multimedia integration, home appliances and power tools, building automation motor control, power and power converters, energy and smart grids, automation, computer and communication infrastructure.
7. Qualcomm: United States, primarily provides 16-bit and 32-bit MCUs. Application areas: smartphones, tablets, wireless modems.
8. Texas Instruments: United States, primarily provides 16-bit and 32-bit MCUs. Application areas: automotive electronics, consumer electronics, medical devices, mobile devices, and communications.
9. Maxim: United States, primarily provides 32-bit MCUs. Application areas: automotive electronics, consumer electronics, industrial applications, and security.
East Asia
1. Renesas: Japan, primarily provides 16-bit and 32-bit MCUs. Application areas: computers and peripherals, consumer electronics, health care electronics, automotive electronics, industrial, and communications.
2. Toshiba: Japan, primarily provides 16-bit and 32-bit MCUs. Application areas: automotive electronics, industrial use, motor control, wireless communication, mobile phones, computers and peripheral devices, imaging and audio-visual, consumer (home appliances), LED lighting, security, power management, and entertainment devices.
3. Fujitsu: Japan, primarily provides 32-bit MCUs. Application areas: automotive, medical, machinery, and home appliances.
4. Samsung Electronics: South Korea, primarily provides 16-bit and 32-bit MCUs. Application areas: automotive electronics, industrial use, motor control, automotive, building automation, home appliances, home entertainment, industrial automation, lighting, IoT, smart energy, mobile electronic devices, and computer peripherals.
China
▍ Mainland China
1. Sigma Microelectronics: Primarily provides 32-bit MCUs, application areas: telecommunications, manufacturing, energy, transportation, power, etc.
2. Zhuhai Obit: Primarily provides 32-bit MCUs, application areas: aerospace: star and arrow stations, aircraft; high-end industrial control: embedded computers; ship control, industrial control, power equipment, environmental monitoring.
3. GigaDevice: Primarily provides 32-bit MCUs, application areas: industrial automation, human-machine interface, motor control, security monitoring, smart home, and IoT.
4. Shengxi Microelectronics: Primarily provides 8-bit and 32-bit MCUs, application areas: small appliances, consumer electronics, remote controls, mice, lithium batteries, digital products, automotive electronics, medical instruments, measurement, toys, industrial control, smart home, and security.
5. Chipsea Technology: Primarily provides 16 and 32-bit MCUs, application areas: instrumentation, IoT, consumer electronics, home appliances, and automotive electronics.
6. United Microelectronics: Primarily provides 8-bit and 16-bit MCUs, application areas: consumer electronics, white goods, industrial control, communication equipment, automotive electronics, and computers.
7. Zhuhai Jianrong: Primarily provides 8-bit MCUs, application areas: home appliances and mobile power supplies.
8. Juchip Technology: Primarily provides 8-bit to 32-bit MCUs, application areas: tablets, smart homes, multimedia, Bluetooth, and Wi-Fi audio.
9. Aisiko Microelectronics: Primarily provides 8-bit and 16-bit MCUs, application areas: consumer chips, communication chips, and information chips for home appliances.
10. Huaxin Microelectronics: Primarily provides 8-bit and 4-bit MCUs, application areas: satellite receivers, mobile phone chargers, perpetual calendars, and multi-functional remote controls.
11. Shanghai Beiling (Huada Semiconductor Holdings): Primarily provides 8-bit, 16-bit, and 32-bit MCUs, application areas: computer peripherals, HDTV, power management, small appliances, and digital appliances.
12. Haier Integrated Circuits: Primarily provides 14-bit, 15-bit, and 16-bit MCUs, application areas: consumer electronics, automotive electronics, industrial, and smart instruments.
13. Beijing Junzheng: Primarily provides 32-bit MCUs, application areas: wearable devices, IoT, smart home appliances, automotive, consumer electronics, and tablets.
14. Zhongwei Semiconductor: Primarily provides 8-bit MCUs, application areas: smart home appliances, automotive electronics, security monitoring, LED lighting and landscaping, smart toys, smart home, and consumer electronics.
15. Shenzhou Longxin Integrated Circuits: Primarily provides 32-bit MCUs, application areas: power monitoring, smart grid, industrial digital control, IoT, smart home, and data monitoring.
16. Unisoc Microelectronics: Primarily provides 8-bit and 16-bit MCUs, application areas: smart home appliances.
17. Times Microelectronics: Primarily provides 32-bit MCUs, application areas: automotive navigation, traffic monitoring, fishing boat supervision, and power telecommunication networks.
18. China Resources Silicon Microelectronics (subsidiary of China Resources Micro): Primarily provides 8-bit and 16-bit MCUs, application areas: consumer electronics, industrial control, and home appliances.
19. Guoxin Technology: Primarily provides 32-bit MCUs, application areas: information security, office automation, communication networks, and information security.
20. Zhongtian Micro: Primarily provides 32-bit MCUs, application areas: smartphones, digital televisions, set-top boxes, automotive electronics, GPS, e-readers, and printers.
21. China Resources Microelectronics: Primarily provides 8-bit and 16-bit MCUs, application areas: home appliances, consumer electronics, and general control circuits for industrial automation.
22. Zhongying Electronics: Primarily provides 4-bit, 8-bit, 16-bit, and 32-bit MCUs, application areas: home appliances and motors.
23. Lingdong Microelectronics: Primarily provides 32-bit MCUs, application areas: motor control, Bluetooth control, high-definition display, wireless charging, drones, micro printers, smart tags, electronic cigarettes, and LED dot matrix screens.
24. Xintai Technology: Primarily provides 32-bit MCUs, application areas: lighting, IoT, etc.
25. Neusoft Carrier: Primarily provides 8-bit and 32-bit MCUs, application areas: home appliances, smart homes, instrumentation, LCD panel controllers, and industrial control.
26. Betley: Primarily provides 32-bit MCUs, application areas: smart homes, industrial control, and consumer product fields.
27. Shengquan Technology: Primarily provides 8-bit MCUs, application areas: automotive, education, industrial control, and medical for small and medium-sized display panels.
28. Hangshun Chip: Primarily provides 8-bit and 32-bit MCUs, application areas: automotive and IoT.
29. Fudan Microelectronics: Primarily provides 16-bit and 32-bit MCUs, application areas: smart meters and smart locks.
30. Huada Semiconductor: Primarily provides 8-bit, 16-bit, and 32-bit MCUs, application areas: industrial control, smart manufacturing, smart living, and IoT.
▍ Taiwan Region
1. Holtek: Primarily provides 8-bit MCUs. Application areas: communications, industrial control, information home appliances, and voice.
2. Nuvoton Technology: Primarily provides 8-bit and 32-bit MCUs. Application areas: consumer electronics, LED lighting, etc.
3. Sunplus Technology: Primarily provides 8-bit and 16-bit MCUs. Application areas: home audio and video.
4. Zhongying Electronics: Primarily provides 4-bit and 8-bit MCUs. Application areas: chargers, mobile power supplies, home appliances, and industrial control.
5. Sonix Technology: Primarily provides 8-bit and 32-bit MCUs. Application areas: remote controls, smart chargers, large and small systems, electronic scales, ear thermometers, blood pressure monitors, tire pressure monitors, and various measurement and health devices.
6. Winbond Electronics: Primarily provides 8-bit and 16-bit MCUs. Application areas: automotive electronics, industrial electronics, networks, computers, consumer electronics, and IoT.
7. Ten Speed Technology: Primarily provides 4-bit, 8-bit, and 51-bit MCUs. Application areas: remote controls and small appliances.
8. Yuhua Microelectronics: Primarily provides 4-bit and 8-bit MCUs. Application areas: recording integrated circuit products, consumer electronics, and home products.
9. Yingguang Technology Microcontroller: Primarily provides 4-bit and 8-bit MCUs. Application areas: machinery, automation, home appliances, and robotics.
10. Yilong Electronics: Primarily provides 8-bit and 16-bit MCUs. Application areas: consumer electronics, computers, and smartphones.
Comprehensive Guide to Microcontroller Units
Learning Tips for Microcontrollers
For any MCU, the basic principles and functions are quite similar. What differs are the configurations and quantities of peripheral functional modules, instruction systems, etc.
Regarding the instruction system, although they may seem vastly different in form, they essentially represent different symbols, and the meanings they denote, the functions they need to accomplish, and the addressing methods are generally similar.
To understand an MCU, the first thing to know is its ROM space, RAM space, number of I/O ports, number of timers and timing methods, provided peripheral functional modules (Peripheral Circuit), interrupt sources, operating voltage, and power consumption, etc.
After understanding these MCU features, the next step is to compare the functions of the selected MCU with the requirements of the actual project development, clarifying which resources are needed and which are not.
For functions needed in the project that the selected MCU does not provide, it is essential to thoroughly understand the relevant MCU documentation to seek indirect methods to achieve them. For example, if the project requires communication with a PC COM port but the selected MCU does not provide a UART port, an external interrupt method can be considered.
For resources required in project development, it is necessary to carefully understand and read the manuals, while unnecessary functional modules can be ignored or skimmed through. In MCU learning, application is key and the primary goal.
Once the relevant functions of the MCU are clarified, programming can commence.
For beginners or designers using this MCU for the first time, many ambiguities may arise regarding the MCU’s functional descriptions. These issues can be resolved in two ways: one is to write special validation programs to understand the functions as described in the documentation; the other can be to temporarily ignore them and write the microcontroller program according to current understanding, modifying and refining it during debugging. The first method is suitable for projects with more relaxed timelines and for beginners, while the second method is more appropriate for those with certain MCU development experience or for projects with tighter schedules.
Do not spend excessive time trying to understand the instruction system. The instruction system is merely a logical description symbol; it is sufficient to refer to the relevant instructions based on your logic and the program’s logic requirements during programming. Moreover, as programming progresses, familiarity with the instruction system will naturally increase, and it may even be memorized unconsciously.
Comprehensive Guide to Microcontroller Units
Programming for Microcontrollers
Programming for MCUs differs significantly from programming for PCs. Although MCU development tools based on C are becoming increasingly popular, for an efficient program code, assembly language is still the most concise and effective programming language for designers who prefer it.
In MCU programming, the basic framework is generally consistent and can be divided into three main parts: initialization part (this is the biggest difference between MCU programming and PC programming), main program loop, and interrupt handling program, as described below:
1. Initialization: Initialization is the most basic and crucial step in all MCU program designs, generally including the following:
Mask all interrupts and initialize the stack pointer: The initialization part generally does not wish for any interrupts to occur.
Clear the system’s RAM area and display memory: Although it may not always be necessary, from the perspective of reliability and consistency, especially to prevent unexpected errors, it is advisable to develop good programming habits.
Initialize I/O ports: Set the relevant I/O ports’ input/output methods according to the project’s application requirements. For input ports, pull-up or pull-down resistors must be set; for output ports, their initial level output must be set to prevent unnecessary errors.
Set up interrupts: For all interrupt sources needed in the project, they should be enabled and the trigger conditions for the interrupts should be set. For unnecessary excess interrupts, they must be disabled.
Initialize other functional modules: For all peripheral functional modules of the MCU that need to be used, corresponding settings must be made according to the project’s application requirements. For example, for UART communication, Baud Rate, data length, parity method, and Stop Bit length need to be set, while for Programmable Timer, its clock source, prescale, and Reload Data must be set.
Parameter initialization: After completing the initialization of the MCU’s hardware and resources, the next step is to initialize some variables and data used in the program. This part of the initialization needs to be designed based on the specific project and overall program arrangements. For applications that use EEPROM to store preset numbers, it is advisable to copy the relevant data to the MCU’s RAM during initialization to improve the program’s data access speed while reducing system power consumption (in principle, accessing external EEPROM will increase power consumption).
2. Main program loop: Most MCUs operate continuously for extended periods, so their main program body is generally designed in a loop format. For applications with multiple operating modes, there may be multiple loop bodies, which transition between each other using status flags. The main program body generally arranges the following modules:
Calculation programs: Calculation programs are generally time-consuming, so it is strongly advised not to handle them in any interrupts, especially multiplication and division operations.
Programs that do not have high real-time requirements or do not require real-time processing;
Display transmission programs: Mainly for applications with external LED and LCD drivers.
3. Interrupt handling programs: Interrupt programs are primarily used to handle tasks and events that require high real-time responsiveness, such as detection of external sporadic signals, button detection and handling, timing counts, LED display scanning, etc.
Generally, interrupt programs should be kept as concise and small as possible. For functions that do not need to be processed in real-time, a flag can be set in the interrupt, and the main program can execute the specific tasks—this is very important, especially for low-power, low-speed MCUs, where timely response to all interrupts must be guaranteed.
4. Different task arrangements may vary based on different MCUs:
For example, for low-speed, low-power MCUs (Fosc=32768Hz) applications, considering that these projects are handheld devices using standard LCD displays, the requirements for button reactions and display reactions are quite high, so a timed interrupt is generally used to handle button actions and data displays; whereas for high-speed MCUs, such as those with Fosc > 1MHz, there is ample time to execute the main program loop, so various trigger flags can be set only in relevant interrupts, with all tasks executed in the main program body.
5. In MCU program design, it is crucial to avoid: Simultaneously accessing or setting the same variable or data in both the interrupt and main program body. An effective prevention method is to arrange the processing of such data in one module and determine whether to execute the relevant operations based on trigger flags. In other program bodies (mainly interrupts), only the trigger flags for data processing need to be set. This ensures that data execution is predictable and unique.
Comprehensive Guide to Microcontroller Units
Engineers’ Summary on Microcontroller Programming
1. Develop a good habit of summarizing; summarization is not only a review of your learning but also deepens the learning process and helps avoid making the same mistakes twice.
2. Before writing a program, you need to have a good understanding of the project, so you know what to expect and can outline a rough framework. Carefully consider how to layout the program and what the most reasonable layout would be. This step is crucial. Analyze which module to work on first, detailing the steps for that module, how to name various functions, and how they connect with other modules. It is best to jot down important processes on paper.
3. For modular programming in C language, separate various modules and program one at a time, establishing a sequence. After one module is successfully written, proceed to the next. For header files, write them only after the corresponding module is complete.
4. Do not ignore warnings; they indicate that there are unreasonable aspects in the program. Understand their origins and find solutions. When tracing sources, be targeted; search online for relevant information or consult others. For example, mistakenly including the main function from another project in this one or having duplicate function names. Analyze reasons based on experimental phenomena, layer by layer. Sometimes, if you truly cannot resolve an issue, taking a break can be beneficial. Even for the simplest parts, be cautious, as mistakes can happen.
In microcontroller application development, issues related to code efficiency, anti-interference capabilities, and reliability continue to be troublesome. Below are several basic skills that should be mastered in microcontroller development.
Comprehensive Guide to Microcontroller Units
Microcontroller Development Skills
1. How to Reduce Bugs in Programs
To reduce bugs in programs, consider the following parameters that should be managed during system operation:
  • Physical parameters: These parameters are mainly the system’s input parameters, including excitation parameters, operational parameters during processing, and result parameters after processing.

  • Resource parameters: These parameters mainly refer to the resources in the system’s circuits, devices, and functional units, such as memory capacity, storage unit length, and stack depth.

  • Application parameters: These application parameters often manifest as application conditions for some microcontrollers and functional units. Process parameters: refer to orderly changing parameters during system operation.

2. How to Improve the Efficiency of C Language Programming Code
Using C language for microcontroller program design is an inevitable trend in microcontroller development and application. To achieve the highest efficiency when using C programming, it is best to familiarize yourself with the C compiler being used. First, experiment with the number of assembly language statement lines corresponding to each C language statement after compilation; this will clarify efficiency. In future programming, use the statements with the highest compilation efficiency. Each C compiler will have certain differences, so the compilation efficiency will also vary. Excellent embedded system C compilers have code lengths and execution times that are only 5-20% longer than those written in assembly language for the same functionality.
For complex projects with tight development timelines, C language can be employed, provided that you are very familiar with the MCU system’s C language and C compiler, especially the data types and algorithms that the C compilation system can support. Although C language is the most common high-level language, different MCU manufacturers have variations in their C language compilation systems, particularly in operations of some special functional modules. Therefore, if you are unaware of these characteristics, debugging will lead to many issues, potentially resulting in lower execution efficiency than assembly language.
3. How to Address Microcontroller Anti-Interference Issues
The most effective way to prevent interference is to eliminate the source of interference and interrupt the interference path, but this is often difficult to achieve. Thus, the focus shifts to whether the microcontroller’s anti-interference capability is strong enough. While enhancing the hardware system’s anti-interference capability, software anti-interference is increasingly valued for its flexible design, resource-saving features, and reliability.
The most common phenomenon of microcontroller interference is reset. While program runaway can also be resolved using software traps and watchdog timers to revert the program to a reset state, the most crucial aspect of software anti-interference for microcontrollers is managing the reset state.
Generally, microcontrollers will have some flag registers that can be used to determine the cause of resets; additionally, you can embed some flags in RAM. Upon each program reset, these flags can help identify different reset causes; you can also directly jump to the corresponding program based on different flags. This approach ensures continuity in program operation, and users will not notice that the program has been reset.
4. How to Test the Reliability of Microcontroller Systems
When a microcontroller system design is completed, different microcontroller system products will have distinct testing items and methods, but some tests are essential:
  • Testing the completeness of microcontroller software functions
  • Power-on and power-off tests
  • Aging tests
  • ESD and EFT testing
Sometimes, we can also simulate potentially damaging situations that may occur during human usage. For example, deliberately rubbing the microcontroller system’s contact ports with the body or clothing to test its anti-static capability. Bringing a high-power electric drill near the microcontroller system to test its electromagnetic interference resistance, etc.
In summary, microcontrollers have become an important aspect of computer development and application. Their significance lies in fundamentally changing traditional control system design concepts and methods. Most functions that previously had to be realized by analog or digital circuits can now be achieved using microcontrollers through software methods. This control technology, which replaces hardware with software, is also known as microcontroller technology, representing a revolution in traditional control technology.
Furthermore, during the development and application process, we must master skills and improve efficiency to maximize their broader uses.
Comprehensive Guide to Microcontroller Units
Summary of Chip Operations
The operation of the chip primarily involves manipulating the chip’s internal registers, which are mapped in memory and have their unique addresses. When examining a chip, first look at the timing diagram, then understand the corresponding registers, how to operate them, define the required ports (which the program can recognize), and write the write and read operation programs.
How to write data into the chip, how to read data out, and which ports to input or read from (the most crucial part).
When connecting a chip through a bus, first understand the protocol of that bus. For I2C bus-connected chips, the main control of the chip is done through that bus.
1. A 74HC595 in the dot matrix is used for column selection, while the other two are used for color selection. The dot matrix is equivalent to a collection of diodes. One end must be given a high level, and the other a low level for the diode to light up. It just lights up different colors when the ends are selected differently.
Timer working mode selection: The high four bits set Timer T1, and the low four bits set T0. The last two bits of each mode set the working mode. When setting two timers, be careful to use OR (|). When using interrupts, be mindful to clear any necessary flags upon entering the interrupt.
2. Serial communication: Baud rate settings generally use mode 2 (automatic reload initial value) because different devices have varying data processing capabilities. The baud rate is mainly set to accommodate low-speed devices and facilitate communication between them. The interrupt flag must be cleared by software. When setting the serial port interrupt, either send or receive can trigger the interrupt function, so be careful to set the interrupt function accordingly. (I generally feel that it’s best to set one function as either a host or a slave).
If using an interrupt for sending, the first step is to determine how to enter the interrupt, so the first send must happen before entering the interrupt; thereafter, you can enter the interrupt. Only one byte can be sent at a time, and the next byte can only be sent after TI is set.
3. The PCF8591 AD converter has four input channels. When reading from the PCF8591, select which channel to read from, and the voltage input from that channel will be read. The converted data is stored within the chip and can be read out later. To read, first write the chip’s address, then write the device’s sub-address (0x40 | channel number), followed by the data to be read.
4. DA conversion requires first writing the device address to the chip, then writing the sub-address (0x40), followed by the digital quantity to be converted. The device address is detailed in the chip documentation.
5. For LCD displays, once data is written to be displayed, it will remain displayed without needing continuous refresh. To change the display, you must input new data.
6. For the DS1302 clock chip, data is read during the eighth clock’s falling edge when writing data, and then prepare for the next output. Pay attention to the program’s writing method and where to place the return value.
7. In the DS1302, first specify the register, then write data into it. The register addresses marked in the chip documentation.
(According to the previous expert, after initializing time, a flag can be set so that if this flag exists, there is no need to reinitialize time. However, if power is lost, the MCU’s RAM cannot retain this flag, so the DS1302’s RAM can be used to store this flag, and read it after powering up. I am also a beginner and plan to use the DS1302 soon. I am unsure if this approach is correct; I have not implemented it yet, so I welcome any discussions.)
8. It is best to also write initialization to prevent forgetting later. Be mindful of whether to operate on the lowest or highest bit when reading or writing; this can be determined by the timing diagram.
9. For infrared transmission and reception, the receiver determines whether it is high or low based on the duration between two falling edges. When writing the program, first use a timer to determine the duration, save it, and then convert it to binary (it is beneficial to observe various program writing methods).
10. Stepper motors: Mainly used for switching. The torque of a stepper motor decreases as the speed increases. They are primarily used in machine tools for automatic feeding of parts. They can also be used in places requiring high precision control. A stepper motor is an open-loop control device that converts electrical pulse signals into angular or linear displacements. Under non-overload conditions, the motor’s speed and stopping position depend only on the frequency and number of pulse signals, unaffected by load changes. When a stepper driver receives a pulse signal, it drives the stepper motor to rotate a fixed angle in the set direction, known as the “step angle”. Its rotation occurs in fixed angles step by step. By controlling the number of pulses, the angular displacement can be controlled to achieve accurate positioning; simultaneously, controlling the pulse frequency can regulate the motor’s speed and acceleration to achieve speed control.
Stepper motors convert electrical pulses into angular displacements or linear displacements in an open-loop control manner. Under non-overload conditions, the motor’s speed and stopping position depend solely on the frequency and number of pulse signals, without being affected by load changes. When the stepper driver receives a pulse signal, it drives the stepper motor to rotate a fixed angle in the set direction, known as the “step angle”. Its rotation occurs in fixed angles step by step. The angular displacement can be controlled by controlling the number of pulses, achieving accurate positioning; simultaneously, the motor’s speed and acceleration can be controlled by adjusting the pulse frequency, thereby achieving speed control.
11. Servo motors: A servo motor is a motor that controls the movement of mechanical components in a servo system. It is a type of auxiliary motor that indirectly changes speed. Servo motors can control speed and position very accurately, converting voltage signals into torque and speed to drive controlled objects. The rotor speed of a servo motor is controlled by the input signal and can respond quickly. In automatic control systems, it serves as an actuator and has characteristics such as small electromechanical time constant, high linearity, and starting voltage. It can convert the received electrical signal into angular displacement or angular velocity output on the motor shaft. They are divided into two main categories: DC and AC servo motors, with the main feature being that when the signal voltage is zero, there is no self-rotation phenomenon, and speed decreases uniformly as torque increases.
DC motors have a wide range of applications and are commonly found in small vehicles.
12. Overview of Chinese Characters:
To output Chinese characters on a display or printer, Chinese characters are designed into dot matrix graphics, resulting in corresponding dot matrix codes (glyph codes).
A unified encoding method formed for representing Chinese characters in computers is called internal code (e.g., national standard code). Internal codes are unique (equivalent to the ID number of the character). Encoding formed for the convenience of inputting Chinese characters is called input code, which belongs to the external code of Chinese characters, and input codes vary due to different encoding methods. Encoding formed for displaying and printing Chinese characters is called glyph code; the computer uses the internal code to find the character’s glyph code in the font library to achieve conversion.
Internal Code
According to the national standard code regulations, each Chinese character has a determined binary code. However, this code conflicts with ASCII code during internal processing in computers. To solve this problem, the first bit of each byte of the national standard code is incremented by 1. Since ASCII code uses only 7 bits, this “1” in the first bit serves as a marker for recognizing Chinese character codes. When the computer processes a code with a leading “1”, it interprets it as Chinese character information, while a leading “0” is interpreted as ASCII code. The processed national standard code (internal code) is known as machine internal code.
If we replace the dot in the graphic of the character “口” with “0”, we can visually obtain the glyph code of “口”: 0000H 0004H 3FFAH 2004H 2004H 2004H 2004H 2004H 2004H 2004H 2004H 2004H 2004H 3FFAH 2004H 0000H 0000H. When the computer needs to output “口”, it first locates the starting address of the display font library, calculates the glyph code for “口” based on its internal code, and then uses the glyph code (in binary) to control the character generator to sequentially scan the screen, where the binary code’s “0” indicates a blank scan, and “1” indicates a lit point, resulting in the character graphic for “口” appearing on the display.
The glyph library for Chinese characters is stored in binary file format in memory, forming a Chinese character glyph library, also known as a Chinese character library.
Two encoding methods are detailed in the header file.
GB1616.h//------------------ 汉字字模的数据结构定义 ------------------------//struct  typFNT_GB16               //汉字字模数据结构{      unsignedchar  Index[3];             //汉字内码索引         unsignedchar   Msk[32];                      //点阵码数据 };/////////////////////////////////////////////////////////////////////////// 汉字字模表                                                        //// 汉字库: 宋体16.dot,横向取模左高位,数据排列:从左到右从上到下        ///////////////////////////////////////////////////////////////////////////conststruct  typFNT_GB16 codeGB_16[]=         //数据表{/*------------------------------------------------------------------------------;  源文件 /文字 :徐;  宽×高(像素):16×16------------------------------------------------------------------------------*/ "徐",0x10,0x80,0x10,0x80,0x21,0x40,0x42,0x20,0x94,0x10,0x1B,0xEC,0x20,0x80,0x60,0x80,0xAF,0xF8,0x20,0x80,0x22,0xA0,0x24,0x90,0x2A,0x88,0x21,0x00,0x00,0x00,0x00,0x00,
This structure is very simple: One is the internal code, and the other is the dot matrix sequence. Previously, the dot matrix library was stored in internal code order, requiring no internal code index. If only part of the Chinese characters is stored, an internal code index is needed. (The previous character “徐” is to find the dot matrix sequence for outputting “徐”; this dot matrix sequence was written by the user. When using 1602 displays, the English dot matrix sequence is already present in the chip, so it does not need to be written.) Generally, two bytes are sufficient for the internal code, and using an extra byte is simply adding a trailing zero, allowing the internal code to directly hold the Chinese character string.
codeGB_16[k].Index[0]
codeGB_16[k] indicates an array of structures of typFNT_GB16 called codeGB_16
codeGB_16[k] is the k+1th member of the array
index is a member of the typFNT_GB16 structure, so it can be referenced using codeGB_16[k].Index
index is also an array, so index[0] can be accessed.
if((codeGB_16[k].Index[0]==c[0])&& (codeGB_16[k].Index[1]==c[1]))
&& is the logical AND operator
It means that both values on either side of the && symbol must be true for the value of && to be true, i.e., true && true = true.
This statement implies that both codeGB_16[k].Index[0]==c[0] and codeGB_16[k].Index[1]==c[1] must hold true for the statements below the if to execute.
codeGB_16[] is a structure array, and codeGB_16[k].Index[0] refers to the value of the 0th element of the index member of the k-th structure in the structure array.
13. 12864 LCD:
Each display point corresponds to a binary number, where 1 indicates lit and 0 indicates off. The RAM that stores this dot matrix information is called display data memory. To display a certain graphic or Chinese character, the corresponding dot matrix information must be written into the respective storage unit.
The address counter (AC) for the drawing RAM only automatically increments the horizontal address (X-axis). When the horizontal address = 0FH, it resets to 00H but does not automatically increment the vertical address. Therefore, when writing multiple pieces of information consecutively, the program must determine whether the vertical address needs to be reset.
14. Drawing RAM (GDRAM)
Drawing display RAM provides 128×8 bytes of memory space. When modifying the drawing RAM, first write the horizontal and vertical coordinate values consecutively, followed by writing two bytes of data to the drawing RAM. The address counter (AC) will automatically increment the horizontal address (X address). When the horizontal address is 0XFH, it resets to 00H. It will not automatically increment the vertical address. During the writing process to the drawing RAM, the drawing display must be turned off.
// Display Chinese characters    voiddispString (uchar X, Y,uchar *msg)    //X为哪一行,Y 为哪一列。msg  为汉字   {        if(X==0)       X = 0x80;        // 第一行,汉字显示坐标        else if(X==1) X = 0x90;     // 第二行        else if(X==2) X = 0x88;     // 第三行       else       X = 0x98;        //第四行        Y = X + Y;                //Y 为1 往右移一位        write_com(Y);         // 写入坐标     while (*msg)    {           write_data(*msg++); //显示汉字   }  }  //////////////////////////////// //////////////// ///////////////  // 显示图象  voiddisppicture(uchar code *adder)  {       uint i,j;  //*******显示上半屏内容设置       for(i=0;i<32;i++)                // 上半屏32个列地址       {              write_com(0x80 + i);    //SET  垂直地址 VERTICALADD           write_com(0x80);          //SET   水平地址 HORIZONTAL ADD            for(j=0;j<16;j++)               {                   write_data(*adder);                   adder++;               }        }  //*******显示下半屏内容设置       for(i=0;i<32;i++)               //        {             write_com(0x80 + i);     //SET 垂直地址 VERTICALADD             write_com(0x88);           //SET  水平地址 HORIZONTAL ADD             for(j=0;j<16;j++)              {                  write_data(*adder);                adder++;            }       }  
For C language, defined variables are automatically allocated space, with the address being the variable’s name. Through this name, the data can be accessed in memory, and new data can be obtained through calculations, while in assembly language, the programmer must define storage space and send data to the accumulator for calculations, requiring manual operations at each step. In C language, the compiler handles these processes.
15. Some Useful Q&A
① How is memory allocated for variables in microcontroller C language? Is it true that the compiler intelligently adds allocation and recovery code during the compilation process? The key point is how to ensure that my program does not have memory overflow errors. If I perform recursive calculations, it is challenging to calculate memory requirements.
② Are there constraints on variable definitions in microcontroller C language? For example, multiplication and division operations with floating-point data are quite complex in assembly. If written directly in C language, wouldn’t it be overly simple?
③ Are the addresses of instructions and data in the ROM of the hex file generated by the microcontroller C language automatically allocated by the compiler? Can users allocate them?
Answer 1: C language programs for microcontrollers are first compiled by one program (like c51.exe). After compilation, the size of the variable’s storage space is arranged, but specific addresses are not yet allocated (addresses are floating). Another program (like a51.exe) then connects them, finalizing the specific addresses.
If there are too many variables, the compilation will prompt that the data segment is too large. To avoid memory overflow errors, one must mainly consider whether the stack overflows, relying on experience.
Microcontroller C language generally prohibits recursion; recursion is generally avoided due to the speed impact on microcontrollers compared to PCs. If recursion is necessary, DSP chips are more suitable. In summary, one must choose the appropriate chip.
Answer 2: The size (bit count) of variables generally matches the bit count of the chip’s accumulator. For example, 51 commonly uses 8-bit variables because it is an 8-bit microcontroller. Microcontrollers can define bit variables, but cannot define bit arrays. Writing in C language appears simple, but in reality, it generates the most code. Microcontrollers used for control rarely utilize floating-point calculations, as they are slow, cumbersome, and occupy space. For DSP chips, the hardware structure is more suitable.
Answer 3: Generally, allocation is automatic, and it is possible to mix C and assembly language programming. Keil C also allows inline assembly, and data exchanges between the chip and external devices are conducted via ports.
Disclaimer: The materials in this article are sourced from the internet, and the copyright belongs to the original author. If there are any copyright issues regarding the works, please contact me for removal.
Comprehensive Guide to Microcontroller Units

1

《Baidu Embedded Linux Software R&D Engineer 2021 Campus Recruitment Written Test Questions》

2

《MCU Development is Boring; Let’s Focus on Embedded Development Based on Linux Systems!》

3

《Essential Stack Concepts in Embedded Programming You Must Understand!》

Leave a Comment