At present, the PIC series of microcontrollers produced by Microchip have rapidly occupied the domestic market with its advantages of low cost, low power consumption, high performance, fast development speed and one-time user programmability, becoming the best-selling microcontroller in China. However, there are relatively few books and articles introducing its C language development tools in China, and not many people use it, which has brought many difficulties and inconveniences to programmers in the process of development.
Microchip does not have its own C language compiler for low-end and mid-range PIC microcontrollers, but many professional third-party companies provide a number of C language compilers that support PIC microcontrollers, including Hitech, CCS, IAR, Bytecraft, etc. Hitech's PICC compiler is stable and reliable, and the compiled code is highly efficient. It is widely recognized by engineers who use PIC microcontrollers for system design and development. Therefore, this article mainly introduces the basic characteristics of PIC's C language based on Hi-Tech PICC.
1. Differences and similarities between HiTech PICC and ANSI C and characteristics of HiTech PICC language
Except that PICC does not support recursive function calls, PICC basically complies with the ANSI standard. The main reason is the special stack structure of PIC microcontrollers. The stack in PIC microcontrollers is implemented by hardware, and its depth is fixed with the chip, so it is impossible to implement recursive algorithms that require a large number of stack operations. In addition, the efficiency of implementing software stacks in PIC microcontrollers is not very high. For this reason, the PICC compiler uses a "static overlay" technology to allocate fixed address space to local variables in C language functions. The machine code generated after this treatment is very efficient. When the code size exceeds 4 kB, the difference between the length of the code compiled by C language and the length of the code implemented entirely in assembly code is not very large (<10%). Of course, the premise is that you need to pay attention to the efficiency of the statements you write during the entire C code writing process.
2Variables in PICC
The variable types in PICC are the same as those in standard C, so they will not be repeated here. In order to make the compiler generate the most efficient machine code, PICC leaves the bank problem of the data registers in the microcontroller to the programmer to manage. Therefore, when defining user variables, you must decide which bank to put these variables in. If not specifically specified, the defined variables will be located in bank0. The variables defined in other banks must be preceded by the corresponding bank number, for example:
bank1 unsigned char temp; // variable is located in bank1
The size of a bank of data registers in the mid-range PIC microcontroller is 128 bytes. Excluding the special function register area of the first several bytes, the total number of variable bytes defined in a bank in the C language cannot exceed the number of available RAM bytes. If the bank capacity is exceeded, an error will be reported at the final connection. The general information is as follows:
The connector prompts that a total of 0x12C (300) bytes are ready to be placed in bank1, but the capacity of bank1 is insufficient. Although the bank location of the variable must be determined by the programmer himself, there is no need to specifically write instructions to set the bank before performing variable access operations when writing the source program. The C compiler will automatically generate assembly instructions for the corresponding bank settings based on the object being operated. In order to avoid frequent bank switching and improve code efficiency, try to locate variables that implement the same task in the same bank; when reading and writing variables in different banks, try to merge variables in the same bank together for continuous operations.
Bit variables can only be global or static. PICC will merge 8 bit variables located in the same bank into one byte and store it at a fixed address. PICC implements bit addressing for the entire data storage space. The 0th bit of the 0x000 unit is the bit address 0x0000. From then on, each byte has 8 bit addresses. If a bit variable flag1 is addressed as 0x123, then the actual storage space is located at:
Byte address = 0x123/8 = 0x24
Bit offset = 0x123%8 = 3
That is, the flag1 bit variable is located at the 3rd bit of the byte at address 0x24. When debugging the program, if you want to observe the changes of flag1, you must observe the byte at address 0x24 instead of 0x123. When PICC compiles the original code, whenever possible, the operation of ordinary variables will be implemented with the simplest bit operation instructions. Assuming that a byte variable tmp is finally located at address 0x20, then In
addition, the function can return a bit variable. In fact, this returned bit variable will be stored in the carry bit of the microcontroller and brought out of the return. [page]
3 Pointers in PICC
3.1 Pointers to RAM
When PICC compiles the original C program, the pointer operation pointing to RAM is finally implemented with FSR for indirect addressing. The range that FSR can directly and continuously address is 256 B, so a pointer can cover the storage area of two banks at the same time (bank0/1 or bank2/3, one bank area is 128 B). To cover the internal data storage space of up to 512 B, the addressing area applicable to the pointer must be clearly specified when defining the pointer. For example:
Since the defined pointer has a clear bank applicable area, type matching must be implemented when assigning a value to the pointer variable, otherwise an error will occur. For example:
If such an erroneous pointer operation occurs, PICC will inform a message similar to the following when the connection is finally made:
Fixup overflow in expression (…)
3.2 Pointers to ROM constants
If a set of variables is a constant that has been defined in the ROM area, then the pointer to it can be defined as follows:
3.3 Pointer to function
Because the efficiency of implementing function pointer calls on the specific architecture of PIC microcontrollers is not high, it is recommended that you try not to use function pointers unless required by special algorithms.
4Subroutines and functions in PICC
The program space of the mid-range PIC microcontroller has the concept of paging, but you don't need to worry too much about the paging of the code when programming in C language, because the page setting when calling all functions or subroutines (if the code exceeds one page) is implemented by the instructions automatically generated by the compiler.
4.1 Function code length limit
PICC determines that the machine code generated by a function in a C source program after compilation must be placed in the same program page. The length of a program page of the mid-range series of PIC microcontrollers is 2 kB, and the code generated by any function written in C language cannot exceed 2 kB. If you really need to write a long program continuously to achieve a specific function, then you must split these continuous codes into several functions to ensure that the code compiled by each function does not exceed one page space.
4.2 Call hierarchy control
PIC microcontrollers use hardware stacks, so the function call levels are subject to certain restrictions during programming. Generally, the hardware stack depth of the mid-range microcontrollers in the PIC series is 8 levels. Programmers must control the nesting depth of subroutine calls to meet this restriction. After the final compilation and connection is successful, PICC can generate a connection positioning mapping file (*map), which contains a detailed function call nesting indicator graph "call graph". Some function calls are library functions that are automatically added when compiling the code. These function calls cannot be directly seen from the C source program, but they are clear at a glance on the nesting indicator graph.
5. Mixed programming of C language and assembly language
Some special instructions of the microcontroller do not have a direct corresponding description in the standard C language syntax, such as the clear watchdog instruction "clrwdt" and the sleep instruction "sleep" of the PIC microcontroller; the microcontroller system emphasizes the real-time control. In order to achieve this requirement, it is sometimes necessary to use assembly instructions to implement part of the code to improve the efficiency of program operation. There are two ways to embed assembly instructions in C programs:
(1) If you only need to embed a few assembly instructions, PICC provides a function-like statement:
asm("clrwdt");
This is the most direct and easiest way to directly embed assembly instructions in the original C program.
(2) If you need to write a continuous section of assembly instructions, PICC supports another syntax description: start the assembly instruction segment with "#asm" and end it with "#endasm". For example:
[page]
5.1 Assembly instructions address global variables defined in C language
All symbols defined in C will automatically have an underscore "_" added in front of them after compilation. Therefore, if you want to address various variables defined in C language in assembly instructions, you must add the "_" symbol in front of the variable. For example, count in the above example is an unsigned global variable defined in C. In assembly language, you only need to add the "_" symbol in front of it to access it. In addition, for multi-byte global variables defined in C, for example, there is the following definition in C:
Then when accessing it in assembly, you have to access it by bytes, for example:
5.2 Assembly instructions address local variables of C functions
As mentioned above, PICC uses a "static overwrite" technique to determine a fixed address (located in bank0) for each automatic local variable (including the entry parameters when calling a function), so the embedded assembly instructions only need to use the direct addressing method of the data register to address it, so the key is to know the addressing symbols of these local variables. It is recommended that readers first write a small piece of C code, which contains the simplest local variable operation instructions, and compile this C source code into the corresponding PICC assembly instructions; check how the assembly instructions generated by the C compiler address these local variables, and use the same addressing method for the inline assembly instructions written by yourself.
Compared with assembly language, the advantages of programming in C language are unquestionable: development efficiency is greatly improved, humanized statement instructions plus modular programs are easy to manage and maintain on a daily basis, and programs are easy to port between different platforms. So since C language is used for programming, try to avoid using embedded assembly instructions or writing assembly instruction module files as a whole. For example:
the circular right shift operation of variables is very inconvenient to implement in C language. PIC microcontrollers already have corresponding shift operation assembly instructions, so it is most efficient to implement it in the form of embedded assembly. At the same time, the control of the number of shifts, in essence, the decrement judgment of the variable count1 can also be directly implemented with assembly instructions, which can save code, but it is more intuitive and easier to maintain to describe it in standard C language.
6. Notes
(1) Since all local variables will occupy the storage space of bank0, the number of bytes of variables that users can locate in bank0 will be limited. Please pay attention to this in actual use.
(2) When a non-bit variable is converted into a bit variable in a program, please note that the compiler only judges the lowest bit of the ordinary variable: if the lowest bit is 0, it is converted into bit variable 0; if the lowest bit is 1, it is converted into bit variable 1.
(3) Since the internal resources of the PIC series microcontroller are very limited, unsigned character variables should be used as much as possible to save space under the conditions allowed.
(4) PICC does not reserve address space for absolutely located variables, for example:
So please use it with caution.
(5) Try to use global variables for parameter passing. The biggest advantage of using global variables is that addressing is intuitive. You only need to add an underscore before the variable name defined in C language to address it in the assembly statement; the efficiency of using global variables for parameter passing is also higher than that of formal parameters.
(6) For multi-byte variables (such as int type, float type variables, etc.), PICC follows the Littleendian standard, that is, the low byte is placed at the low address of the storage space, and the high byte is placed at the high address. Please pay attention to this when programming.
7 Conclusion
Generally, the codes generated by C language are relatively complicated, so if you want to write high-quality and practical C language programs, you must have a detailed understanding of the microcontroller architecture and hardware resources. However, using C language to develop PIC series microcontroller system software has the advantages of high code writing efficiency, intuitive software debugging, convenient maintenance and upgrading, high code reuse rate, and convenient cross-platform code transplantation. Therefore, the application of C language programming in microcontroller system design will become more and more extensive.
References
[1]HITECH Software.PICC ANSI C compiler use's guide[EB].2002.
[2]Cai Chunjie, Xing Wu.PIC 16/17 microcontroller principle and application[M].Hefei: University of Science and Technology of China Press, 1997
Previous article:Application of PIC16C65 single chip microcomputer in scanning tunneling microscope
Next article:Application of PIC16C7X microcontroller in low power consumption identification and meter reading
Recommended ReadingLatest update time:2024-11-16 15:57
- Popular Resources
- Popular amplifiers
- Modern Compiler Principles C Language Description (Ampel)
- Principles and Applications of Single Chip Microcomputers 3rd Edition (Zhang Yigang)
- Power Integrated Circuit Technology Theory and Design (Wen Jincai, Chen Keming, Hong Hui, Han Yan)
- Digital integrated circuit backend design (Tian Xiaohua, Li Chunxia, Wang Xu)
Professor at Beihang University, dedicated to promoting microcontrollers and embedded systems for over 20 years.
- Innolux's intelligent steer-by-wire solution makes cars smarter and safer
- 8051 MCU - Parity Check
- How to efficiently balance the sensitivity of tactile sensing interfaces
- What should I do if the servo motor shakes? What causes the servo motor to shake quickly?
- 【Brushless Motor】Analysis of three-phase BLDC motor and sharing of two popular development boards
- Midea Industrial Technology's subsidiaries Clou Electronics and Hekang New Energy jointly appeared at the Munich Battery Energy Storage Exhibition and Solar Energy Exhibition
- Guoxin Sichen | Application of ferroelectric memory PB85RS2MC in power battery management, with a capacity of 2M
- Analysis of common faults of frequency converter
- In a head-on competition with Qualcomm, what kind of cockpit products has Intel come up with?
- Dalian Rongke's all-vanadium liquid flow battery energy storage equipment industrialization project has entered the sprint stage before production
- Allegro MicroSystems Introduces Advanced Magnetic and Inductive Position Sensing Solutions at Electronica 2024
- Car key in the left hand, liveness detection radar in the right hand, UWB is imperative for cars!
- After a decade of rapid development, domestic CIS has entered the market
- Aegis Dagger Battery + Thor EM-i Super Hybrid, Geely New Energy has thrown out two "king bombs"
- A brief discussion on functional safety - fault, error, and failure
- In the smart car 2.0 cycle, these core industry chains are facing major opportunities!
- The United States and Japan are developing new batteries. CATL faces challenges? How should China's new energy battery industry respond?
- Murata launches high-precision 6-axis inertial sensor for automobiles
- Ford patents pre-charge alarm to help save costs and respond to emergencies
- New real-time microcontroller system from Texas Instruments enables smarter processing in automotive and industrial applications
- CBG201209U201T Product Specifications
- Keil compiles ADuC7029 and reports an error
- Technical Article: Optimizing 48V Mild Hybrid Electric Vehicle Motor Drive Design
- DIY an STLink V2.1
- Playing with Zynq Serial 18——[ex01] Trying out the first project based on Zynq PL
- Hangshun chip-HK32F103 xCxDxE data sheet
- How to lay digital and analog floors?
- The entire process of R&D and production of a chip
- pyWatch with BLE functionality and micropython
- Use the microcontroller DAC to output analog voltage and control the output voltage of the DC-DC circuit so that Vout=2*Vset. Please help me design the circuit