16. Composition of PIC microcontroller C language program
A complete PIC microcontroller C language source program should include: header file, variable definition, constant description, function definition, main function main(), several other function functions, various functional C statements, as well as defined functions and function bodies, comments and other parts.
Note: For intermediate or lower-level PIC microcontrollers, the header files are #include
The operation of a C program always starts from the main function main() (which can be directly observed through simulation), and the main function calls other functions, and other functions can also call each other, and the operation works in this way. C statements can be divided into sequential structures, selection structures, and loop structures according to their different execution methods. The sequential structure here means that the program executes one by one in the order of statements; the selection structure refers to the execution order selected by the program according to relevant conditions; the loop structure means that the program executes a section of the program according to the existence of a certain condition until the condition disappears. If the condition always exists, an infinite loop is formed.
1. Three expressions of delay function
When editing a large PIC microcontroller program in assembly language, it is generally divided into multiple program modules, and the subroutine of each module implements a specific function. When editing the program in C language, the function of the module is implemented by function, that is, the function is equivalent to the subroutine of assembly language. Below we use the example of delay function application to illustrate the basic composition format of PIC microcontroller C language program.
The delay function is a function that appears frequently in the source program of the PIC microcontroller, and there are many forms of delay functions with the same function. We choose three commonly used delay functions for discussion.
The three delay functions cited are all implemented by loop control statements - while, do_while and for.
(1) A delay function consisting of a for statement with formal parameters.
void delay(unsigned int k)
{
unsigned int i, j;
fir(i=0;i<=81;i++)
fir(j=0;j<=k;j++)
cONtinue;
}
The delay function consists of two for statements. The 81 in the first for statement is a constant set by the author (can be set arbitrarily) to increase the delay value; the k in the second for statement is the value given by the user when the main function main() calls delay(k) in the program. Different k values will result in different delay times. Therefore, the delay function can implement multiple different delay amounts in a C program, which is obviously much simpler than the assembly language delay subroutine. When the delay amount is required to be shorter, the functions of the two for statements in the delay function can be implemented with one for statement.
(2) A delay function consisting of a while loop statement with formal parameters.
Void deley(unsigned long int k)
{
Unsigned long int d=k;
While (--d)
{;
}
{
This delay function is simple and easy to remember. When in use, when the main function main() in the program calls delay(k), the user can give different k values to achieve multiple delay values.
(3) A delay function consisting of a do-while statement with formal parameters.
Void delay(unsigned long int k)
{
Unsigned int long j=o;
do {
j++;
}
While (j <= k);
j=o;
}
This delay function is simple and easy to remember. When using it, when the main function main() in the program calls delay(k), the user can give different k values to achieve multiple delay values.
It should be noted that the formal parameters in the delay function composed of the while loop statement and the do-while statement above do not necessarily use long integers (long ink).
⒉ Four C programs with the same circuit function but different forms
The following describes how to use the 8 LEDs connected to the PORTB port of the PIC16F84A microcontroller and use four C programs to control the LED lights of the port to illustrate the basic format and flexibility of editing C language programs. The circuit is shown in Figure 1 in the article "Microcontroller C Language Programming (1)" in the 9th issue of "Electronic Production" in 2009. The program flow is shown in Figure 64, which uses an infinite loop working mode.
Fig.64
(1) C program 1, file name is pic09.c, the listing is as follows:
#include
void delay(unsigned long int K)
// Delay function starts
{
unsigned int long j=0;
// Explanation statement
do
// Delayed execution statement composed of do-while
{
j++;
}
while(j<=K);
j=0;
}
main() // Start of main function
{
TRISB=0x00;
// Set PORTB to output
INTCON=0x00; // Disable all interrupts
PORTB=0x00; //RB port sends low level first
while(1) // Start of a permanent loop
{
PORTB=0x55;
//RB port externally connects LEDs 1, 3, 5, and 7 to light up
delay(45000);
// The lit LED will be turned off after 1 second delay
PORTB=0xAA;
//RB port externally connects LEDs 2, 4, 6, and 8 to light up
delay(98000);
// The lit LED turns off after a delay of 2 seconds
PORTB=0xFF; //RB port external LED all lights up
delay(155000);
// All LEDs will turn off after 3 seconds
}
}[page]
Note: a. In the above program, the delay function has a formal parameter K and consists of a do-while statement.
b. When the main function main() calls delay(k), its K is 45000 (1 second), 98000 (2 seconds), and 155000 (3 seconds).
c. The infinite loop when the LED light is on is completed by the while (1) statement.
(2) C program 2, file name is pic10.c, the listing is as follows:
#include
void delay( K ) // delay function
unsigned long int K;
// Shape parameter (k) Description
{
unsigned long int d=K;
// Explanation statement
while (--d)
// Delayed execution statement composed of while
{;
}
}
main() // Start of main function
{
TRISB=0x00
// Set PORTB to output
INTCON=0x00; // Disable all interrupts
PORTB=0x00; //RB port sends low level first
loop: // statement label (infinite loop)
PORTB=0x55;
//RB port externally connects LEDs 1, 3, 5, and 7 to light up
delay(37000);
// The lit LED will be turned off after 1 second delay
PORTB=0xAA;
//RB port externally connects LEDs 2, 4, 6, and 8 to light up
delay(74000);
// The lit LED turns off after a delay of 2 seconds
PORTB=0xFF; //RB port external LED all lights up
delay(111000);
// All LEDs will turn off after 3 seconds
goto loop; // Jump to loop
}
Note: a. In the above program, the delay function has a parameter k and consists of a while statement.
b. When the main function main() calls delay(k), k is 37000 (1 second), 74000 (2 seconds) and 1110000 (3 seconds) respectively.
c. The infinite loop when the LED lights up is completed by the goto unconditional transfer execution statement. Where loop is the statement label. Be cautious when using the goto statement. It is necessary to use the goto statement in a simple C program, but editing a complex C program structure will make the program less readable.
(3) C program 3, file name is pic11.c, the listing is as follows:
#include
unsigned int h; // unsigned integer variable
void delay(unsigned long int M)
// Delay function starts
{
unsigned int long i,j; // description statement
for(i=0;i<=81;i++)
// Consists of two for statements
for(j=0;j<=M;j++) // Delayed execution statement
continue; // continue the loop
}
main() // Start of main function
{
TRISB=0x00;
// Set PORTB to output
INTCON=0x00; // Disable all interrupts
PORTB=0x00; //RB port sends low level first
h=0; // assign 0 to h
do
// do-while statement starts the loop
{
PORTB=0x55;
//RB port externally connects LEDs 1, 3, 5, and 7 to light up
delay(500);
// The lit LED will be turned off after 1 second delay
PORTB=0xAA;
//RB port externally connects LEDs 2, 4, 6, and 8 to light up
delay(1000);
// The lit LED turns off after a delay of 2 seconds
PORTB=0xFF; // RB port external LEDs are all on
delay(1500);
// All LEDs will turn off after 3 seconds
h++; // h increments
}
while(h<=100); //h increments when the condition is not met
h=0; // assign 0 to h
return; // return
}
Note: a. In the above program, the delay function has a shape parameter M and consists of two for statements (it can be multiple for statements or one for statement).
b. When the main function main() calls delay(M), the values of M are 500 (1 second), 1000 (2 seconds) and 1500 (3 seconds).
c. The infinite loop when the LED light is on is completed by the do_while statement, and the 100 in while (h <= 100) can be any value greater than 0.
(4) C program 4, file name pic12.c, listing is as follows:
#include
void delay(unsigned long int M)
// Delay function starts
{
unsigned int long j; // Explanation statement
for(j=0;j<=M;j++)
// A delay statement consisting of a for statement
continue; //For condition is met and the loop continues
}
void light1() ;
//Declare RB port LED light function 1
void light2() ;
//Declare RB port LED light function 2
void light3() ;
//Declare RB port LED light function 3
main() // Start of main function
{
TRISB=0x00;
// Set PORTB to output
INTCON=0x00; // Disable all interrupts
PORTB=0x00; //RB port sends low level first
while(1) // Start of a permanent loop
{
light1(); // Call LED light function
delay(45000); //Call the delay function (1 second)
light2(); //Call LED light function 2
delay(95000); //Call the delay function (2 seconds)
light3(); //Call LED light function 3
delay(145000); //Call the delay function (3 seconds)
}
}
void light1( ) //LED light function 1
{
PORTB=0x55;
// RB port externally connected LEDs 1, 3, 5, 7 light up
}
void light2( ) //LED light function 2
{
PORTB=0xAA;
//RB port externally connects LEDs 2, 4, 6, and 8 to light up
}
void light3( ) //LED light function 3
{
PORTB=0xFF; //RB port external LED all lights up
}
[page]
Note: a. In the above program, the delay function has a parameter M and consists of a for statement.b. When the main function main() calls delay(M), the M values are 45000 (1 second), 95000 (2 seconds) and 145000 (3 seconds) respectively.
c. The infinite loop when the LED light is on is completed by the while statement.
d. The above programs are all completed with the LED function light1(); light2(); light3(). When the program is running, the main function main() calls the function and delay function of each LED. This method is necessary for editing complex C programs.
3. PIC microcontroller port bit definition
PIC microcontroller is a series of products, and the number of ports and the port bits are related to the specific model. For example, the ports of PIC16F877 are PORTA ~ PORTE, and the port bits are not all 8 bits. Its PORTA port has only 6 bits (RAO ~ RA5), and PORTAB, BORTC and PORTD are 8 bits, RB0 ~ RB7, RC0 ~ RC7, RD0 ~ RD7 respectively. When editing a C program, to access a certain bit of the above ports, you must first determine the address of this bit, which can be achieved through the @add (address) structure and the bit keyword, where @ is the address identifier and add (address) is the absolute address. Using the above address symbols, you can define the bits of the PIC microcontroller port, and then you can access the port bits at will. The following is a statement to define the bit of the PORTB port of PIC16F84A:
# dafine PORTBIT (add, bit) ((unsigned)
(&add)*8+(bit))
Satic bit PORTB_0@PORTBIT(PORTB,0);//define bit 0 of PORTB
Satic bit PORTB_1@PORTBIT(PORTB,1)//define 1 bit of PORTB
…
Static bit PORTB_7@PORTBIT(PORTB,7);//define PORTB bit 7
The "&" and "*" symbols are used as bitwise operators in C language, and 8 refers to 8 bits. When editing a PIC microcontroller C program, once a port, such as PORTB, is defined, its corresponding bit can also be written as RBO, RB1, RB2, RB3...RB7 to simplify the program code.
For the application of port bit definition, you can also refer to the program pic06.c in the article "Microcontroller C Language Programming (6)".
4. Application of LED digital display function
The following is a countdown and countdown C program example to illustrate the application of the LED digital display function display (x).
(1) Hardware circuit Use the PIC16F84A 4-digit LED digital display circuit (see Figure 3 and Figure 4 in the article "Microcontroller C Language Programming (4)") to make a 2-digit digital tube (the other two digits are not used) 99 to 0 countdown and countdown display. The countdown is in seconds and the countdown is in minutes. As long as there is a display function display(), the format of the counting and timing program is the same.
(2) The C source code listing for 99 to 0 (in minutes) is as follows. The program name is pic13.c.
#include
#define PORTAIT (add, bit) ((unsigned)
(&add)*8+(bit))
static bit PORT_2@PORTAIT (PORTA, 2);
//PORTA port definition
static bit PORT_3 @PORTAIT(PORTA,3);
static bit PORT_4 @PORTAIT(PORTA,4);
unsigned int x=0; // unsigned integer variable
void delay(unsigned long int k)
// Delay function starts
{
unsigned long int i; // description statement
for(i=0;i<=k;i++) //for execution statement
continue; // continue the loop
}
void display(unsigned int x)
// Digital tube LED display function
{
unsigned int d=5700,unit_bit,ten_bit;
// Unsigned integer variable D, ones and tens
unsigned char SEG7[10]={0xc0,0xf9,0xa4,
//7-segment code array from 0 to 9
0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
unit_bit=x%10; // PICC can recognize single digits
ten_bit=x/10%10; //picc can recognize ten digits
while(d>0) //while statement starts
{
PORTA=0x1F;
//PORTA port low output high level
PORTB=SEG7[unit_bit];
// Send the bit field code array to port B
RA3=0; //RA3 is assigned a value of 0, and the LED displays the unit digit
delay(200); // Delay for observation
RA3=1; //RA3 is assigned a value of 1, the LED unit digit is off
delay(2); // short delay
PORTB=SEG7[ten_bit];
// Send the 10-bit field code array to port B
RA2=0; //RA2 is assigned a value of 0, and the LED displays the tens digit
delay(200); // Delay to observe
RA2=1; //RA2 is assigned a value of 1, the LED tens digit is off
delay(2); // short delay
d--; //d self-decrement
}
}
void main() // Main function starts
{
TRISB=0x00; //Port B is all output
TRISA=0x10; //The lower 4 bits of port A are output
PORTB=0x40; // Output 0 to the low bit of port B
INTCON=0x00; // Disable all interrupts
PORTA=0x10; //Port A low bit output 0
x=99; // Assign the value 99 to the integer variable x
while (RA4) // Display start signal
{; //RA4 is 0, timing starts
}
while(1) // while loop statement starts
{
display(x); // Call the display function
x--; //x decreases
if(x==-1) // if x is decremented to -1
x=99; // assign 99 to x
}
}
Note: a. For the above C source program, you only need to change the unsigned integer variable d (unsignedint d) in the display function display(x) from 5700 to 95 to turn it into a countdown program from 99 to 0 in seconds, because the value of d determines the time of the unit digit displayed by the digital tube (it is unique).
b. If you want to use the above program and have strict requirements on the timing (minutes or seconds) accuracy, you can fine-tune the integer variable d value (57000) based on the standard clock to achieve high-precision minute or second timing.
c. All the C source programs of the above PIC microcontrollers are executable and can be used by beginners without any worries.
5. Questions about PIC microcontroller C language program SIM software simulation
In "Single-Chip Microcomputer C Language Programming (11)" and "Single-Chip Microcomputer C Language Programming (12)", the SIM software simulation process of C programs is introduced in detail. Software simulation is very useful for beginners to edit PIC single-chip microcomputer C language programs. It can not only observe the program running process, but also find problems in the program. Even professionals who have mastered PIC programming technology often use SIM software simulation to find problems in the program.
Conclusion
The three expressions of delay function, four C programs with the same circuit function but different forms, port bit definition, LED digital display function and C language program SIM software simulation problems introduced above are all basic knowledge for beginners to edit source programs in C language for PIC microcontrollers. You should understand the content and remember and recite it. On this basis, you should also think of some simple circuit functions independently and complete them in C language for PIC microcontrollers (must be a successfully compiled executable program). After that, you can further learn operators, structures, unions, A/D conversion, serial communication and other contents in C language. When learning, you should still aim to edit executable utilities.
Previous article:A three-bit tachometer based on PIC16 to measure ultra-low frequency
Next article:PIC microcontroller C language programming (14)
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
- MSP430F123 experience
- Please help me look at this program
- Level conversion
- Request gerber to pcb altium designer format
- What is PWM? Principle of PWM
- Answer questions to win gifts | World Peace Group NXP Solutions Show
- [CH563L Review] Part 3 Based on uCos, using FIFO algorithm to achieve zero wait, any baud rate FreeModbus RTU
- Electrical knowledge encyclopedia
- C6678 Learning - Interrupt Nesting
- The role and selection of input and output capacitors in power supplies