Microcontroller: programming and debugging

 Microcontroller: programming and debugging 

2026-07-09

Microcontroller: programming and debugging - from code to hardware without errors

The process of developing embedded systems often turns into a struggle not with the logic of the algorithm, but with the unpredictable behavior of the hardware.Microcontroller: programming and debugging- these are not just two separate stages, but a single cycle, where an error in timing settings can undo weeks of writing clean code. In our practice of working with industrial customers, we have repeatedly encountered a situation where a device worked stably on an engineer’s desk, but was reset due to vibration or power surges in production. The reason always lay not in the C++ syntax, but in ignoring the physical limitations of the peripheral and the wrong debugging strategy.

This article was written by engineers who have gone from simple Arduino projects to complex industrial controllers based on ARM Cortex-M and RISC-V. We'll look at how to choose the right debugging tool, why static code analysis saves money faster than an oscilloscope, and what safety standards (such as IEC 61508) dictate firmware quality requirements. If you want to avoid the typical pitfalls of embedded development, this material will save you dozens of hours.

Choosing a development environment and tools: the basis for stability

The first step, which determines the speed of all subsequent work, is the choice of an integrated development environment (IDE) and compiler. Many beginners make the mistake of choosing tools based solely on popularity, ignoring support for a specific family of microcontrollers. For professional development, not only syntax highlighting is critical, but also the depth of integration with the debugger.

Three approaches dominate the industrial segment. The first is the use of vendor IDEs, such as STM32CubeIDE or MPLAB X. Their main advantage is the ready-made configuration of peripherals and code examples. However, they often suffer from redundancy and slow performance on large projects. The second approach is professional cross-platform frameworks such as Keil MDK or IAR Embedded Workbench. They provide the highest code optimization, which is critical for microcontrollers with limited memory (less than 64 KB Flash). The third, increasingly popular option is a combination of VS Code + PlatformIO or Eclipse + GNU Arm Embedded Toolchain. This path requires more initial setup time, but provides maximum flexibility and control over the build process.

We recommend choosing a tool based on your certification requirements. If your product must meet functional safety standards, using certified compilers (eg IAR with TUV certification) is not a choice, but a necessity. Conventional GCC, even being a powerful tool, will require additional validation efforts for medical or automotive applications.

Practical advice:Before starting a large project, test the selected toolchain on a simple example using all types of peripherals that you plan to use. Check how convenient it is to look at the assembly listing and memory map. If difficulties arise at this stage, they will turn into a nightmare when scaling the project.

Firmware architecture: modular versus monolithic

The structure of the code directly affects the difficulty of debugging. Monolithic firmware, where all the logic is in one filemain.c, works until the project exceeds 500-1000 lines of code. After this, finding a bug related to variable or interrupt conflicts becomes a task with an asterisk. A professional approach requires a strict separation of abstraction layers.

We use a three-tier architecture:

  1. Hardware abstraction level (HAL):Low-level drivers that work directly with registers or manufacturer libraries. This layer should be isolated as much as possible. Changing the microcontroller should require changes only here.
  2. Middleware/Services:Peripheral logic (ADC filtering, UART/SPI communication protocols, PWM control). There is no knowledge about the business logic of the device.
  3. Application Layer:Final logic of the product (state machine, processing user commands).

This structure allows you to debug each level independently. For example, you can write unit tests for the Services layer on a PC, emulating the operation of the hardware, and make sure that the data filtering algorithms are correct even before the board is manufactured. This reduces debugging time on real hardware by 30-40%.

One of the most common mistakes we have seen from clients is the use of global variables to exchange data between modules. This leads to hidden dependencies and subtle bugs when one function changes the value used by another, completely unrelated part of the program. Use queues or data structures with a clear access interface.

Debugging Strategies: From printf to real-time tracing

Debugging embedded systems differs from desktop development in that you can't always stop the program from running. In real-time systems, stopping the processor by a breakpoint can lead to engine failure or loss of data packets. Therefore, an engineer's arsenal must include methods that do not stop code execution.

1. Logging via UART/ITM

Classic methodprintfvia UART is useful, but it is slow and blocking. If the buffer overflows, the program will freeze. A more advanced option is to use the Instrumentation Trace Macrocell (ITM) interface available on Cortex-M cores. ITM allows you to display debugging information asynchronously, with virtually no CPU load. The data goes directly to a debugger (for example, Segger Ozone or ST-Link Utility) via a separate SWO wire.

2. Hardware breakpoints and watchpoints

Modern debuggers support hardware watchpoints. You can set a trigger to write to a specific memory cell. As soon as the variable changes, the processor will stop. This is indispensable when looking for memory corruption when the stack overwrites global variables. In our practice, this method helped us find an error that appeared only after 48 hours of continuous operation of the device.

3. Energy consumption analysis as a debugging tool

An unobvious but powerful method. By connecting a high-resolution ammeter to the power circuit, you can visualize the execution of the code. Different parts of the program consume different current. If you see an unexpected spike in consumption, it could mean entering an unexpected state or getting stuck in a loop. This method is especially effective for debugging sleep modes, where current leakage of several microamps can be critical for battery devices.

Important:Never leave active debug pins (SWD/JTAG) connected in the final product without protection. This is a security hole and a potential source of interference. Use fuses or jumpers that are removed during final assembly.

Dealing with interruptions and multitasking

Interrupts are the most powerful and most dangerous mechanism of a microcontroller. Incorrect handling of them leads to race conditions and freezes, which are almost impossible to reproduce deterministically. The main rule: the interrupt handler (ISR) should be as short as possible. It should only capture the event (for example, putting a byte into the ring buffer) and exit. All heavy processing should happen in the main loop or RTOS task.

When using real-time operating systems (FreeRTOS, ThreadX, Zephyr), the synchronization problem is solved through mutexes and semaphores. However, many developers forget about priorities. If a low priority task holds a mutex and a high priority task tries to grab it, priority inversion occurs. The system may freeze. The solution is to use the Priority Inheritance Protocol, which is supported by most modern RTOS.

We strongly recommend using static stack analyzers. Stack overflow is the #1 cause of random microcontroller reboots in the field. Tools like Stack Usage Analysis in IAR or manually marking patterns in memory can accurately determine the peak stack usage of each task.

Common mistakes and how to avoid them

Over the years, we have identified a list of mistakes that 80% of developers make when moving from prototyping to production.

  • Ignoring default states (Reset State).After a reset, the microcontroller pins may be in an undefined state. If you control a relay or power switch, this may result in false activation. Always explicitly initialize GPIO at the beginning of the functionmain()before turning on any peripherals.
  • No timeouts.Any communication via UART, I2C or SPI must have a timeout. If a slave hangs, your microcontroller shouldn't wait forever. Infinite loopswhile(!flag)without checking the meter - a direct path to system failure.
  • Unaccounted side effects of compiler optimization.When you enable O2 or Os level optimization, the compiler may remove variables that it thinks are not changing. If a variable is changed in an interrupt, it must be declared asvolatile. The absence of this keyword is a classic mistake that causes the code to work in Debug mode and break in Release.

One of our clients encountered an issue where the device stopped responding to buttons after a firmware update. It turned out that the new code used a loop-based delay, which the compiler optimized, considering it useless. Additionvolatileto the cycle counter solved the problem instantly.

Testing and validation before mass production

Programming and debugging do not end at the “it works” stage. The “it always works” stage begins. For the B2B sector, compliance is critical. In Russia and the EAEU countries this is often GOST R ISO 9001 for development processes and industry standards (for example, GOST IEC 60730 for automatic electrical regulators).

The validation process should include:

  1. Stress testing:Operation at extreme temperatures (-40°C…+85°C) and limiting supply voltage values. The firmware must correctly handle brown-outs, saving data to EEPROM or Flash.
  2. EMC tests (Electromagnetic compatibility):Although this is more a matter of circuit design, it is possible to add debounce filters for inputs and data integrity checks (CRC) for communications in software.
  3. Long-term tests (Long-run tests):Continuous operation of the device for 7-14 days with logging of all events. This allows you to identify memory leaks that accumulate slowly.

Documenting the debugging and testing process is a requirement for many large customers. Save change logs, bug reports and test results. This builds the company's knowledge base and speeds up the development of subsequent products.

The role of reliable component suppliers in project success

Even perfectly debugged code and competent architecture will not save the device if the hardware base is built on low-quality or counterfeit components. In industrial electronics, supply chain reliability is as important as firmware quality. This is where professional distributors such asWuhan Xinhualong Technology LLC.

Founded in 2009 in China's "Optical Valley" (Wuhan), the company has established itself as a key intermediary between the world's leading integrated circuit manufacturers and end consumers. The main value of such a partnership is the guarantee of product authenticity. Wuhan Xinhualong Technologies provides a completely legal and transparent supply chain: all components, from LHA6961 series analog-to-digital converters and ZJC2000 SAR converters to Loongson 3 architecture processors (LS3D5000) and specialized LS76928 controllers, are supplied exclusively through official channels.

For developers of embedded systems, technical support is especially important at the stage of selecting a component base. The company's in-house application engineers (FAEs) have deep expertise in electronic component integration, helping to avoid compatibility issues early in the design phase. Whether it's the R-FDM320R069 RF solutions, the AS2630A voice chips, or the JT2150W solar relays, each element goes through multiple levels of quality control, including lot number verification and technical specification compliance. Cooperation with a trusted distributor minimizes the risk of “floating” defects caused by defective components, allowing engineers to focus on the software part of the task.

Frequently Asked Questions

Which debugger is better for a beginner: ST-Link, J-Link or DAPLink?

For training and simple projects, clones of ST-Link or CMSIS-DAP (DAPLink) are sufficient - they are cheap and functional. However, for professional debugging, especially at high speeds or using complex Trace functions, we recommend the original Segger J-Link debuggers. They have better stability, support for a huge number of chips and powerful Ozone software for data visualization. The difference in price is worth it in time saved.

How to protect microcontroller firmware from copying?

Most modern microcontrollers have Read Protection (RDP) bits. Setting RDP Level 1 prevents reading Flash memory through the debugger. For maximum protection, use RDP Level 2 (irreversible blocking), but be careful: this disables the ability to flash again through standard interfaces. Another effective method is to encrypt the firmware and use unique chip IDs to link the code to a specific device.

What to do if the microcontroller does not exit Bootloader mode?

This usually occurs due to the incorrect state of the BOOT0/BOOT1 pins at startup or damage to the flash memory. First check the voltage and condition of these pins. If the hardware is ok, try connecting the UART interface and sending a reset or erase command through the manufacturer's official utility (for example, STM32 CubeProgrammer). As a last resort, a full reset via the NRST signal will help with a certain power supply algorithm described in Errata to the chip.

Should I use RTOS in simple projects?

No. If your task is linear and does not require simultaneous processing of multiple independent events under tight time constraints, RTOS will add unnecessary complexity and memory overhead. A superloop with a non-blocking architecture based on a State Machine will be a more efficient and easier to debug solution. Switch to RTOS only when manual thread management becomes impossible.

Conclusion

Qualitativeprogramming and debugging of microcontrollersis a balance between a deep understanding of hardware and the discipline of writing code. There is no “silver bullet” that will get rid of bugs, but using the right tools, modular architecture and hardware debugging methods (tracing, power consumption profiling) reduces the risks by an order of magnitude. Investments in studying the datasheet and reference manual of your chip pay off faster than searching for random solutions on forums.

If you are faced with complex tasks in the field of embedded development, require a code audit or help in choosing a component base for an industrial product, our experts are ready to help. We have experience bringing devices to market that meet stringent reliability standards and partner with trusted suppliers to ensure the quality of every element of your system.

Embedded systems development and microcontroller programming services

Contact us today

Home
Products
About Us
Contacts

Пожалуйста, оставьте нам сообщение

Privacy Policy

Thank you for using this site (“we”, “us” or “our”). We respect your rights and interests in personal information, comply with the principles of legality, legitimacy, necessity and integrity, and protect your information security. This policy describes how we process your personal information.

1. Collection of information
Information you provide voluntarily, such as name, mobile number, email address, etc., is completed during registration. Information such as device model, browser type, access logs, IP address, etc. is automatically collected to optimize service and security.

2. Use of information
provide, maintain and optimize website services;
account verification, security protection and fraud prevention;
Send necessary information such as service notifications and policy updates;
Comply with laws, regulations and applicable regulatory requirements.

3. Protection and exchange of information
We use security measures such as encryption and access controls to protect your information and only store it for the minimum period necessary to complete the task.
Do not sell or rent personal information to third parties without your consent; Share only if:
Get your explicit permission;
third parties entrusted to provide services (subject to confidentiality obligations);
Respond to legal requests or protect legitimate interests.

4. Your rights
You have the right to access, correct and supplement your personal information, and you can also apply to cancel your account (after cancellation, the information will be deleted or anonymized according to the rules). To exercise your rights, you may contact us using the contact details provided below.

5. Policy Updates
Any changes to this policy will be notified by posting on the site. Your continued use of the services means your acceptance of the amended rules.