If I Became a Microcontroller…

If I Became a Microcontroller...

Source: 21ic Electronics Network

Original Author: Na Luo Mi Mi

A microcontroller (单片机) is an integrated circuit chip that combines a central processing unit (CPU) with data processing capabilities, random access memory (RAM), read-only memory (ROM), various I/O ports, an interrupt system, and timer/counter functions into a single silicon chip, forming a compact and complete microcomputer system. This article reveals the working process of a microcontroller from a first-person perspective.

Buzz~~~~~

A gentle current flows into my body, waking me from slumber. I feel the steady beating of my heart, and my brain is operating at high speed. I sense its operational speed—quick, very quick, with calculations in the tens of megahertz per second. I feel omnipotent. At the same time, I have dozens or even hundreds of limbs. Am I a microcontroller?

Gradually, I also discover my shortcomings. It seems my memory capacity is quite small; I can’t remember many things. Although my thoughts are active, my energy seems limited. All my energy comes from the gentle current that awakened me. While it is stable, it provides very little energy. I can flexibly move my limbs, but they seem incapable of lifting heavy objects. I feel almost useless.

A microcontroller, also known as a microcontroller unit (MCU), integrates the CPU (brain), memory (brain system), clock (heart), and various input/output interfaces (limbs) onto a single integrated circuit chip. Generally, microcontrollers have small memory sizes and low input voltages, typically ranging from 3.3V to 5V. Their operating speeds (main frequencies) range from tens of megahertz to hundreds of megahertz.

If I Became a Microcontroller...▲ Block diagram of the enhanced STM32F103xx moduleAs the environment changes, I suddenly feel a heaviness in my chest; both high and low temperatures cause my heartbeat to become erratic, leading to frequent errors. However, I am helpless. At this moment, I hear a voice: “You are called a microcontroller, a crystallization of technology. Although you currently resemble a clown, you can venture into dungeons to unlock new skins and maps.” So, I fell into a deep sleep.When I wake up again, I feel a sharp pain in my back. What! Someone is tattooing me. Is it “Loyalty to the Country”? Am I destined to charge into battle and achieve great feats? It turns out my dungeon is to protect my homeland…Later, I learned that the tattoo on my back is STM32F103RB. What use is that? Sigh~I didn’t expect this skin to have a magical power, allowing me to unlock a new map—the development board.On this map, I have another heart, an external heart that I can use. That thing is quite powerful; it can adapt to many environments that I cannot, preventing heartbeat irregularities. I just need to activate it when I wake up, and it works great.Now, 32-bit microcontrollers typically integrate an oscillator internally, allowing them to function normally even without an external oscillator. However, internal oscillators are significantly affected by environmental factors, which can cause considerable errors in extreme situations. Therefore, in most applications, an external high-precision oscillator is used to ensure better performance of the microcontroller.If I Became a Microcontroller...▲ Typical application using an 8MHz crystalExploring the new map has begun!Although I have a powerful heart, I still don’t know anything. I’m afraid of the dark and want to turn on the light, but I don’t know how. I see a light on the map, but I don’t know how to turn it on until I meet a magical creature—the programmer. He looks human but strangely resembles a cow.That day, the programmer gave me a manual to turn on the light. This manual is so complicated; it requires me to do many things, and finally, I just need to pull a switch with one of my hands to turn on the light. I don’t understand why it has to be so complicated. However, sometimes he gives me very simple manuals that only say: “Reach out.” Then the light turns on. How magical! Why did he give me such a complicated manual before?A microcontroller itself does not contain any functions; users must write code, compile it into a language familiar to the microcontroller, and burn it into the microcontroller to realize functionality. For example, to turn on a light, we simply set the control pin for the light to output the corresponding level.In ST’s development environment, ST provides various development methods: direct register manipulation, standard libraries, HAL libraries, and LL libraries. Among them, the register method is the most direct, allowing the microcontroller to respond the fastest and execute code with the highest efficiency, but it is also the most challenging. The LL library is close to the register, with slightly lower efficiency. The standard library encapsulates the registers, allowing users to directly use library functions to achieve functionality without directly facing the registers; this was once the most commonly used method. The HAL library is the simplest development method, isolating the registers from the developer, making development particularly easy, but it also brings a problem: the execution efficiency is lower compared to the previous methods.Once I learned to turn on the light, I found that my logical thinking seemed problematic. I always follow a single path and cannot backtrack; I can only proceed linearly. Fortunately, the programmer gave me a new manual that said: “The sea of suffering is endless; turning back is the shore.” It essentially told me to complete the main task before starting over and to pay attention to my limbs. If he touches a different limb, I must pause the main task to complete the side task. Only after finishing the side task can I return to continue the main task.The manual also specifies the urgency of tasks. If he touches my first limb, I must complete the first side task. If I haven’t finished it and he touches my second limb, I must pause the first side task to complete the second side task. After finishing the second side task, I can return to the first task, and I can only return to the main task after completing both side tasks.A microcontroller is linear; it will execute according to logic continuously. When an urgent event needs to be handled, the microcontroller can use its interrupt system to manage it. The microcontroller will pause the current task and switch to the task assigned by the interrupt, returning to the previously interrupted instruction after completing the interrupt.If I Became a Microcontroller...▲ Interrupt nesting and response diagramAs shown in the figure above, when an interrupt occurs, the microcontroller saves the state and parameters at the time of the interrupt into the stack. It completes the interrupt service task according to the interrupt vector. After finishing the interrupt service task, it returns to the previously interrupted instruction and continues executing downwards. When a higher-priority interrupt request arrives while executing the current interrupt function, the current interrupt task is saved, and it jumps to execute the higher-priority task. After the higher-priority task is completed, it returns to the previously lower-priority task and continues executing until all interrupt tasks are completed and returns to the main program.That day, I discovered another microcontroller. It was hard to meet a kindred spirit, and I wanted to chat with it. So, I called out to it (UART), but I could only emit 1s and 0s, and it remained unresponsive. Then, the programmer gave me a dictionary (protocol). Following the dictionary’s instructions, I began to speak, but the other party’s language skills seemed poor. If I spoke too quickly, it couldn’t respond; if I spoke too slowly, it would miss my words (baud rate matching). After many attempts, I finally got a response, but it could only say things like 1 and 0. I could only use the dictionary to translate (encoding), but I could only respond one for one, like a walkie-talkie (asynchronous serial communication). Fortunately, although it was cumbersome, we could finally communicate.As time passed, the distance between us grew, and our conversations became intermittent. Even if I shouted at the top of my lungs, it was useless (long-distance communication). So, we found a loudspeaker (RS485 chip). This device comes with its own power supply, so we don’t need to provide one (separate power supply). I just need to speak normally, and it amplifies my voice, allowing us to communicate even from a distance. However, for some reason, our distance kept increasing, far enough that the loudspeaker couldn’t help. But that didn’t stop us; we found a more advanced device—a wireless communication module. With this device, we could communicate flawlessly across vast distances.In embedded development, the UART serial communication protocol is one of the commonly used communication protocols, known as the Universal Asynchronous Receiver/Transmitter. It is a type of asynchronous serial communication protocol that works by transmitting each character of data one bit at a time. It can convert data to be transmitted between serial and parallel communication, allowing for flexible full-duplex data exchange with external devices. UART communication must adhere to the communication protocol and match the baud rate to function correctly. The communication process can be imagined as shown in the figure below:If I Became a Microcontroller...▲ Normal communicationSending data via UART is like opening a door to let data out; the baud rate controls the speed of opening the door. When the sender releases data at a certain rate, the receiver also opens and closes its gate at the same speed, allowing the data to come in one by one. If the baud rates of the sender and receiver do not match, data may arrive at the receiver’s door when it is closed, preventing the data from entering and causing communication errors.If I Became a Microcontroller...▲ Communication errorWhen the communication distance is too far, communication can be obstructed. In this case, RS-485 communication can be used. The RS-485 protocol was developed to solve the distance limitations of RS-232 communication. The maximum data transmission rate of RS-485 is 10Mbps. The RS-485 interface uses a combination of balanced drivers and differential receivers, enhancing its ability to resist common-mode interference, thus improving noise immunity.The maximum communication distance of RS-485 is approximately 1219m, with a maximum transmission rate of 10Mbps. The transmission rate is inversely proportional to the transmission distance. At a transmission rate of 100Kb/s, the maximum communication distance can be achieved. If longer distances are required, RS-485 repeaters must be added. The RS-485 bus generally supports a maximum of 32 nodes. If special RS-485 chips are used, it can support up to 128 or 256 nodes, with a maximum of 400 nodes possible.RS-485 communication only requires two wires, + and -, also known as A and B. The differential voltage signal between A and B is used for data transmission. Since both sending and receiving use these two wires, it means that each time, they can only be used for either sending or receiving. Therefore, RS-485 is half-duplex communication.If I Became a Microcontroller...▲ RS-485 communicationBut talking like this is exhausting. How can I make sounds? At this moment, I discover that I have a buzzer (passive piezoelectric) in my hand. As long as I shake it vigorously, it will make sounds. The frequency of my shaking determines the pitch of the sound, allowing me to produce different sounds. I can even play a tune (square wave signal input converted to sound output). However, it’s quite tiring, and I have to keep track of the timing while shaking.Now that I have music, I also want lights, but the light in my hand can only emit one color; I can either turn it on or off. So, I found a timer on my body that I can use to control my hand to switch the light (PWM output). By controlling the time the light is on and off, it can blink on and off, but I need to act quickly (frequency greater than the human eye’s capture frequency), or it will flicker, which is really cool (dynamically changing PWM duty cycle).Gradually, I feel that raising a dog would be better because last time I made a mistake, I got stuck in a loop and refused to give up, causing many things to be delayed and almost getting me into trouble. I decided to raise a watchdog (watchdog timer). I need to feed the dog periodically; if it isn’t hungry, it won’t bark. If I get stuck, I might forget to feed the dog, and it will bark, reminding me to react.However, I also need to solve problems. I can write down these issues in a notebook (write FLASH), so I can check what happened later. But my notebook is quite inconvenient; I have to erase a page every time to write, and I have to erase at least one page. However, it is still necessary because every time I fall asleep (power loss), I lose some data (RAM data is lost on power loss). To prevent forgetting, I can write it down. But my brain might really have a problem; every time I take notes, I always block out other sounds, and no one can disturb me.In a microcomputer system composed of microcontrollers, the operation of the microcontroller is often affected by external electromagnetic interference, causing the program to run erratically and fall into a dead loop. The normal operation of the program is interrupted, and the system controlled by the microcontroller cannot continue to work, leading to unpredictable consequences. Therefore, to monitor the operating status of the microcontroller in real-time, a special chip for monitoring the program’s operation status was developed, commonly known as a “watchdog”.The watchdog’s function is to reset the CPU if it does not receive a signal from the system within a specified time, indicating that the system is malfunctioning. Generally, projects will use two watchdogs: one is an independent watchdog, mainly used for resetting after the code runs erratically, and the other is a window watchdog, primarily used to save important data before resetting. Small amounts of data can generally be saved in the microcontroller’s own FLASH, persisting even after power is restored.Note:1. The FLASH size varies for each microcontroller. Before operating FLASH, it is essential to confirm the FLASH size of the microcontroller in hand according to the manual. Writing operations that exceed FLASH capacity are not allowed and cannot be completed successfully.2. Calculate the program’s memory size; the program is also stored in FLASH. If the program size is not calculated correctly, writing the program into the memory occupied by FLASH will cause the program to crash.3. Before writing data, the page must be erased first because FLASH cannot write 1, only 0. Therefore, before writing, the FLASH page’s data must be restored to FF through the erase operation. If there is data that needs to be retained in FLASH, it must be read into a buffer first, then the page erased, and finally, the data written.4. Data not exceeding one page can be written continuously.5. Pay attention to the FLASH operation unit; at least 4 bytes must be written at a time. The page size can be checked in the manual, as generally, whole pages are erased and written, and arbitrary erasing and writing are not allowed.6. Operating FLASH will occupy the bus and interrupt your interrupt operations, and writing FLASH generally takes a long time. Therefore, ensure that the microcontroller has enough time reserved when operating FLASH.I feel that I still have many strong abilities waiting to be discovered, but suddenly I feel my energy is dwindling, and I gradually feel dizzy. I might need to rest for a while. I wonder if a short nap will help (sleep mode). If not, I might need to sleep well (deep sleep). If my energy decreases further, I might fall into a deep sleep (standby mode), and when I wake up, I might forget everything that happened before (data loss in RAM on power-off).Hoo~~1. Sleep Mode:In sleep mode, only the core clock is turned off, and the core stops running, but its on-chip peripherals and the CPU core’s peripherals continue to operate normally, which is reflected in software as no new code execution. This state retains the core registers and memory data from before sleep. Upon waking, if awakened by an interrupt, it first enters the interrupt, exits the interrupt service routine, and then continues executing the program after the WFI instruction; if awakened by an event, it directly continues executing the program after the WFE instruction. Wake-up delay: none. (WFI: Wait For Interrupt, WFE: Wait For Event).2. Deep Sleep Mode (Stop Mode):In stop mode, all other clocks are further turned off, so all peripherals stop working. However, due to the partial power supply in the 1.2V region not being turned off, the core registers and memory information are retained. Therefore, upon waking from stop mode and re-enabling the clock, it can continue executing code from where it last stopped.Upon waking, if awakened by an interrupt, it first enters the interrupt, exits the interrupt service routine, and then continues executing the program after the WFI instruction; if awakened by an event, it directly continues executing the program after the WFE instruction. After waking from stop mode, the STM32 will use HSI (f1’s HSI is 8M, f4 is 12M) as the system clock. Therefore, it is necessary to reconfigure the system clock in the program after waking to switch back to HSE.Wake-up delay: the base delay is the startup time of the HSI oscillator. If the regulator operates in low-power mode, the time to switch the regulator from low-power to normal mode must also be added. If FLASH operates in power-off mode, the time to wake FLASH from power-off mode must also be added.3. Standby Mode:In this mode, all clocks are turned off, and the power supply to the 1.2V region is also completely turned off. This means that upon waking from standby mode, there is no record of the previous code execution, and the chip can only be reset, rechecking the boot conditions, and starting the program from the beginning.

END

The reproduced content only represents the author’s views

It does not represent the position of the Semiconductor Institute of the Chinese Academy of Sciences

Editor: Renowned Wei Classmate

Editor-in-Chief: Three Dollar Fish

Submission Email: [email protected]

Previous Recommendations

1. The Semiconductor Institute has made progress in the research of bionic covering neuron models and learning methods

2. The Semiconductor Institute has made significant progress in inverted structure perovskite solar cells

3. Why do chips use copper as interconnect metal?

4. What exactly is 7nm in chips?

5. Silicon-based integrated optical quantum chip technology

6. How abnormal is the quantum anomalous Hall effect? It may lead to the next revolution in information technology!

If I Became a Microcontroller...

Leave a Comment