PIC microcontroller C language programming (1)

Publisher:MagicGardenLatest update time:2012-07-11 Source: 21ic Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere

Editor's note: In order to help technicians or engineers who have knowledge of PIC microcontroller assembly language quickly master the method of using C language to program PIC microcontrollers, this magazine has launched a series of articles entitled "PIC Microcontroller C Language Programming". The C language program examples given in the article are all executable and readers can quote them with confidence.

1. Assembly language and C language

Early single-chip computer programs were mostly written in assembly language. Programming in assembly language is direct and simple, and can effectively access and control various hardware devices, such as memory, I/O ports, etc. The target code is short, occupies less memory, has fast execution speed, and high statement efficiency. However, since assembly language is a machine-oriented language, single-chip computers from different manufacturers or different series of the same manufacturer often have different assembly language instruction systems, which is commonly known as "incompatibility". This has led to the phenomenon that people who are proficient in the assembly language of 51 single-chip computers cannot directly write assembly language source programs for PIC or other single-chip computers, and vice versa, as well as the problem of product upgrades and the difficulty of transplanting programs between different single-chip computers. Moreover, since assembly language is a low-level language using mnemonics, it has poor readability. When the source program has many functions and the program is long, even if comments are added, it will be difficult to read the program you wrote, not to mention modifying the program and adding functions.

At present, the application of single-chip microcomputers is becoming more and more widespread. Various semiconductor manufacturers continue to launch various high-, medium- and low-end single-chip microcomputer series to meet the needs of the market. The basic requirement of customers for designers of single-chip microcomputer systems is to select single-chip microcomputers that can meet product performance and cost requirements, and to develop intelligent products that fully meet market needs at the fastest speed. Programming in assembly language obviously cannot meet these requirements.

The biggest advantage of using C language to develop MCU system software is high code efficiency, intuitive software debugging, convenient maintenance and upgrade, high code reuse rate, and easy cross-platform code transplantation. Therefore, C language is increasingly widely used in MCU system design.

C language is a high-level language with the characteristics of a low-level language. The microcontroller programs originally written in various assembly languages ​​can be replaced by C language programs.

2. Characteristics of C language

The characteristics of C language can be summarized as follows.

1. Simple language

C is a small language with 32 keywords and 9 control statements. It has a simple expression method. You can construct powerful data types, statements and program structures by using standard methods. For example, ++ represents addition, one represents subtraction and operators are omitted.

2. Flexible and practical expression

C language provides a variety of operators and expression value methods. Problems can be expressed in a variety of ways, and its programming is more active and flexible. Its syntax restrictions are not too strict, and the programming freedom is large. For example, it can be used for integers, character data, and logical data.

3. Strong expressiveness

C language has a rich set of data structures and operators. It contains various data structures, such as integers, data types, pointer types, and union types, which are used to implement operations on various data structures. There are 34 operators in C language, covering a wide range. Flexible use of various operators can achieve extremely difficult operations.

C language can directly access the physical address of the hardware and perform bit operations, and has many advantages of both high-level and low-level languages.

It can be used to write system software as well as to develop application software, and has become a general programming language.

4. The target code generated by C language is of high quality

C language can describe problems faster than assembly language, requires less work, has better readability, is easier to debug, modify and port, and the code quality is comparable to assembly language.

5. Structured Programming

C language is a structured language that provides the control flow structure statements required for writing structured programs, such as for, while, do...while, lf...else, etc.; it uses functions as the basic unit of program design to achieve program modularity; its source files can also be divided into multiple source files, so that each source file can be compiled separately and then connected to generate executable target code (hex) files.

6. Portability

Assembly language is not portable. However, 86% of the code of C language compilers on different machines is common, so C language compilers are easy to port. A program written in C language in one environment can be ported to another completely different environment without modification or with slight modification.

3. Learning Methods

The most important thing when developing electronic products with PIC microcontrollers and programming in C language is to persist in learning without interruption. You should learn the grammatical rules of C language through various example programs. You must be proficient in the data type expression method, various operators, and various statement structures of C language.

It is best to memorize it. You need to learn how to use C functions to achieve the required functions. In fact, each C function is equivalent to a functional module, and a C function can achieve one function.

In addition, to develop PIC microcontroller application products with C language, you must have knowledge of PIC microcontroller assembly language. If you have mastered the method of writing PIC microcontroller source programs in assembly language, it is best to replace the successfully written PIC microcontroller assembly language source programs with C language source files one by one to experience the superiority of C language.

4. Simple C language program

In order to help readers enter the C language programming environment, we will introduce a simple C language program to everyone.

The following is a brief introduction to the basic knowledge of C language used in this program. More knowledge will be introduced in detail later. [page]

1. Main function main()

C language programs are generally composed of several functions. A function is a program segment that completes an algorithm for a certain function and is the basic unit of C language. Several functions that make up a program can be saved in one or several source program files, all of which have the extension C (the extension ASM for assembly language). A program must have and can only have one function named main, which is the main function main(). When the program is running, it always starts from the main function main().

2. C language function

The basic unit of a C language program is a function. A C language program must have and can only have one main function named main. The main function can call other functions, and other functions can also call each other. The called function can be a library function provided by the system or a function written by the programmer himself. For MCU (such as PIC microcontroller), most of the functions used are self-written functions. A function consists of two parts: a function header and a function body. The form of each function is the same.

(1) A function header consists of a function name (user-defined name), a function symbol ( ), which is a pair of parentheses, and a parameter list, also known as the function's formal parameter name and parameter description (which defines the formal parameter type).

The first two items are required, such as the main function main(), and the last two items are optional. Note: The function name can include the function type and function name, etc.

(2) The function body is enclosed by a pair of curly braces: {}, and the brackets contain several statements. These statements are of two types: one is the declaration statement, also known as the variable definition, which is used to define the variables used in the function; the other is the execution statement, also known as the execution part of the function.

Used to complete certain functions, namely algorithm processing. Note: Some functions do not have a variable definition part, but have several execution statements. In certain cases, there is neither a declaration part nor an execution part, such as:

Dump()

{}

This is an empty function. It does nothing, and it is still a valid function.

In addition, there must be a semicolon ";" at the end of each statement and data definition (no semicolon for #define...). Semicolons are the first basic symbols you encounter in the C language environment. We will further introduce the uses of these symbols in later articles.

(3) Assignment operator: The assignment sign “=” is the assignment operator.

There are three forms of assignment operators. Here we first introduce a simple assignment operator.

Format: variable=expression.

Function: Calculate the expression value first (some expressions already have results and do not need to be calculated), and assign the value to the variable on the left side of the equation. The assignment operator works in the order of "from right to left". For example:

PORTB=0X0 3

TRISB=0×0 0

TRISA=0X0 F (0X represents hexadecimal)

Perform the following operations respectively: send 0X0 3 on the right side of the equation to the port register PORTB on the left side of the equation, that is, the lower two bits of port B are high level and the remaining 6 bits are low level; send 0X0 0 to the direction register TRISB, that is, set port B to output; send 0×0 F to the direction register TRISA, that is, set the lower four bits of port A to input and the upper four bits to output.

3.PIC16F84A lighting circuit and C language program

The following is an example of controlling the on and off of any of the 8 LEDs connected to the port register PORTB of the PIC16F84A microcontroller to introduce the writing of the relevant C language program. The circuit is shown in Figure 1.

The author uses MPLAB tDE V7 40 integrated development environment and PICC compiler, and the generated C language source program is also called source file.

When writing C source programs, you need to define the hardware header file (also called include header file or header file). Because the standard register addresses and bit addresses that users often use are defined in the Pic h header file, according to the syntax rules of the C language compiler to compile source programs, when writing C language programs, you must use the #include statement to include this pic.h header file into your source program. That is, for PIC intermediate product microcontrollers, the beginning of the C language program is a fixed format #include. When the compiler compiles and processes the #include statement, it will copy the contents of pic.h to your source program, so that PICC will think that the port address of the standard register used by the user and the bit address of end 1:3 have been defined, and the source program will legally use these standard registers and their corresponding bits. About MPLAP IDE V7.4 and picc compiler will be introduced in detail later. [page]

4. Bit definition of PIC microcontroller port register

The bit definition of the PIC microcontroller port introduced here is something that needs to be memorized.

Taking PIRTB as an example, the bit definition (i.e. 8 bits) of the PIC microcontroller port register is written as follows:

5. Delay function

There are many equivalent ways to write the delay function (i.e., delay a certain value) in the C language of the PiC microcontroller. Here we introduce a simplest delay function. In the following text, we will introduce various delay functions in detail.

K in the function is a given integer value

6.C language program listing

The program list for lighting up 8 LEDs connected to PORTB of PIC16F84A microcontroller and lighting up the LEDs connected to positions 1, 2, and 6 respectively is as follows (source file name PIC01.C):

Note: The above is a complete C program that can execute Figure 1 LED lighting. It mainly consists of the bit definition of port register PORTB 1:3, the definition of delay function delay(); the main function main(), the delay function void delay() and various statements. [page]

The description text starting with the symbol “∥” on the third line of the C program is a comment, which can be written in one line or in multiple lines. Comments can be written anywhere in the program to help read and understand the program. Describe the relevant functions and precautions of the program, as well as explain related algorithms. Comments should be as simple as possible. Comments do not generate code during compilation. C programs can also use the content between the beginning of “ ” and the end of “ ” as comments, which is equivalent to the comment starting with the symbol “∥”.

The first line of the above program is the header file that uses the #include statement to start the bootstrap program.

The second line is the bit definition of PIC microcontroller PORTB, which refers to 8 bits here, that is, (&ddd)*8.

The third line is a comment on the bit definition of port register PORTB in the second line.

The fourth to sixth lines are the definitions of the three bits RBO, RB1, and RB6 of the port register PORTB, so that they can be assigned values ​​in subsequent programs.

The seventh line contains the definition comments for RBO, RB1, and RB6.

The eighth line is the definition of the delay function and the ninth line is the end of the function (see the relevant comments).

About the bit expression of port register. When writing PIC microcontroller source file in C language, once the port bit is defined, that is (taking port PORTB as an example); #daefine PORTBIT (ddd, bit) ((unsigned) (&ddd) 8+ (bie)), under this condition, the bit of port PORTB has two expressions, which are equivalent in C program. Take the 0 bit of PORTB as an example:

They are all equivalent. However, if PORTB_O is used in a bit definition, then PORTB_O should also be used in the assignment: or if PORT_O is used in a bit definition, then PORT_O should also be used in the corresponding assignment.

(to be continued)

Reference address:PIC microcontroller C language programming (1)

Previous article:A brief introduction to the production principle of a telephone amplifier using the PIC16C54 microcontroller
Next article:PIC microcontroller C language programming (2)

Latest Microcontroller Articles
  • Download from the Internet--ARM Getting Started Notes
    A brief introduction: From today on, the ARM notebook of the rookie is open, and it can be regarded as a place to store these notes. Why publish it? Maybe you are interested in it. In fact, the reason for these notes is ...
  • Learn ARM development(22)
    Turning off and on interrupts Interrupts are an efficient dialogue mechanism, but sometimes you don't want to interrupt the program while it is running. For example, when you are printing something, the program suddenly interrupts and another ...
  • Learn ARM development(21)
    First, declare the task pointer, because it will be used later. Task pointer volatile TASK_TCB* volatile g_pCurrentTask = NULL;volatile TASK_TCB* vol ...
  • Learn ARM development(20)
    With the previous Tick interrupt, the basic task switching conditions are ready. However, this "easterly" is also difficult to understand. Only through continuous practice can we understand it. ...
  • Learn ARM development(19)
    After many days of hard work, I finally got the interrupt working. But in order to allow RTOS to use timer interrupts, what kind of interrupts can be implemented in S3C44B0? There are two methods in S3C44B0. ...
  • Learn ARM development(14)
  • Learn ARM development(15)
  • Learn ARM development(16)
  • Learn ARM development(17)
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号