SlideShare a Scribd company logo
1 of 166
Embedded C / C + + language the essence of the article highlights
C / C + language struct deep exploration ........................................... ................................. 2
In C + + extern "C" meaning deep exploration ......................................... ............................... 7
Efficient C language programming recipe ........................................... .................................... 11
Want to become embedded programmers should know 0x10 basic problem
..................................... .................... 15
C language embedded systems programming practice ...........................................
................................ 22
One of the C language embedded systems programming practice: background papers
...................................... ...................... 22
C language embedded systems programming practice: software architecture articles
..................................... ................... 24
C language embedded systems programming practice: memory operations
...................................... .................... 30
C language embedded systems programming practice: screen operation ......................................
.................... 36
C language embedded systems programming practice of: keyboard operation
...................................... .................... 43
Six C language embedded systems programming practice: performance optimization
...................................... .................... 46
C / C + + the language void and the void pointer Deep Exploration ........................................
......................... 50
C / C + + language variable parameter list Deep Exploration ........................................
............................... 54
C / C + + array name and pointer difference between deep exploration ........................................
............................. 60
C / C + + programmers candidates common interview questions-depth analysis of (1)
.................................... .......................... 62
C / C + + programmers candidates common interview questions in-depth analysis (2)
.................................... .......................... 67
A well-known foreign companies face questions unraveling the ...........................................
........................... 74
C / C + + advanced features of the structure - the designated members of the median
.................................. ..................... 78
C / C + + in the near-instruction, far pointers and giant pointer .....................................
.............................. 80
From two classic questions about the C / C + + in the Commonwealth of the use of the (union)
................................. ..................... 81
Real-life experience of ARM-based embedded Linux transplant .........................................
....................... 83
Real-life experience of ARM-based embedded Linux transplantation (1) - Basic Concepts
.................................. ......... 83
ARM-based embedded Linux transplantation real experience (2) - BootLoader
................................... ...... 96
Real-life experience of ARM-based embedded Linux transplantation (3) - the operating system
.................................. ........ 111
ARM-based embedded Linux transplantation real experience (4) - Device Driver
.................................. ........ 120
ARM-based embedded Linux transplantation real experience (5) - Application Examples
.................................. ........ 135
Layman Linux device driver programming ............................................. .......................... 144
1.Linux kernel module ............................................. ................................. 144
2. Character device driver ............................................ ............................... 146
3. Concurrency control device driver .......................................... ............................. 151
4. Equipment blocking and non-blocking operation ......................................... ............................
157
2
C / C + language struct Deep Exploration
Source: PConline author: Song Baohua
1. Struct huge role
Faced with a large C / C + + program, look on the use of the struct we can programming through
its writers
Inspection for evaluation. Because a large C / C + + program is bound to involve some (or even
large) the combination of data structures, these nodes
Isomers can be the original sense of belonging to a whole data together. To some extent, it will
not use the struct, how to use it
struct is the difference between a sign of whether the developers with a rich development
experience.
Is not a simple network protocol, communication control, embedded systems, C / C + +
programming, we often want to send a stream of bytes (char
Up a whole array), but the combination of a variety of data, its manifestations is a structure.
Inexperienced developers often need to send the content in order to save char array through a
pointer offset
The method of transmission network packets, and other information. Doing programming
complex, error-prone, and are subject to change once the control methods and communication
protocols, procedures
Will be carried out in great detail modifications.
An experienced developer flexibility in the use of the structure, to give an example, the
hypothetical network or control protocol needs to send three
Text, its format were packetA, packetB, packetC:
struct structA
{
int a;
char b;
};
struct structB
{
char a;
short b;
};
struct structC
{
int a;
char b;
float c;
}
Excellent programmers designed such that the message sent:
struct CommuPacket
{
3
int iPacketType; / / packet type flag
union / / every time you send three packets using the union
{
struct structA packetA; struct structB packetB;
struct structC packetC;
}
};
Performing packet transmission, transmitted directly a whole struct CommuPacket.
Assume that the send function prototype is as follows:
/ / PSendData: first address to send a stream of bytes, iLen: To send a length
Send (char * pSendData, unsigned int iLen);
The sender can directly call send the the struct CommuPacket an instance sendCommuPacket:
Send ((char *) & sendCommuPacket, sizeof (CommuPacket));
Assume that the receiver function prototype is as follows:
/ / PRecvData: first address to send a stream of bytes, iLen: To receive length
/ / Return value: the number of bytes actually received
unsigned int Recv (char * pRecvData, unsigned int iLen);
Receiver can be directly called as follows and the received data is saved in struct CommuPacket
an instance recvCommuPacket:
Recv ((char *) & recvCommuPacket, sizeof (CommuPacket));
Then determine the type of message and dealt with accordingly:
switch (recvCommuPacket. iPacketType)
{
case PACKET_A:
... / / A class packet processing
break;
case PACKET_B:
Packet processing ... / / B class
break;
case PACKET_C:
Packet processing ... / / C class
break;
}
Most noteworthy in the above procedure
Send ((char *) & sendCommuPacket, sizeof (CommuPacket));
Recv ((char *) & recvCommuPacket, sizeof (CommuPacket));
In the cast: (char *) & sendCommuPacket, (char *) & recvCommuPacket address of first, and
then converted to a char pointer to
This can directly to handle byte stream function.
Using this mandatory type of transformation, we can also facilitate the preparation of the
program, for example, in which the memory initialization of sendCommuPacket can
Like calling the standard library function memset ():
memset ((char *) & sendCommuPacket, 0, sizeof (CommuPacket));
2 members of the struct alignment
Intel, Microsoft and other companies have a similar interview questions:
# Include <iostream.h>
4
# Pragma pack (8)
struct example1
{
short a;
long b;
};
struct example2
{
char c;
example1 struct1;
short e;
};
# Pragma pack ()
int main (int argc, char * argv [])
{
example2 struct2;
cout << sizeof (example1) << endl;
cout << sizeof (example2) << endl;
cout << (unsigned int) (& struct2.struct1) - (unsigned int) (& struct2) << endl;
return 0;
}
Asked enter the result of the program is it?
The answer is:
8
16
4
Do not understand? Still do not understand? The following eleven to:
The 2.1 naturally on sector
struct is a composite data type, its constituent elements, both variables can be basic data types
(such as int, long, float, etc.) can also
Data unit complex data types (such as array, struct, union, etc.). For the structure, the compiler
will automatically alignment of the member variables
To improve the operation efficiency. By default, the compiler to allocate space for each member
of the structure of their natural community (natural alignment) conditions. Each
Members in accordance with their order of declaration are sequentially stored in memory, the
same as the address of the first member and the entire structure of the address.
The natural logarithm sector (natural alignment) that default alignment is a member of the largest
members of the structure size aligned.
For example:
struct naturalalign
{
char a;
short b;
char c;
};
In the above structure, size maximum is short, its length is 2 bytes, and thus the the char
members in the structure a, c are 2 units aligned,
sizeof (naturalalign) results equal to 6;
If read as follows:
struct naturalalign
5
{
char a;
int b;
char c;
};
The result is apparently to 12.
2.2 specified on the sector
In general, by the following method to change the default on the boundary conditions:
• Use the directive # pragma pack (n), the compiler will be aligned in accordance with the n
bytes;
• Use directive # pragma pack (), to cancel custom byte alignment.
Note: If you specify # pragma pack (n) n is greater than the size of the largest member in the
structure, it does not work, the structure
Still on the sector in accordance with the maximum size of members.
For example:
# Pragma pack (n)
struct naturalalign
{
char a;
int b;
char c;
};
# Pragma pack ()
When n alignment for 4,8,16, the sizeof (naturalalign) of results is equal to 12. And when n is 2
, Play a role, such that sizeof (naturalalign) result is 6.
VC + + 6.0 compiler, we can specify its sector (see Figure 1), and its mode of operation to select
projetct>
the setting> C / C + + menu, specified in the struct member alignment you want on the sector.
Figure 1 is specified on the sector in the VC + + 6.0
6
Further, through __attribute ((aligned (n))) can also make the role of a member of the structure
body is aligned in the N-byte boundary, but
Is it less, and thus does not explain in detail.
2.3 interview questions answers
At this point, we can Intel, Microsoft interview questions comprehensive answer.
Second line # pragma pack (8) program specified on the sector, but due to the members of the
struct example1
size 4 (long variable size, 4), so the struct example1 still 4 bytes on the sector, struct example1
size
8, line 18 output;
struct example2 contains struct example1, the maximum size itself contain simple data members
of 2 (short
Variable e), but because it contains a struct example1, and struct example1 largest member size
4, struct
the example2 also should be four pairs of circles, # pragma pack (8) is specified on the boundary
of the struct example2 does not work, it is on line 19
The output result is 16;
As members of the struct example2 to 4 units of the sector, its char variable c should
complement the three empty and subsequently is
Members struct1 memory space, 20 lines of output.
C and C + + between struct deep distinction
In C + + language struct with the function of the "class" with the keyword class difference is that
the members of the struct variable
And function the default access permissions for the public, but class is private.
For example, the definition of the struct class and class categories:
struct structA
{
char a;
...
}
class classB
{
char a;
...
}
Then:
structA a;
a.a = 'a'; / / access public members, legal
classB b;
b.a = 'a'; / / access private members, illegal
Many papers wrote here that has been given a C + + struct and class all differences, but in fact
not the case, another point
It needs to be noted is:
Struct in C + + is fully compatible with maintaining a struct in C (which is consistent with the C
+ + original intention - a better c ")
Thus, the following operation is legitimate:
/ / Define the struct
struct structA
{
char a;
char b;
int c;
};
7
structA a = {'a', 'a', 1}; / / defined directly given initial
That the struct can be defined when directly to the {} of its members variable initial values, and
the class is not in the classic bibliography
Thinking C + + 2nd edition of this point is emphasized.
4. Struct Programming Note
Take a look at the following program:
1. # Include <iostream.h>
2. Struct structA
3 {
4. Int iMember;
5. Char * cMember;
6};
7. Int main (int argc, char * argv [])
8 {
9. StructA instant1, instant2;
10. Char c = 'a';
11. Instant1.iMember = 1;
12. Instant1.cMember = &c;
13. Instant2 = instant1;
14. Cout << * (instant1.cMember) << endl;
15. * (Instant2.cMember) = 'b';
16. Cout << * (instant1.cMember) << endl;
17. Return 0;
}
14 lines of output: a
16 lines of output: b
Why? 15 line instant2 modifications change the value of a member instant1!
The reason is that the line 13 instant2 = instant1 assignment statement is variable one by one
copy, which makes instant1 and
the cMember in instant2 point to the same piece of memory, which the modification of instant2
is on instant1 modify.
In the C language, when the structure pointer members, we must pay attention to whether the
assignment statement in the two instances
Pointer members point to the same piece of memory.
In the C + + language, when the structure pointer members, we need to rewrite the the struct
copy constructor and "="
Operator overloading.
In C + + extern "C" meaning deep exploration
Author: Song Baohua e-mail: 21cnbao@21cn.com Source: Pacific Internet
1 Introduction
C + + language originally create "a better C", but this does not mean that the C + +, C-like
language of global variables and functions
Used to compile and link mode is identical to the C language. As a desire language compatible
with C, C + + retains part of the procedural language
Introduction characteristics (called "not completely object-oriented"), and thus it does not belong
to any kind of global variables and functions can define the world.
However, C + +, after all, is an object-oriented programming language, in order to support
function overloading, C + + global function approach with C
There are obviously different.
Speaking from the standard header files
A company had given a face questions as follows:
Interview questions
Why the standard header files have similar structures below?
# Ifndef __ INCvxWorksh
# Define __ INCvxWorksh
# Ifdef __ cplusplus
extern "C" {
# Endif
/ * ... * /
# Ifdef __ cplusplus
}
# Endif
# Endif / * __ INCvxWorksh * /
Analysis
Clearly, the role of compile macros in the header file # ifndef __ INCvxWorksh # define __
INCvxWorksh The # endif "
Prevent the header files are repeated references.
Then
# Ifdef __ cplusplus
extern "C" {
# Endif
# Ifdef __ cplusplus
}
# Endif
The role, then what is it? In the following, we will one by one.
Deep Inside extern "C"
extern "C" contains a double meaning, literally can be obtained: First, it modified target "extern";
Second,
It modified target is "C". Let's take a detailed interpretation of the meaning of a two-fold.
(1) is defined function or variable extern "C" extern type;
extern C / C + + language shows that the scope of functions and global variables visibility
keywords, the keyword tells the compiler,
Its declaration of functions and variables can be used in the module or modules. Remember, the
following statement:
extern int a;
Just a variable declaration is not in define variables, not for a distributed memory space. Variable
a for all modules
Can only be defined as a global variable, otherwise there will be a connection error.
Typically, the module in the module header files available to other modules referenced in
function and global variable declaration extern keyword.
For example, if the global variables and functions defined in the module A module B For
reference only contains the the module A header files can. In this way,
Call function in module A module B in the compilation phase, module B can not find the
function, but it does not error; it will
Find this function module A compiler generates object code from the connection phase.
The keywords extern corresponding static, global variables and functions can only be modified
in the module. Therefore, a
Function or variable may only use this module, which can not be modified extern "C".
(2) is modified extern "C" variables and functions in accordance with the compilation and
linking of the C language way;
Compile not add extern "C" declaration
9
First, take a look at C + +, how to compile the C-like function.
As an object-oriented language, C + + supports function overloading, procedural language C is
not supported. Function is C + + compiler in character
No. library name with the C language is different. For example, assume that a function
prototype:
void foo (int x, int y);
The function C compiler symbol library name _foo, C + + compiler will generate the like
_foo_int_int like
Name (different compiler may generate a different name, but use the same mechanism to
generate a new name called "mangled
name "). _foo_int_int this name contains the name of the function, the number of function
parameters and the type of information, C + + is to rely on this mechanism to
Function overloading. For example, in C + +, the function void foo (int x, int y) void foo (int x,
float y)
The compiler generates the symbol is not the same, the latter _foo_int_float.
Similarly, variables in C + + in addition to support for local variables, but also support the class
member variables and global variables. Class into the user program
Member variable may be global variables of the same name, we have to differentiate. " Essence,
the compiler during compile time, similar to the processing of the function,
Also took a unique name for the class variables, global variable name of the name with the same
name in the user program.
Connection not add extern "C" declaration
Assumptions in module A, C + + header files as follows:
/ / The module A header file moduleA.h
# Ifndef MODULE_A_H
# Define MODULE_A_H
int foo (int x, int y);
# Endif
Module B refer to the function:
/ / Module B file moduleB.cpp
# Include "moduleA.h"
foo (2,3);
In fact, looking _foo_int_int the target file moduleA.obj connection phase, the connector will be
generated from the module A such
The sign!
Add extern "C" statement after compiling and linking
Plus extern "C" declaration module A header file becomes:
/ / The module A header file moduleA.h
# Ifndef MODULE_A_H
# Define MODULE_A_H
extern "C" int foo (int x, int y);
# Endif
Still call module B implementation file foo (2,3), the result is:
(1) Module A compiler generates object code for foo, not its name, the special treatment, the use
of the C language;
(2) connector in object code module B looking for foo (2,3) called looking for is unmodified
symbol name _foo.
Declared in module A function foo extern "C" type, and module B contains extern int foo (int x,
int y), then the module the B module A can not be in the function; vice versa.
Therefore, can be summarized in one sentence extern "C" the real purpose of the statement (in
any language any grammatical characteristics of the birth
Are not arbitrary and, from the real world, demand-driven. We think you can not only stay in this
language is how
To do, but also to ask why it is you want to do, what the motive is, so that we can be more in-
depth understanding of the many issues):
C + + and C and other languages mixed programming.
Understand the motives of the establishment of the C + +, extern "C" We turn next to a concrete
analysis of the extern "C" usually use skills.
4.extern "C" idiom
10
(1) reference functions and variables in C language, C + + contains the C language header files
(assuming cExample.h), into
Line following treatment:
extern "C"
{
# Include "cExample.h"
}
Header files in the C language, its external function can only be designated as extern type extern
"C" statement is not supported in the C language,
Compiler syntax errors. C file contains the extern "C" will appear.
Author written in C + + source code reference to the C function examples project contains three
files are as follows:
/ * C language header file: cExample.h * /
# Ifndef C_EXAMPLE_H
# Define C_EXAMPLE_H
extern int add (int x, int y);
# Endif
/ * C language file: cExample.c * /
# Include "cExample.h"
int add (int x, int y)
{
return x + y;
}
/ / C + + files, invoke add: cppFile.cpp
extern "C"
{
# Include "cExample.h"
}
int main (int argc, char * argv [])
{
add (2,3);
return 0;
}
If C + + calls a C language prepared by the DLL when the DLL header file declares the interface
function should be added extern "C"
{}.
(2) The reference in C C + + language functions and variables, C + + header files need to add
extern "C", but not in the C language
Declared extern "C" can directly reference the header files should only be declared as C file in C
+ + as defined in extern "C" function
The extern Type.
The author to write the C reference C + + source code of the function in the example project
contains three files are as follows:
/ / C + + header files cppExample.h
# Ifndef CPP_EXAMPLE_H
# Define CPP_EXAMPLE_H
extern "C" int add (int x, int y);
# Endif
/ / C + + implementation file cppExample.cpp
# Include "cppExample.h"
int add (int x, int y)
11
{
return x + y;
}
/ * C file cFile.c
/ * This will compile error: # include cExample.h "* /
extern int add (int x, int y);
int main (int argc, char * argv [])
{
add (2, 3);
return 0;
}
If the in-depth understanding of the extern "C" as set forth in the three play a role in the
compilation and linking stages, will be able to truly understand this section
Elaborated from C + + reference C functions and C reference to the C + + function usage.
Section 4 gives the example code, you need to pay special attention to each
Details.
Efficient C language programming recipe
Write simple and efficient C code, which is a goal pursued by many software engineers. In this
paper, some experience and experience in the work to do related to the exposition, wrong place
Please
Advise.
1 recruit: space for time
The biggest contradiction in the computer program is a contradiction of space and time, then
reverse thinking from this perspective, to consider the efficiency of the program, we will have to
solve
Problem
First strokes - space for time.
For example: string assignment.
Method A, the usual way:
# Define LEN 32
char string1 [LEN];
memset (string1, 0, LEN);
strcpy (string1, "This is an example!!"
Method B:
const char string2 [LEN] = "This is an example!"
char * cp;
cp = string2;
(When using the direct pointer to the operation.)
As can be seen from the above example, the efficiency of the A and B can not be compared.
Under the same storage space, B directly use the pointer can be operated, and A needs to call
The two characters function to complete. B's disadvantage flexibility A good. A better flexibility
in a string content needs to change frequently;
If Method B, stored many strings, though they take a lot of memory, but to obtain a high
efficiency of program execution.
Real-time requirements of the system, memory, there are some that I recommend you use the
tricks.
The edge of the tricks trick - macro function rather than a function. The following are examples:
Method C:
# Define bwMCDR2_ADDRESS 4
# Define bsMCDR2_ADDRESS 17
int BIT_MASK (int_bf)
{
return ((IU << (bw # # _bf)) -1) << (bs # # _bf);
}
void SET_BITS (int_dst, int_bf, int_val)
{
_dst = ((_dst) & ~ (BIT_MASK (_bf))) I 
(((_val) <<< (Bs # # _bf)) & (BIT_MASK (_bf)))
}
SET_BITS (MCDR2, MCDR2_ADDRESS, RegisterNumb
er);
Method D:
# Define bwMCDR2_ADDRESS 4
# Define bsMCDR2_ADDRESS 17
# Define bmMCDR2_ADDRESS BIT_MASK
(MCDR2_ADDRESS)
# Define BIT_MASK (_bf) (((1U << (bw # # _bf)) -1) <<
(Bs # # _bf)
# Define SET_BITS (_dst, _bf, _val) 
((_dst) = ((_dst) & ~ (BIT_MASK (_bf))) I
(((_val) << (Bs # # _bf)) & (BIT_MASK (_bf))))
SET_BITS (MCDR2, MCDR2_ADDRESS, RegisterNumb
er);
The difference lies in the function and macro function, a macro function takes up a lot of space, while
the function takes time. We want to know, the function call is to use the system
Stack to save the data, if the compiler stack checking option, usually in the head of the function will be
embedded in some assembly statement to check the current stack; same time, CPU should
Save and restore the current scene in the function call, push and popped operations, function calls, so
need some CPU time. The macro function does not exist this asked
Problems. Macro function only as a pre-written code embedded in the current program does not
produce the function call, so it is just taking up space in the frequent calls to the same macro
Function when the phenomenon is especially prominent.
D method is the best I have seen set manipulation functions, is part of the ARM's source, a lot of
features in just three lines, covering almost all the
Bit manipulation functions. C method is a variant of the taste of them need to carefully understand.
2 strokes: mathematical methods to solve the problem
Now our interpretation of the second measure of efficient C language - mathematical methods to solve
the problem.
Mathematics is the mother of the computer, there is no basis and foundation of mathematics, there
would be no development of a computer program, using some mathematical methods will program
The efficiency of the implementation of magnitude improvement.
Following are examples, and, of 1 to 100,.
Method E
int I, j;
Method F
int I;
13
for (I = 1; I <= 100; I + +) {
j + = I;
}
I = (100 * (1 +100)) / 2
This example use case is a mathematical impressed me the most, my hungry computer first teacher test
me. I was only in third grade, but unfortunately I do not know with
Formula NX (N +1) / 2 to solve this problem. Method E loop 100 times before solving the problem, that
is at least 100 assignment, 100 judgment, 200
Additions (I and j); Method F only with an addition, a multiplication, division 1. The effect of natural self-
evident. So now when I was editing program
More brains to find rules to maximize the power of mathematics to improve the efficiency of the
program running.
3 strokes: Use-bit operating
Efficient C language to write the third measure - use bit operation to reduce the division and modulo
arithmetic.
In the computer program, the data bit is the smallest unit of data that can operate, in theory, can be
used "calculation" to complete all of the operations and operation. Usually a bit operation
Is used to control the hardware, or do the use of the data conversion, however, can effectively improve
the efficiency of running flexible bit operating. Example table is as follows:
Method G
int I, J;
I = 257/8;
J = 456% 32;
Method H
int I, J;
I = 257 >> 3;
J = 456 - (456 >> 4 << 4);
Literally as if H ratio G trouble a lot, but a closer look at the assembly code will understand the method
G is called basic the modulo functions and the division function
Both function calls, there are a lot of assembly code and register to participate in computing; method H
is only a few words related to the compilation of the code more concise and efficient. Of course,
Due to the different compiler, efficiency may not differ much, However, I am currently experiencing MS
C, ARM C point of view, the efficiency gap is still not small. Related compilation
Code is not listed here.
Is transported 用这招 Note that, the problems that may arise because of the different CPU. For
example, on a PC 用这招 programs written through debugging, and on the PC,
When transplanted into a 16-bit machine platform may generate code hidden. So only in certain
advanced before you can use this trick.
4 strokes: compilation of embedded
Efficient C language programming nirvana the fourth trick - embedded compilation.
"The eyes of the people familiar with assembly language, C language program is garbage." Although this
view is extreme, but it has its reason. Assembly language is valid
The highest rate of computer language, however, can not rely on it to write an operating system? So, in
order to get the high efficiency of the program, we had to adopt alternative side
Law - embedded compilation, mixed programming.
For example the array assignment to array each byte match. char string1 [1024], string2 [1024];
14
Method I
int I;
for (I = 0; I <1024; I + +)
* (String2 + I) = * (string1 + I)
Method J
# Int I;
for (I = 0; I <1024; I + +)
* (String2 + I) = * (string1 + I);
# Else
# Ifdef_ARM_
_asm
{
MOV R0, string1
MOV R1, string2
MOV R2, # 0
loop:
LDMIA R0!, [R3-R11]
STMIA R1!, [R3-R11]
ADD R2, R2, # 8
CMP R2, # 400
BNE loop
}
# Endif
Method I is the most common method, used 1024 cycles; method J is different depending on the
platform a distinction between the ARM platform, embedded assembler only 128
Cycles to complete the same operation. There are friends will say, why not use the standard memory
copy function? This is because in the source data may contain data for
0 bytes, so the standard library functions will be ahead of the end and will not complete the requested
operation. This routine is typically applied to the LCD data copy process. Root
According to different CPUs, skilled use of the embedded assembler, can greatly improve the efficiency
of program execution.
Although this is nirvana, but will pay a heavy price if easily use. It is embedded assembler, it limits the
portability of the program, the program in
Different platforms transplant process, Crouching Tiger, Hidden Dragon, and danger! Meanwhile, the
tricks are also contrary to the idea of modern software engineering only in compelling circumstances
Can be used. Remember.
Highly efficient programming using C language, my experience. Initiate this article, please experts to
share their experience. I hope to give a better
Method we can work together to improve our programming skills.
Taken from the microcontroller and embedded systems applications 2003.9
15
Want to be 0x10 basic questions embedded programmers should know
- | Endeaver 2006-3-8 16:16:00
The C language test is a necessary and effective method of recruitment of embedded systems
programmers. All these years, I participate in both organized this test, in this process I realized that
these measurements
The test can provide a lot of useful information with the interviewer and the interviewee, setting aside
the pressure of the interview aside, this test is quite interesting.
From the perspective of the interviewee, you learn a lot about the title or the invigilator. This test is only
a question to show their knowledge of the details of the ANSI standard, rather than technical skills
Design? This stupid question? To know the result of the ASCII value of a character. These problems the
study focused on the ability of system calls and memory allocation strategy it? This indicates that the
topic
May spend time on the PC and not on the embedded system. If the answer to any questions is "yes",
then I know I have to seriously consider whether I should do the job.
From the interviewer's perspective, a test may be able to reveal several qualities of the candidate: the
most basic, you can understand the the candidate C language level. Anyway, look at how this man
Answered that he would not issue full of interesting. Candidate in good intuition to make informed
choices, or just guessing blindly? When the candidate stuck on an issue is to find an excuse, or the
performance of
Genuine curiosity on the issue, see this as the opportunity to learn it? I find this information as useful as
their test scores.
With these in mind, I decided to live out some real hope these headaches exam Questions and Answers
for embedded systems, looking for work is to give people a little help. These issues are these annual real
Interpersonal encounter. Some of these questions is difficult, but they should be able to give you a little
inspiration.
This test is suitable for candidates of different levels, the most junior level of the candidate's results will
be poor, experienced programmers should have good results. Some ask in order to allow you to be able
to decide
Preference of questions, each question has not been assigned scores If you choose exam for you, your
own scores assigned by you mean.
Preprocessor (Preprocessor)
Preprocessor directives # define statements in a constant used to indicate how many seconds in a year
(ignoring leap years)
# Define SECONDS_PER_YEAR (60 * 60 * 24 * 365) UL
I would like to see a few things:
•; basic knowledge of the # define syntax (for example: You can not end with a semicolon, the use of
braces, etc.)
•; know preprocessor will calculate the value of the constant expression directly write the year you how
to calculate the number of seconds rather than the actual value calculated clearer price.
•; aware of this expression will make a 16-bit machine integer overflow - so use to the long integer
symbol L, tells the compiler that this constant is the long integer.
•; if you used in your expressions UL (unsigned long), then you have a good starting point. Remember,
first impressions are very important.
Write a "standard" macro MIN, this macro input two parameters and returns the smaller one.
# Define MIN (A, B) ((A) <= (B)? (A): (B))
This test is designed for the purpose of the following:
•; basic knowledge of the # define macro applications. This is very important, because until Embedding
(inline) operator becomes part of the standard C macro is convenient to generate only embed code
The law, in order to achieve the required performance for embedded systems, embedded code often
must.
•; triple conditional operator knowledge. This operator exists in C language because it allows the
compiler to produce more optimized code than if-then-else, it is very important to understand this
usage.
•; understand the macro Carefully parameters in parentheses up
•; I also use this to begin to discuss the macro side effects, such as: What happens when you write the
following code?
least = MIN (* p + +, b);
What is the purpose of the preprocessor directive # error?
If you do not know the answer, see Reference 1. This problem it is useful to distinguish between a
normal folks and the nerds. Only the nerds read Appendix C language textbooks to find out about
The answer to this problem. Of course, if you are not looking for a nerd, then the candidate better hope
that they do not know the answer.
Infinite loop (Infinite loops)
4. Embedded systems often use to an infinite loop, how kind of you to write in C infinite loop?
16
The problem with a few solutions. My preferred solution is:
while (1)
{
?}
Some programmers prefer the program as follows:
for (; ;)
{
?}
The way to achieve that embarrassed me, because this syntax does not exactly how the matter in the
end. If a candidate gives this as a solution, I will use this as an opportunity to explore their
The basic principle of doing so. If their answer is: "I was taught to do so, but did not think why." This will
leave a bad impression.
The third option is to use goto
Loop:
...
goto Loop;
Candidates who are given the above program, which shows that he is an assembly language
programmer (which is probably a good thing) or he want to get into a new field of BASIC / FORTRAN
programmers.
Data declarations (Data declarations)
Variable a following definition is given
a) an integer (An integer)
b) a pointer to an integer pointer (A pointer to an integer The)
c) a pointer to a pointer to a pointer, it points to the pointer is pointing to an integer (A pointer to a
pointer to an intege) r
d) an array of 10 integer (An array of 10 integers)
e) an array of 10 pointers, the pointer is a pointer to an integer number. (An array of 10 pointers to
integers)
f) a pointer to a pointer to an array of 10 integers (A pointer to an array of 10 integers)
g) a pointer to a function, the function takes an integer argument and returns an integer (A pointer to a
function that takes an integer as an argument
and returns an integer)
h) an array of 10 pointers, the pointer to a function, the function is an integer argument and returns an
integer (An array of ten pointers to functions t
hat take an integer argument and return an integer)
The answer is:
a) int a; / / An integer
b) int * a; / / A pointer to an integer
c) int ** a; / / A pointer to a pointer to an integer
d) int a [10]; / / An array of 10 integers
e) int * a [10]; / / An array of 10 pointers to integers
f) int (* a) [10]; / / A pointer to an array of 10 integers
g) int (* a) (int); / / A pointer to a function a that takes an integer argument and returns an integer
h) int (* a [10]) (int); / / An array of 10 pointers to functions that take an integer argument and return an
integer
It is often claimed that there are several issues here that a brief look at the book in order to answer the
question, I agree with this. When I wrote this article, in order to determine the correctness of the
syntax, I do check
Look book. But when I interview, I expect to be asked this question (or similar). Since the time of the
interview, I'm sure I know the answer to this question.
Candidates who do not know all the answers (or at least most of the answers), then there would be no
for the interview and to prepare for the interview if the interviewer does not prepare, then he can
What are the preparations?
17
Static
What is the role of the static keyword?
This simple question is rarely answered completely. Three distinct role in the C language, the keyword
static:
•; in the body of the function, a is declared as static variables in this function is called to maintain its
value unchanged.
•; within the module (but function in vitro), a declared as static variables within the module with a
function to access, but not access other functions outside the module. It is a local global variables
Amount.
•; within the module, a declared as static function can only be called by other functions within this
module. That is, this function is limited to use in the local declaration module within.
Most candidates correctly answered the first part correctly answer the second part, the same few
people understand the third. This is a candidate serious drawback, because he apparently
Do not know the benefits and importance of localization data and code range.
Const
7. Keyword const mean?
I just heard the interviewer said: "const means constant," I know I'm dealing with an amateur. Dan Saks
last year, has been completely in his article summarizes the const
All usage ESP (translator: Embedded Systems Programming) every reader should be very familiar with
the const can do and can not do if you never
Read the article say that const means "read-only" as long as you can. Although the answer is not entirely
the answer, but I accept it as a correct answer. (If you want to know
More detailed answer, carefully read the the Saks article. )
If the candidate correctly answer this question, I will ask him an additional problem:
The following statements are What does it mean?
const int a;
int const a;
const int * a;
int * const a;
int const * a const;
/ ****** /
The role of the first two is the same, a is a constant integer. The third means a is a pointer to a constant
integer pointer (that is, the integer is not modified, but the pointer). The fourth
Mean a often is a pointer to an integer pointer (ie, the integer pointer can be modified, but the pointer
is not modified). Last a point often means a whole
Type the number of regular pointer (that is, the integer pointer can not modify the pointer itself may not
be modified). If the candidate correctly answer these questions, then he gave me to stay
Under a good impression. Incidentally, perhaps you might ask, even without the keyword const, or can
easily write the correct function of the program, then why is so dear to shut
Key word const it? I have the following several reasons:
•; role of the const keyword is very useful for people to read your code to convey information, in fact,
declare a parameter for the constant parameters of the user application purpose is to tell. If
You have to spend a lot of time to clean up the garbage left by other people, you will quickly learn to
appreciate this extra piece of information. (Of course, know how to use const, rarely leave the mess for
others to clean
Reasonable. )
•; through some additional information to the optimizer, use the const keyword may be able to
generate more compact code.
•; reasonably use the const keyword allows the compiler to naturally protect those who do not want to
change the parameters, and code changes to prevent unintentional. In short, this can reduce bug
Appear.
Volatile
8 What are the implications of keyword volatile? Given three different examples.
Defined as volatile variable is that this variable may be unexpectedly changed, so the compiler will not
go assuming the value of this variable. Accurate to say is that the optimizer used in
This variable must always be carefully re-reads the value of this variable, instead of using the backup
stored in the register. Here are a few examples of the volatile variable:
18
•; the parallel device hardware registers (such as: Status Register)
•; an interrupt service routine access to non-automatic variables (Non-automatic variables)
•; multi-threaded applications, shared by several task variables
People do not know the answer to this question will not be hired. I think this is a distinction between C
programmer and embedded systems programmers the basic problem. The guys often engage
embedded with hardware interrupt
The RTOS and so dealing with all of these require volatile variables. Do not know how volatile will bring
disaster.
Assumption that the interviewee correctly answered a problem (doubt whether it will be the case), I will
probe a little deeper, look at this guy is not straight is to understand the full significance of volatile.
•; parameter either const volatile can also do? Explain why.
•; a pointer can be volatile? Explain why.
•; What is wrong with the following function:
int square (volatile int * ptr)
{
return * ptr ** ptr;
}
Here is the answer:
•; An example is a read-only status register. It is volatile because it may be an unexpected change. It is
const because the program should not attempt to modify it.
•; Although this is not very common. An example is when a service routine modifies a pointer to a buffer
pointer.
•; This code is a little abnormal. The purpose of this code is used to return the pointer * ptr points to the
value of the square, * ptr points to a volatile parameter, the compiler will generate something like the
following
Code:
int square (volatile int * ptr)
{
int a, b;
a = * ptr;
b = * ptr;
return a * b;
}
* Ptr, values may change unexpectedly, a and b may be different. As a result, this code could return the
value of the square is not what you expect! The correct code is as follows:
long square (volatile int * ptr)
{
int a;
a = * ptr;
return a * a;
}
Bit operation (Bit manipulation)
Embedded systems always bit operating variables or register. Given an integer variable a, write two
pieces of code, first set a bit, the second to clear a bit.
In the above two operations to keep the other bits unchanged.
There are three basic reaction on this issue
•; does not know how to start. The interviewee can not have done any embedded systems work.
•; Use bit fields. Bit fields are thrown into the C language dead things, it ensures that your code is not
portable between different compilers, but also to ensure that your code is not
Reusable. I recently had the misfortune to see the driver written by Infineon for its more complex
communication chip, it used bit fields and therefore completely useless to me, because the other side of
my compiler
Style implemented the bit fields. The moral: Never let a non-embedded guy stick the edges of the actual
hardware.
•; operation with # defines and bit masks. This is a highly portable method, the method should be used.
The best solution is as follows:
# Define BIT3 (0x1 << 3)
static int a;
void set_bit3 (void) {
a | = BIT3;
}
void clear_bit3 (void) {
a & = ~ BIT3;
}
Some people like to define a mask at the same time define some constants, which is acceptable to set
and clear values. I would like to see a few key points: constants, | = and & = ~ operator.
Access to fixed memory location (Accessing fixed memory locations)
10. Embedded systems often requires the programmer to access a specific memory location
characteristics. In a project, it is required to set an absolute address 0x67a9 integer variable value 0xaa6
6. The compiler is a pure ANSI compiler. Write code to accomplish this task.
This question tests whether you know in order to access an absolute address cast to an integer number
(typecast) as a legal pointer. The realization of this problem with the personal style
And different. Typical of similar code as follows:
int * ptr;
ptr = (int *) 0x67a9;
* Ptr = 0xaa55;
A more obscure approach is:
A more obscure:
* (Int * const) (0x67a9) = 0xaa55;
Even if your taste runs more to the second solution, but I suggest you use the first option in the
interview.
Interrupt (Interrupts)
11. Interrupt is an important part of embedded systems, which led to many compiler vendors offer an
extension - the standard C support interrupt. With representatives of fact, a new key
Word __interrupt. The following code keyword __interrupt to define an interrupt service subroutine
(ISR) Please comment on this code.
__interrupt double compute_area (double radius)
{
20
double area = PI * radius * radius;
printf (" nArea =% f", area);
return area;
}
There are too many errors in this function, and even people I do not know where to start:
•; ISR can not return a value. If you do not understand this, then you will not be hired.
•; ISR can not pass parameters. If you do not see this, you are hiring the opportunity equivalent to the
first.
•; many processors / compilers, floating point are generally not re-entrant. Some processor / compiler
need to let the amount at the register stack, some processor / compiler is not allowed in the IS
R do floating-point operations. In addition, ISR should be short and efficient, floating-point operations in
the ISR is unwise.
The •; line of succession to the third point, printf () often reentrant and performance. If you lost the
third and fourth points, I will not be too difficult for you. Needless to say, if you can get two points,
Your employment prospects are looking increasingly bright.
*****
Code examples (Code examples)
12 What is the output of the following code, and why?
void foo (void)
{
unsigned int a = 6;
int b = -20;
(A + b> 6)? Puts ("> 6"): puts ("<= 6");
}
This question tests whether you understand the integer promotion rules in C language, I have found
some developers are very poorly understood. No matter what, this unsigned integer problems answer is
that the output is
"6." The reason is that all operand expression symbol types and unsigned types are automatically
converted to unsigned type. -20 Become a very large positive integer, so
The result of the expression is greater than 6. It should be used frequently unsigned data types of
embedded systems is very important. If you got the wrong answer to this question, you will to
Not the job of the edge.
13. Evaluate the following code fragment:
unsigned int zero = 0;
unsigned int compzero = 0xFFFF;
/ * 1's complement of zero * /
For an int type is not 16-bit processor, the above code is incorrect. Should be written as follows:
unsigned int compzero = ~ 0;
This question really reveal whether the candidate understands the importance of the word length of the
processor. In my experience, good embedded programmers are accurately understand the details of the
hardware and its limitations, however, P
C computer program often can not be avoided as a hardware troubles.
This stage, the candidates are either completely dejected or determined to win confidence. If the
candidate is not very good, so this test in the end. But should obviously
Try doing quite well, then I throw in the following additional issues, these problems are more difficult, I
think only the very best candidates will do good. Asking these questions, I hope that more
Candidate to cope with the problem, not the answer. No matter how you when this entertainment ...
21
Dynamic memory allocation (Dynamic memory allocation)
14, although unlike the less common non-embedded computer, embedded system, or the process of
dynamically allocated memory from the heap (heap). Embedded systems, dynamic allocation of memory
may be sent
What is raw?
Here, I would expect the user to mention memory fragmentation, problems with garbage collection,
variable execution time, and so on. In ESP, this topic has been widely discussed (mainly PJ
Plauger, his explanation is far more than any explanation I mentioned here), all go back and look at
these magazines! Having lulled into a sense of false security, I have come up with such a
Small programs:
What is the output of the following code fragment, and why?
char * ptr;
if ((ptr = (char *) malloc (0)) ==
NULL)
else
puts ("Got a null pointer");
puts ("Got a valid pointer");
This is an interesting question. Recently in one of my colleagues inadvertently 0 value passed to the
functions malloc, have been a legitimate pointer, I thought about this. This is above
Code, the code output "Got a valid pointer". I use this to start a discussion of this issue, take a look at
whether the interviewee thought of the library routines doing it right. Get the right
The answer is of course important, but the way to solve the problem and more importantly, you do the
basic principles of decision.
Typedef
:
15 Typedef in C language frequently used to declare an existing data type synonyms. Can also use the
preprocessor to do something similar. For example, think about the following example:
# Define dPS struct s *
typedef struct s * tPS;
The intent of the above two cases are to be defined the the dPS and tPS as a pointers to structure s.
Which method is better? (If any) and why?
This is a very delicate issue, and anyone who gets this issue (legitimate reasons) is to be congratulated.
The answer is to: typedef better. Consider the following example:
dPS p1, p2;
tPS p3, p4;
First expands to
struct s * p1, p2;
.
The above code defines p1 as a pointer to the structure, p2 an actual structure, which is probably not
what you want. The second example is correctly defined p3 and p4 pointer.
Obscure syntax
16. C language agree with some shocking structure, the following structure is legal, if it do?
int a = 5, b = 7, c;
c = a + + + b;
22
This issue will be the quiz, as a happy ending. Whether you believe it or not, the above example is
perfectly grammatical. The problem is that the compiler how to deal with it? Level is not high for the
compiler
Actually debate this issue, according to the best principles, the compiler should be able to handle as
much as possible, all legal usage. Therefore, the above code is treated as:
c = a + + + b;
Therefore, the code held the line a = 6, b = 7, c = 12.
If you know the answer, or to guess the correct answer, well done. If you do not know the answer, I do
not put this as a problem. I found this the biggest benefit is that this is a 'code
Writing style, the readability of the code, the code can be modified a good topic.
Well, guys, you have now done all the tests. This is my C language test questions, I joyfully finish it, I
hope you read it in the same mood. If it is
This is a good test, and then try to go are used in your job search process. God knows maybe after a year
or two, I do not work now, need to find a.
Nigel Jones is a consultant, now live in Maryland, when he is not underwater, you can be found in more
than one range of embedded project him. He was very pleased to receive letters from readers, he
The email address is: NAJones@compuserve.com.
References
•; Jones, Nigel, "In Praise of the # error directive," Embedded Systems Programming, September 1999,
p. 114.
•; Jones, Nigel, "Efficient C Code for Eight-bit MCUs," Embedded Systems Programming, November
1998, p. 66
C language embedded systems programming practice
One of the C language embedded systems programming practice: background papers
Author: Song Baohua Update :2005-08-30
Source: yesky.com
Unlike most forms of software programming, embedded systems programming based on a specific
hardware platform, will require that its programming language with strong hardware operation can be
directly
Force. Undoubtedly, assembly language with such qualities. However, due to the complexity of assembly
language development process, it is not a general choice for embedded system development.
In contrast, the C language - an advanced low-level "language, the best choice for embedded system
development. The author in embedded systems development process,
Again and again to feel the subtleties of the C language, indulge the convenience brought by the C
language for embedded development.
Figure 1 shows the hardware platform based on this discussion, in fact, this is the most embedded
systems hardware platform. It comprises two parts:
(1) a general-purpose processor-centric protocol processing module for network control protocol
processing;
(2) a digital signal processor (DSP) as the center of the signal processing module, for modulation,
demodulation and digital / analog signal conversion.
This discussion is mainly around the general-purpose processor centric protocol processing module,
because it involves more specific C language programming skills. While the DSP
The programming is focused on digital signal processing algorithms, mainly related to the knowledge in
the field of communication, is not the focus of this discussion.
23
Focus on the discussion of the popular C programming skills embedded systems, protocol processing
module of the system does not select a particular CPU, choosing instead a well-known CPU core
Piece - 80186, every learning Microcomputer Principle readers should this chip has a basic
understanding of, and more familiar with its instruction set. 80186 wordlength
16, the memory space can be addressed to 1MB, the only real address mode. C language compiler
generated pointer 32 (double word), and high 16-bit segment address low
16 segment offset a period of up to 64KB.
Figure 1 System architecture
FLASH and RAM protocol processing module is almost essential equipment for each embedded system,
the former is used to store programs, the latter when the program is running commands and
The storage location of the data. Flash and RAM bit width selected by the system are 16, consistent with
the CPU.
Real-time clock chip for system timing, given the current year, month, date and specific time (hours,
minutes, seconds and milliseconds) can be set after a period of time that
Interrupt to the CPU or set the alarm time comes to CPU interrupt (similar to the alarm clock function).
Go sexual NVRAM (nonvolatile RAM) having a power-down without losing data characteristics, the
setting information can be used for the preservation system, such as the network protocol parameters.
In the system
Power down or restart, you can still read the information of the previous settings. 8 bits wide, smaller
than the CPU word length. The article deliberately chosen a CPU word length is inconsistent
Create the conditions for the memory chips, after a discussion.
UART complete the CPU parallel conversion data transmission with the RS-232 serial data transmission,
it can be received [1 to MAX_BUFFER byte to the CPU in
Off, MAX_BUFFER UART chip storage bytes received the maximum buffer.
The keyboard controller and display controller complete control of the system man-machine interface.
The above is a complete embedded system hardware architecture, the actual system may contain fewer
peripherals. Chose a complete system,
A more comprehensive discussion of all aspects of embedded systems C language programming skills in
order to later, all equipment will become the target of the analysis later.
Embedded systems need good software development environment support, because the target
resource-constrained embedded systems, it is not possible on which to build large, complex open
Development environment, and thus the development environment and the target operating
environment separated from each other. Therefore, the development of embedded application
software is usually open on the host (Host)
Development environment, application coding and cross-compiler, and then establish a connection to
the host with the target (Target), the application is downloaded to the target machine for cross
compliance
Trial, after commissioning and optimization, and finally the application curing to the target machine is
actually running.
CAD-UL embedded application software development environment for x86 processor, it runs on top of
the Windows operating system, x86 processor can generate target
24
Code and downloaded through the PC's COM port (RS-232 serial port) or Ethernet port to run on the
target machine, as shown in Figure 2. Reside in the FLASH memory of the target machine
monitor program can monitor users on the host Windows debugging platform debug commands to get
the value of the CPU registers and the storage space of the target machine, the I / O space within
Yung.
Figure 2 cross-development environment
The subsequent chapters from the software architecture, memory operations, the operation of the
screen, keyboard operation, performance optimization and other aspects on the C language
programming of embedded systems skills. Soft
Pieces of architecture is a macro concept, little contact with the specific hardware; memory operations
involved the system FLASH, RAM and NVRAM chip;-screen operation involves
The display controller and real-time clock; keyboard operation mainly related to the keyboard
controller; performance optimization skills given some specific program of reducing the time and space
consumption.
In our practice journey will go through the 25 mark, the these checkpoints main is divided into two
categories, skill and strong applicability; a class of common sense,
The theory some sense.
C language embedded systems programming practice of two: software architecture articles
Author: Song Baohua Update Date :2005-22
Module division
Plan module division is planning mean, what reasonable means will be a lot of software is divided into
independent part of a series of functional cooperation to complete the system requirements.
C language as a structured programming language module division main basis function (by function
division of an error in the object-oriented design,
Newton's law encountered a> theory of relativity), C language modular program design need to
understand the following concepts:
(1) module that is a combination of a. C file and a. H file, is a statement for the module interface header
file (. H);
(2) a module available to other modules call external functions and data to be dubbed. H file extern
keyword to declare;
(3) modules within the required functions and global variables in c beginning of the file preceded by the
static keyword to declare;
(4) never defined variables. H file! The difference is that the definition of the definition of variables and
declare variables will produce the memory allocation operation, assembly stage almost
Read; statement you just told to look for external functions and variables module contains the
statement from the other modules in the connection phase. Such as:
/ * Module1.h * /
int a = 5; / * Module 1. defined in the h file int a * /
/ * Module1. C * /
# Include "module1.h" / * Module 1 Module 1 contains the h file * /
25
/ * Module2. C * /
# Include "module1.h" / * Module 2 contains the module 1. H file * /
/ * Module3. C * /
# Include "module1.h" / * Module 1 Module 3 contains the h file * /
A result of the above procedures are defined in modules 1,2,3 integer variable a, a different module
corresponds to a different address unit, never in this world
Such a procedure is required. The correct approach is:
/ * Module1.h * /
extern int a; / * declared in the module 1 h files int a * /
/ * Module1. C * /
# Include "module1.h" / * Module 1 Module 1 contains the h file * /
int a = 5; / * defined in module 1. c file int a * /
/ * Module2. C * /
# Include "module1.h" / * Module 2 contains the module 1. H file * /
/ * Module3. C * /
# Include "module1.h" / * Module 1 Module 3 contains the h file * /
If the module 1,2,3 operating a corresponding with a memory unit.
An embedded system usually consists of two types of modules:
(1) Hardware driver module, a module corresponding to a particular hardware;
(2) software function module, the module division shall meet the requirements of low coupling and high
cohesion.
Multi-task or single-task
The so-called "single-task system" refers to the system is unable to support concurrent multi-task
operation, macro serially perform a task. The multi-task system macro and
Line (micro serial) to "perform multiple tasks.
Concurrent execution of multiple tasks usually rely on a multitasking operating system (OS), the core of
the multi-tasking OS, system scheduler, it uses a task control block (the TCB)
To manage the task scheduling function. TCB, including the current state of the task priority, to wait for
the event or resource, the task program code starting address, initial stack pointer
Needles and other information. The scheduler task is activated, the use of these information. In
addition, TCB is also used to store the task context (context). Tasks on
All information below is when a task execution is stopped, to be saved. Typically, the context is the
current state of the computer that the various storage
The contents of the. When a task switch occurs, the context of the currently running task is stored in
TCB, and context of the task to be executed from its TCB removed
Into the various registers.
Typical examples of embedded multi-tasking OS such as Vxworks, ucLinux. An embedded OS is not a
distant thing of the altar, we can use less than 1,000
26
Lines of code to achieve a function most simple OS kernel for the 80186 processor, the author is
prepared to do this work, and hope that the contribution of everyone to be able to experience.
The choice of the multi-task or single task depends on whether large software system. For example, the
vast majority of mobile apps are multitasking, but also
Some PHS protocol stack is a single task, no operating system, they turn calls the main handler of various
software modules to simulate multi-tasking environment.
Typical architecture of single-task program
(1) started from the specified address when the CPU is reset;
(2) jumps to perform at the startup of assembly code;
(3) to jump to the user main program main, completed in the main:
a first test of the various hardware devices;
b. initialize each software module;
c. enter an infinite loop (infinite loop), call processing function of each module
User main program and module handling functions in C language. User main program last entered an
infinite loop, the preferred solution is:
while (1)
{
}
Some programmers would write:
for (; ;)
{
}
This syntax does not exactly express the meaning of the code for (; ;) do not see what, only to figure out
the for (; ;) in C language means unconditional loop before
Understand its meaning.
Here are several "well-known" infinite loop:
(1) The operating system is an infinite loop;
(2) WIN32 program is an infinite loop;
(3) embedded system software is an infinite loop;
(4) the threads of a multithreaded program processing function is an infinite loop.
You may argue loudly said: "everything is not absolute, 2, 3 and 4 are not dead cycle". Yes, you are right,
but you can not get fresh
Flowers and applause. In fact, this is not a dead end, because the world has never needed a
processed several message shouted to OS kill it
The WIN32 program does not require a beginning RUN end their embedded systems do not need
to somehow start to do something to get rid of the thread. Have
Time, not too strict manufacturing convenience but trouble. Have you noticed that five of the
TCP / IP protocol stack beyond the rigorous ISO / OSI seven-layer protocol stack popularity to
become something
In fact the standard?
Users often discuss:
printf ("% d,% d", + + i, i + +); / * What is the output? * /
c = a + + + b; / * c =? * /
And other similar issues. Faced with these problems, we can only send a heartfelt sigh: There are
many interesting things in the world waiting for us to digest food intake.
In fact, embedded systems to run to the end of the world.
Interrupt service routine
Interrupt is the important component in the embedded system, but does not include an interrupt
in the standard C. The many compiled developers the interrupt support, the increase in the
standard C
The new keyword is used to mark the interrupt service routine (ISR), similar to __interrupt, #
program interrupt. When a function is defined as the ISR
The time, the compiler will automatically increase for the function interrupt service routine to the
need to interrupt the scene pushed and popped code.
Interrupt service routine need to meet the following requirements:
(1) can not return value;
(2) can not pass parameters to the ISR;
(3) ISR should be as short and pithy;
(4) printf (char * lpFormatString, ...) function will bring reentrant and performance issues, can
not be used in the ISR.
The development of a project, we have designed a queue just to interrupt, the interrupt service
routine, the type is added to the queue, the infinite loop in the main program
Continuously scan interrupt queue whether there is an interruption, remove the first in the queue
an interrupt type, and dealt with accordingly.
/ * Store interrupt queue * /
typedef struct tagIntQueue
{
int intType; / * interrupt type * /
struct tagIntQueue * next;
} IntQueue;
IntQueue lpIntQueueHead;
__interrupt ISRexample ()
{
28
int intType;
intType = GetSystemType ();
QueueAddTail (lpIntQueueHead, intType) ;/ * at the end of the queue to join the new interrupt *
/
}
Determine whether there is interrupt the main program loop:
While (1)
{
If (! IsIntQueueEmpty ())
{
intType = GetFirstInt ();
switch (intType) / * is not much like the WIN32 program message analytic functions? * /
{
/ * Interrupt type resolution is very similar to the message-driven * /
case xxx: / * we call "interrupt-driven", right? * /
...
break;
case xxx:
...
break;
...
}
}
}
The interrupt service routine designed by the above method is very small, the actual work by the
main program execution.
Hardware driver module
A hardware driver module should normally include the following functions:
(1) the interrupt service routine (ISR)
(2) hardware initialization
a. modify registers, set hardware parameters (such as UART should set its baud rate, AD / DA
device should set its sample rate, etc.);
b. interrupt service routine entry address is written to the interrupt vector table:
/ * Set the interrupt vector table * /
m_myPtr = make_far_pointer (0l); / * return void far type pointer to void far ** /
m_myPtr + = ITYPE_UART; / * ITYPE_UART: uart interrupt service routine * /
/ * Relative to the interruption to the scale first address offset * /
29
* M_myPtr = & UART _Isr; / * UART _Isr: UART's interrupt service routine * /
The control line of the CPU (3) is provided for the hardware
If the control line for PIO (Programmable I / O) and control signals set corresponding to the CPU
internal registers it as a control signal;
set the CPU internal interrupt mask bits for the device, set the interrupt (level-triggered or edge-
triggered).
(4) provide for the operation of the device interface functions. For LCD driver module should
draw pixels, draw lines, draw matrix display
Character dot function; For real-time minutes drive modules need to provide access to the time,
set time function.
C of object-oriented
In object-oriented language which the emergence of the concept of a class. A class is a collection
of a specific operation of the specific data. The class contains two areas: data and operations.
The struct in C language is merely a collection of data, we can use the function pointer struct
simulation data and operations as a "class". The following C
The program simulates a simple "class":
# Ifndef C_Class
# Define C_Class struct
# Endif
C_Class A
{
C_Class A * A_this; / * this pointer * /
void (* Foo) of (C_Class A * A_this); / * Behavior: function pointer * /
int a; / * data * /
int b;
};
We can use the C language to simulate the three characteristics of object-oriented: encapsulation,
inheritance and polymorphism, but more often, we just need the data and behavior
Package to solve the confusion problem of software architecture. C to simulate the purpose of
object-oriented thinking is to simulate the behavior itself, but rather to solve some cases using
the C language
Process when the overall program framework structure fragmented, disjointed data and
functions. This example we will see in subsequent chapters.
Summary
This paper describes the software architecture of embedded systems programming knowledge
module division, multi-task or single-task selected, the typical architecture of single-task
program
Interrupt service program, hardware driver module design, given the macro contains the main
elements of an embedded system software.
Remember: the software architecture is the soul of the software! Unstructured program
terrifying, debugging, testing, maintenance, upgrades are extremely difficult.
Small force force force 2005-09-21 17:29
30
C language embedded systems programming practice: memory operations
Author: Song Baohua Update Date :2005-22
Data pointer
Embedded systems programming, often require corresponding MOV instruction in the memory
unit to read and write specific content, assembler, and in addition to other programming in C / C
+ + outside
The language substantially no ability to directly access the absolute address. With the actual
debugging of embedded systems, multi-has the absolute address of the C language pointer unit
content
Reading and writing skills. Operating memory pointer directly occur in the following situations:
(1) I / O chip is positioned in the storage space of the CPU rather than the I / O space, and
register corresponding to a particular address;
(2) between the two CPU communication to the dual port RAM, CPU needs a lot of unit of the
dual-port RAM (called mail box) writing contents in the other CPU production
Generate an interrupt;
(3) to read the Chinese characters and English font burned in ROM or FLASH specific unit.
For example:
unsigned char * p = (unsigned char *) 0xF000FF00;
* P = 11;
The significance of the above procedures written in the absolute address 0xF0000 +0 xFF00
(80186 use the 16-bit address and 16-bit offset address) 11.
In absolute address pointer to pointer to increment from the result of the subtraction operation
depends on the type of pointer to the data. Example p + + the result is p =
0xF000FF01, p points int, namely:
int * p = (int *) 0xF000FF00;
p + + (or + + p) the result is equal to: p = p + sizeof (int), and p-(or the-p) of the result is p = p-
sizeof (int).
Similarly, if the implementation of:
long int * p = (long int *) 0xF000FF00;
The results of the p + + (or + + p) of the equivalent to: p = p + sizeof (long int), and p-(or the-p)
the result is p = p-sizeof (long int).
Remember: CPU in bytes units addressing the C language pointer to point to the length of the
data types for self-increment and decrement. Understand that the pointer to direct manipulation
Memory is very important.
Function pointer
We must first understand the following three questions:
31
(1) C language function names correspond directly to the address of the instruction code
generated by the function in memory, so the name of the function can be directly assigned to a
pointer to a function;
(2) function is called is actually the same as "jumps + parameter passing the treatment + return
location stack" essentially the core of the operation is a function to generate the target-generation
The first address of the code assigned to the CPU PC register;
(3) because of the nature of the function call code to execute the jump to an address unit, so you
can "call" a function that does not exist entities
Halo? Please read on:
Microcomputer principle "textbook out you can get any one university, the book talks about 186
the CPU starts to jump to an absolute address 0xFFFF0 (on
Should the C language pointer 0xF000FFF0 0xF000 segment address, 0xFFF0 segment offset)
implementation, consider the following code:
typedef void (* lpFunction) (); / * define a parameter, no return type of the function pointer type
* /
/ * Define a function pointer to the CPU starts the execution of the first instruction position * /
lpFunction lpReset = (lpFunction) 0xF000FFF0;
lpReset (); / * call the function * /
In the above program, we did not see any function entity, but we did perform this function call:
lpReset (), it is actually from the
To the role of "soft reboot" to jump to the location of the first after the start of the CPU to
execute instructions.
Remember: function without it, the only set of instructions to the ear; You can call a function of
the body of the function, essentially just change
An address to start executing instructions!
Array vs. dynamic application
Dynamic memory in embedded systems application there are more stringent requirements than
the general system programming, this is because the embedded system's memory space is often
very limited
Inadvertently memory leak will soon lead to the collapse of the system.
So make sure you malloc and free in pairs, if you write such a program:
char * function (void)
{
char * p;
p = (char *) malloc (...);
if (p == NULL)
...;
... / * A series of p-operation * /
return p;
}
Somewhere call function () will run out of memory function in dynamic application free, as
follows:
32
char * q = function ();
...
free (q);
The above code is obviously unreasonable, because of the violation of the principle of malloc
and free in pairs, ie "who apply, who is going to release" principle. Does not satisfy this
Principle, will lead to the increase of the degree of coupling of the code, because the user needs
to know the details of its internal function function is called!
Correct approach is to apply in the call at the memory, and pass the function the function, as
follows:
char * p = malloc (...);
if (p == NULL)
...;
function (p);
...
free (p);
p = NULL;
Function function receives the parameters p, as follows:
void function (char * p)
{
... / * A series of p-operation * /
}
Basically, the dynamic application memory with a large array of replacement. Programming
novice, I recommend you to maximize the use of the array! Embedded systems to Bo
The big mind receiving defective, can not "Heiner" error. After all, the most stupid way to
practice hard magic Guo Jingsheng over the witty but Van political error to take the counter-
revolutionary road
Yang Kang.
Given principles:
(1) as far as the selection of the array, the array can not be cross-border access (truth over the
step is the fallacy array across boundaries honorably fulfill a confusion of embedded
Into the system);
(2) If you are using a dynamic application, the application must determine whether the
application is successful, and the malloc and free pairs!
Const keyword
const means "read-only". The functionality of the code is very important, but also older students
heaved the following differences, if you do not know the difference between them, and have
been in the program
Sector fought for many years, it can only say that this is a sad:
const int a;
int const a;
const int * a;
int * const a;
33
int const * a const;
(1) the role of the const keyword is very useful for people to read your code to convey
information. For example, add the const keyword before the function parameter means
This parameter will not be modified in the body of the function are input parameters. When there
is more than one parameter, the caller of the function can whether by virtue of their parameters
const Off
The key word, clearly identify which input parameters and output parameters of what is possible.
(2) a reasonable use of the const keyword allows the compiler to naturally protect those who do
not want to change the parameters, to prevent unintentional code changes, such
You can reduce the emergence of the bug.
const in C + + language contains a richer meaning, only C language means: "read-only the
ordinary variables", can be referred to as "can not be changed
Variable "(This statement seems to be a mouthful, but it is the most accurate expression of the
nature of the C language const), the constant need in the compilation phase remains only to #
define
Macro definition! Therefore follows that the procedure is illegal in the C language:
const int SIZE = 10;
char a [SIZE]; / * illegal: compile phase can not be used in variable * /
Keyword volatile
Writing C language compiler will optimize the code, for example, the following code:
int a, b, c;
a = inWord (0x100); / * read I / O space 0x100 port content stored in a variable * /
b = a;
a = inWord (0x100); / * read again the I / O space 0x100 port content stored in a variable * /
c = a;
Is likely to be the compiler optimization is:
int a, b, c;
a = inWord (0x100); / * read I / O space 0x100 port content stored in a variable * /
b = a;
c = a;
But the results of this optimization may result in an error, if the content of the I / O space 0x100
port in the implementation of other programs after the first read operation is written to the new
value,
In fact, the contents read out of the 2nd read operation different from the first, the value of b and
c should be different. Variable a definition with the volatile keyword can prevent the compiler
Similar optimization of the device, the correct approach is to:
volatile int a;
volatile variables may be used in the following situations:
(1) parallel device hardware registers (such as: the state register, example code, belong to this
category);
34
(2) a non-automatic variable (interrupt service routine access to global variables);
(3) multi-threaded applications, shared by several task variables.
CPU word length is inconsistent with the memory bit wide processing
Mentioned in the background papers, deliberately chose a CPU word length is inconsistent
memory chips, is to conduct the discussion in this section address the CPU word length and kept
The bit width of the reservoir is inconsistent. 80186 word length is 16, and the NVRAM is 8 bits
wide, and in this case, we need to be provided to as NVRAM read and write bytes, words
The interface, as follows:
typedef unsigned char BYTE;
typedef unsigned int WORD;
/ * Function: read the NVRAM bytes
* Parameters: wOffset, the reading position offset relative NVRAM base address
* Returns: byte read to value
* /
extern BYTE ReadByteNVRAM (WORD wOffset)
{
Why LPBYTE lpAddr = (BYTE *) (NVRAM + wOffset * 2); / * Offset to × 2? * /
return * lpAddr;
}
/ * Function: read the NVRAM word
* Parameters: wOffset, the reading position offset relative NVRAM base address
* Returns: Read the word
* /
extern WORD ReadWordNVRAM (WORD wOffset)
{
WORD wTmp = 0;
LPBYTE lpAddr;
/ * Read high byte * /
Why lpAddr = (BYTE *) (NVRAM + wOffset * 2); / * offset to × 2? * /
wTmp + = (* lpAddr) * 256;
/ * Read the low byte * /
Why lpAddr = (BYTE *) (NVRAM + (wOffset +1) * 2); / * offset to × 2? * /
wTmp + = * lpAddr;
return wTmp;
}
/ * Function: to write a byte in the NVRAM
* Parameters: wOffset writing position offset relative to the base address in the NVRAM
* ByData, bytes to be written
* /
35
extern void WriteByteNVRAM (WORD wOffset, BYTE byData)
{
...
}
/ * Function: to the NVRAM write a word * /
* Parameters: wOffset writing position offset relative to the base address in the NVRAM
* WData, want to write the word
* /
extern void WriteWordNVRAM (WORD wOffset, WORD wData)
{
...
}
Zi Gong asked, saying: Why offset multiplied by 2?
Confucius: a look at Figure 1, 16-bit 80186 and interconnection between eight NVRAM can only
address lines A1 its A0 the CPU itself A0 and NVRAM connection. Therefore,
The NVRAM address can only be an even address, so each unit marched to 0x10!
Figure 1 CPU NVRAM address lines
The Zigong ask: So why 80186 does not address lines A0 A0 connection with the NVRAM?
Confucius: to see IT Analects "Microcomputer Principle articles" that tells the sage composed of
about a computer.
Summary
This paper focuses on the memory operation in embedded systems C programming skills. Master
and in-depth understanding of the data pointer, function pointers, dynamic application memory
const and volatile keywords related knowledge, the basic requirements of a good C language
programmers. When we have a firm grasp of these skills,
We have learned 99% of the C language, because of the connotations of the best in the C
language are embodied in the memory operations.
The reason we use in embedded systems C language programming, 99% of memory because of
its powerful ability to operate!
If you love programming, you love the C language;
If you love the C language, you love pointer;
If you love pointer please you love pointer to a pointer!
C language embedded systems programming practice: screen operation
Author: Song Baohua Update Date :2005-22
Chinese Processing
To solve the problem, often used in embedded systems is not a complete character base, often
only need to provide a limited number of Chinese characters for the necessary
Display function. For example, a microwave oven on the LCD does not need to provide the
functionality of the displayed "Email"; one to provide an air conditioner on the LCD of the
Chinese character display function without
To display a short message, and so on. But a mobile phone, PHS, you usually need to include
complete 汉字库.
If the included 汉字库 complete, then, by the internal code to calculate the offset of the character
font library is very simple: the Chinese character library is arranged in order of location
, The first byte of the character area code, and after a bit number of bytes of the word. 94
characters each district records, the bit number compared with the position of the word in the
area. Because
Chinese characters in the Chinese character library specific location is calculated as follows: 94
(area code -1) + bit number -1. Minus 1 because the array is based on the area code begins bit
No. 1 open
Beginning. Simply multiply the number of bytes that can be occupied by a character font: (94 *
(area codes -1) + bit number -1) * number of bytes occupied by a character font, 16 * 16 dot
matrix characters
The library, for example, the formula was: (94 * (area code -1) + (bit number -1)) * 32. Chinese
character library records from the 32 bytes from the position of the word font information.
Contains more complete character base system, we can calculate the position of the matrix above
rules. However, if only to provide a small amount of Chinese characters do? For example, a few
10 to a few hundred? The best practice is to:
Define the macro:
# Define EX_FONT_CHAR (value)
# Define EX_FONT_UNICODE_VAL (value) (value),
# Define EX_FONT_ANSI_VAL (value) (value),
Define the structure:
typedef struct _wide_unicode_font16x16
{
WORD value; / * internal code * /
BYTE data [32]; / * font dot matrix * /
} Unicode;
# Define CHINESE_CHAR_NUM ... / * the kanji number of * /
Font storage with an array:
Unicode chinese [CHINESE_CHAR_NUM] =
{
{
EX_FONT_CHAR ("industry")
EX_FONT_UNICODE_VAL (0x4e1a)
37
{0x04, 0x40, 0x04, 0x40, 0x04, 0x40, 0x04, 0x44, 0x44, 0x46, 0x24, 0x4c, 0x24, 0x48, 0x14,
0x50,
0x1c, 0x50, 0x14, 0x60, 0x04, 0x40, 0x04, 0x40, 0x04, 0x44, 0xff, 0xfe, 0x00, 0x00, 0x00,
0x00}
}
{
EX_FONT_CHAR ("in")
EX_FONT_UNICODE_VAL (0x4e2d)
{0x01, 0x00, 0x01, 0x00, 0x21, 0x08, 0x3f, 0xfc, 0x21, 0x08, 0x21, 0x08, 0x21, 0x08, 0x21,
0x08,
0x21, 0x08,
0x3f, 0xf8, 0x21, 0x08, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00}
}
{
EX_FONT_CHAR ("cloud")
EX_FONT_UNICODE_VAL (0x4e91)
{0x00, 0x00, 0x00, 0x30, 0x3f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0xff, 0xfe, 0x03,
0x00,
0x07, 0x00,
0x06, 0x40, 0x0c, 0x20, 0x18, 0x10, 0x31, 0xf8, 0x7f, 0x0c, 0x20, 0x08, 0x00, 0x00}
}
{
EX_FONT_CHAR ("pieces")
EX_FONT_UNICODE_VAL (0x4ef6)
{0x10, 0x40, 0x1a, 0x40, 0x13, 0x40, 0x32, 0x40, 0x23, 0xfc, 0x64, 0x40, 0xa4, 0x40, 0x28,
0x40,
0x2f, 0xfe,
0x20, 0x40, 0x20, 0x40, 0x20, 0x40, 0x20, 0x40, 0x20, 0x40, 0x20, 0x40, 0x20, 0x40}
}
}
Specific Chinese characters to be displayed, simply from the array of internal codes and the same
characters in the code to get the font. If the front of the Chinese characters in the array to
Within the code size of the order, and you can find more efficient binary search method to the
matrix of the Chinese characters.
This method is a very effective organization of small Store, it can ensure that the program has a
very good structure.
System time display
Time, the system can be read from the NVRAM system generated general With NVRAM
seconds interrupts per second read time and displayed on the LCD. About when
Between the display, there is a question of efficiency. Time, changes in the 60 seconds it is only
once a minute, 60 minutes before the hour change, if
Every time we will read the time on the screen completely re-refresh system and waste a lot of
time.
A better approach is our time display function static variables are stored in hours, minutes,
seconds, and only when its content changes update
Its display.
extern void DisplayTime (...)
{
38
static BYTE byHour, byMinute, bySecond;
BYTE byNewHour, byNewMinute, byNewSecond;
byNewHour = GetSysHour ();
byNewMinute = GetSysMinute ();
byNewSecond = GetSysSecond ();
if (byNewHour! = byHour)
{
/ * Hours * /
byHour = byNewHour;
}
if (byNewMinute! = byMinute)
{
/ * Minutes * /
byMinute = byNewMinute;
}
if (byNewSecond! = bySecond)
{
/ * Seconds * /
bySecond = byNewSecond;
}
}
This example also incidentally as proof of the power of the static keyword in C language. Of
course, in the C + + language, static has a more powerful Wei
Force, it makes some of the data and functions from the "object" and become part of the "class"
of this characteristic is its numerous outstanding achievements in the software design.
Animation display
The animation does not matter, it does not matter no more way to go still picture, will become
the animation. To different still displayed on the screen as the time changes,
Screen, that is the essence of the animation. So, in an embedded system on the LCD to be
displayed animation, requires the help of a timer. No hardware or software timer world
Is impossible to imagine:
(1) there is no timer, an operating system will not be able to time slice rotation, so can not multi-
task scheduling, so they no longer into more than one
Tasking operating system;
(2) there is no timer, a multimedia player software will not work, because it does not know when
it should switch to the next frame;
(3) there is no timer, a network protocol will not be able to operate because of its timeout and
retransmit the packet transmission can not be informed when, and can not be done at a specific
time special
Given task.
Therefore, there is no timer will mean that no operating system, no network, no multimedia, this
will be what darkness? Therefore, a reasonable and flexible use
Types of timers, is the most basic needs of a software person!
80186-based chip embedded systems, we need the help of a hardware timer interrupt as a
software timer interrupt occurs, change screen display
Display content. "Xx: xx" in the time display alternately with or without colon, every time
seconds interrupt occurs, call ShowDot:
39
void ShowDot ()
{
static BOOL bShowDot = TRUE; / * once again experience the power of the static keyword * /
if (bShowDot)
{
showChar (':', xPos, yPos);
}
else
{
showChar ('', xPos, yPos);
}
bShowDot =! bShowDot;
}
Menu operation
Brains of countless people finally appeared, in this section, we will see a little bit object-oriented
thinking, even in the C language used soft
Pieces of structure such as what will be changed!
I once was a fool, menu engage halo, given such a system:
Figure 1 menu example
Requirements on the keyboard "← →" key to switch the menu focus, if tap OK on the keyboard
when the user focus at a menu CANCEL key to call the focus
Menu handling functions corresponding. I once innocently doing so:
/ * Press the OK button * /
void onOkKey ()
{
/ * Judgment on what the focus of the menu press the Ok key, call the appropriate handler
function * /
Switch (currentFocus)
{
case MENU1:
menu1OnOk ();
break;
case MENU2:
menu2OnOk ();
break;
...
}
}
40
/ * Press the Cancel key * /
void onCancelKey ()
{
/ * Judgment on what the focus of the menu press the Cancel key, call the appropriate handler
function * /
Switch (currentFocus)
{
case MENU1:
menu1OnCancel ();
break;
case MENU2:
menu2OnCancel ();
break;
...
}
}
Finally one day, I do this:
/ * Attributes of the menu and the operation of a "package" together * /
typedef struct tagSysMenu
{
char * text; / * menu text * /
BYTE xPos; / * menu on the LCD x coordinate * /
BYTE yPos; / * menu on the LCD y coordinates * /
void (* onOkFun) (); / * press the menu the ok key processing function pointer * /
void (* onCancelFun) (); / * pointer on the menu, press the cancel key processing functions * /
} SysMenu, * LPSysMenu;
When I define the menu, only this:
static SysMenu menu [MENU_NUM] =
{
{
"Menu1", 0, 48, menu1OnOk, menu1OnCancel
}
And
{
"Menu2", 7, 48, menu2OnOk, menu2OnCancel
}
And
{
"Menu3", 7, 48, menu3OnOk, menu3OnCancel
}
41
And
{
"Menu4", 7, 48, menu4OnOk, menu4OnCancel
}
...
};
OK and CANCEL keys processing becomes:
/ * Press the OK button * /
void onOkKey ()
{
menu [currentFocusMenu]. onOkFun ();
}
/ * Press the Cancel key * /
void onCancelKey ()
{
menu [currentFocusMenu]. onCancelFun ();
}
Procedure is greatly simplified, and also began with good scalability. We only use of the package
in the object-oriented thinking, let the program structure clear its junction
Fruit is almost in the system in the case without the need to modify the program to add more
menu key handler of the system remains unchanged.
Object-oriented true God!
Analog MessageBox function
MessageBox function in the Windows programming the Super Mengliao, I do not know how
many beginners, the first to use the function. Remember the first time we
Windows MessageBox output "Hello, World!" Dialog box appears strange feeling it? Not
statistics, how many programmers to learn this world
Windows programming from MessageBox ("Hello, World!", ...). Widespread in my
undergraduate school, with a vocabulary called "'Hello, World'
Level programmer ", refers to the entry-level programmers, but it seems that the saying 'Hello,
World' class" funny and image.
Figure 2 classic Hello, World!
Figure 2 shows the two eternal classic Hello, World dialog box, one has only to "OK", one
contains the "OK", "Cancel." Yes, MessageBox
Indeed, but should also have two categories! This is completely determined by the specific
application requirements.
Embedded system did not give us the MessageBox, but given its powerful, we need to simulate,
an analog MessageBox function:
42
/ ******************************************
/ * Function name: MessageBox
/ * Function Description: The pop-up dialog box, displayed to remind the user of the information
/ * Parameters: lpStr --- string output information to remind the user
/ * TYPE --- output, format (ID_OK = 0, ID_OKCANCEL = 1)
/ * Return value: return to the dialog box to receive the keys, there are only two KEY_OK,
KEY_CANCEL
/ ******************************************
typedef enum TYPE {ID_OK, ID_OKCANCEL} MSG_TYPE;
extern BYTE MessageBox (LPBYTE lpStr, BYTE TYPE)
{
BYTE keyValue = -1;
ClearScreen (); / * Clear the screen * /
DisplayString (xPos, yPos, lpStr, TRUE); / * Display the string * /
/ * Whether to show the decision of the dialog box, type OK, cancel * /
switch (TYPE)
{
case ID_OK:
DisplayString (13, yPos + High +1, "OK", 0);
break;
case ID_OKCANCEL:
DisplayString (8, yPos + High +1, "OK", 0);
DisplayString (17, yPos + High +1, "Cancel", 0);
break;
default:
break;
}
DrawRect (0, 0, 239, yPos + High +16 +4); / * draw a frame * /
/ * MessageBox is a modal dialog, blocking running, waiting for the button * /
while ((keyValue! = KEY_OK) | | (keyValue! = KEY_CANCEL))
{
keyValue = getSysKey ();
}
/ * Return key type * /
if (keyValue == KEY_OK)
{
return ID_OK;
}
else
{
return ID_CANCEL;
}
}
43
Above function we usually use the MessageBox VC + + how some similarities? To achieve this
function, you will see it in the embedded system
The magical effect is endless.
Summary
This is the deepest one of skill in this series of articles, which provides embedded system screen
display of some very clever approach, and the flexibility to use them,
We will no longer be plagued by messy on the LCD display content.
The screen is an important auxiliary embedded systems survive terrifying the display will get
away with another user. Screen programming, if handled properly, will be the software system,
The most confusing part, I have suffered.
C language embedded systems programming practice of: keyboard operation
Author: Song Baohua Update Date :2005-22
Processing function keys
The problem is that of the function keys, the user interface is not fixed, and the choice of user
function key will allow the screen is in a different display state. For example, the main screen,
such as
Figure 1:
Figure 1 of the main screen
When users press the Enter key on the set XX, the screen switches to set XX of the interface, as
shown in Figure 2:
Switch to XX screen
How to determine whether the user program in which screen and calls the corresponding
function key processing functions, but also to ensure a good structure in the program status
screen, is a
A question worth considering.
Let's take a look at the "window" concept used in the WIN32 programming, message (message)
is sent to a different window, the window message processing function
44
(A callback function) was eventually called, the window message processing function is called
according to the type of the message in the window corresponding processing function.
By this way, the Win32 effective organization of different window, and processing the message
in the case of different window.
We learn that:
(1) a different screen analogy the WIN32 in different windows, the window of the various
elements (menus, buttons, etc.) included in the window being;
(2) to each screen provides a function key "message processing function, the function receive
key information as a parameter;
(3) screen function keys "message processing function to determine the types of buttons and the
current focus elements, and calls the corresponding elements of the key processing functions.
/ * Window elements, message processing function package in the window * /
struct windows
{
BYTE currentFocus;
ELEMENT element [ELEMENT_NUM];
void (* messageFun) (BYTE keyValue);
...
};
/ * Message processing function * /
void messageFunction (BYTE keyValue)
{
BYTE i = 0;
/ * Get the focus element * /
while ((element [i]. ID! = currentFocus) && (i <ELEMENT_NUM))
{
i + +;
}
/ * Message map "* /
if (i <ELEMENT_NUM)
{
switch (keyValue)
{
case OK:
element [i]. OnOk ();
break;
...
}
}
}
The process is similar to corresponding elements key function in the window message processing
function call "message map", which is that we learn from the WIN32 programming. Program
To a realm, a lot of things are the same. Elsewhere thinking can be used to take over for me,
"ism" programming.
45
In this example, if we would like to play a little larger, and we can learn from the processing
MESSAGE_MAP method in the MFC, we can also learn MFC scheduled
Defined several sophisticated macros to achieve the "message map".
Dealing with the number keys
User to enter numbers when an A input, an input corresponds to a display position on the screen
(x coordinate, y coordinate). In addition, the program further
Record of the location of the input value, user digital input is the best way to define a structure so
effectively organize, coordinate and numerical bundled:
/ * User digital input structure * /
typedef struct tagInputNum
{
The BYTE byNum; / * receives user input assignment * /
BYTE xPos; / * digital input on the screen display position of the x coordinate * /
BYTE yPos; / * digital input on the screen display position y coordinates * /
} InputNum, * LPInputNum;
Receive user input can define an array of structures, with the array to form a complete digital:
InputNum inputElement [NUM_LENGTH]; / * receive user digital input array * /
/ * Digital key handler * /
extern void onNumKey (BYTE num)
{
if (num == 0 | | num == 1) / * receive only binary input * /
{
/ * Display on the screen the user input * /
DrawText (inputElement [currentElementInputPlace]. XPos,
inputElement [currentElementInputPlace]. yPos, "% 1d", num);
/ * Input assigned to the array element * /
inputElement [currentElementInputPlace]. byNum = num;
/ * The focus and the cursor right * /
moveToRight ();
}
}
Every digital input coordinates and enter the value of bundled digital key processing functions
more structural organization program, the program appeared to be very compact.
Organize user input
Continue the example of the two, in 2 onNumKey function, just to get every one of the numbers,
and therefore we need to be converted to valid data, give an example
To XXX data into effective method is:
/ * Converted into binary data bits valid data: XXX * /
void convertToXXX ()
{
46
BYTE i;
XXX = 0;
for (i = 0; i <NUM_LENGTH; i + +)
{
XXX + = inputElement [i]. ByNum * power (2, NUM_LENGTH - i - 1);
}
}
Instead, we may also need to be displayed on the screen valid data bit, because we also need to
be able to reverse conversion:
/ * Valid data into binary data bits: XXX * /
void convertFromXXX ()
{
BYTE i;
XXX = 0;
for (i = 0; i <NUM_LENGTH; i + +)
{
inputElement [i]. byNum = XXX / power (2, NUM_LENGTH - i - 1)% 2;
}
}
In the above examples, of course, because the data is binary, with a power function is not a good
choice, direct use of efficient "<< >>" shift operation, we
Only to illustrate the convenience of the problem. Just think, if the user input is decimal, power
function may be the only choice.
Summary
The this keyboard operation involved in all aspects: the function key processing, digital key
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx
20090814102834_嵌入式C与C++语言精华文章集锦.docx

More Related Content

Similar to 20090814102834_嵌入式C与C++语言精华文章集锦.docx

Smashing the stack for fun and profit
Smashing the stack for fun and profitSmashing the stack for fun and profit
Smashing the stack for fun and profitAlexey Miasoedov
 
Buffer overflow tutorial
Buffer overflow tutorialBuffer overflow tutorial
Buffer overflow tutorialhughpearse
 
systemverilog-interview-questions.docx
systemverilog-interview-questions.docxsystemverilog-interview-questions.docx
systemverilog-interview-questions.docxssuser1c8ca21
 
Introduction to c
Introduction to cIntroduction to c
Introduction to camol_chavan
 
r,rstats,r language,r packages
r,rstats,r language,r packagesr,rstats,r language,r packages
r,rstats,r language,r packagesAjay Ohri
 
ECS 40 Program #1 (50 points, my time 2.5 hours) .docx
ECS 40           Program #1 (50 points, my time 2.5 hours)    .docxECS 40           Program #1 (50 points, my time 2.5 hours)    .docx
ECS 40 Program #1 (50 points, my time 2.5 hours) .docxjack60216
 
WiMAX implementation in ns3
WiMAX implementation in ns3WiMAX implementation in ns3
WiMAX implementation in ns3Mustafa Khaleel
 
100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects 100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects Andrey Karpov
 
The reasons why 64-bit programs require more stack memory
The reasons why 64-bit programs require more stack memoryThe reasons why 64-bit programs require more stack memory
The reasons why 64-bit programs require more stack memoryPVS-Studio
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questionsSrikanth
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3Srikanth
 
Porting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to RustPorting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to RustEvan Chan
 
1588147798Begining_ABUAD1.pdf
1588147798Begining_ABUAD1.pdf1588147798Begining_ABUAD1.pdf
1588147798Begining_ABUAD1.pdfSemsemSameer1
 

Similar to 20090814102834_嵌入式C与C++语言精华文章集锦.docx (20)

UDP Report
UDP ReportUDP Report
UDP Report
 
Buffer overflow attack
Buffer overflow attackBuffer overflow attack
Buffer overflow attack
 
Smashing the stack for fun and profit
Smashing the stack for fun and profitSmashing the stack for fun and profit
Smashing the stack for fun and profit
 
Buffer overflow tutorial
Buffer overflow tutorialBuffer overflow tutorial
Buffer overflow tutorial
 
systemverilog-interview-questions.docx
systemverilog-interview-questions.docxsystemverilog-interview-questions.docx
systemverilog-interview-questions.docx
 
Lecture5
Lecture5Lecture5
Lecture5
 
Let's us c language (sabeel Bugti)
Let's us c language (sabeel Bugti)Let's us c language (sabeel Bugti)
Let's us c language (sabeel Bugti)
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
 
r,rstats,r language,r packages
r,rstats,r language,r packagesr,rstats,r language,r packages
r,rstats,r language,r packages
 
ECS 40 Program #1 (50 points, my time 2.5 hours) .docx
ECS 40           Program #1 (50 points, my time 2.5 hours)    .docxECS 40           Program #1 (50 points, my time 2.5 hours)    .docx
ECS 40 Program #1 (50 points, my time 2.5 hours) .docx
 
textconfig
textconfigtextconfig
textconfig
 
WiMAX implementation in ns3
WiMAX implementation in ns3WiMAX implementation in ns3
WiMAX implementation in ns3
 
100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects 100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects
 
The reasons why 64-bit programs require more stack memory
The reasons why 64-bit programs require more stack memoryThe reasons why 64-bit programs require more stack memory
The reasons why 64-bit programs require more stack memory
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questions
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3
 
c.ppt
c.pptc.ppt
c.ppt
 
Porting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to RustPorting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to Rust
 
C programming session9 -
C programming  session9 -C programming  session9 -
C programming session9 -
 
1588147798Begining_ABUAD1.pdf
1588147798Begining_ABUAD1.pdf1588147798Begining_ABUAD1.pdf
1588147798Begining_ABUAD1.pdf
 

More from MostafaParvin1

More from MostafaParvin1 (12)

arm-intro.ppt
arm-intro.pptarm-intro.ppt
arm-intro.ppt
 
ARMInst.ppt
ARMInst.pptARMInst.ppt
ARMInst.ppt
 
ARM.ppt
ARM.pptARM.ppt
ARM.ppt
 
ARM11.ppt
ARM11.pptARM11.ppt
ARM11.ppt
 
ARM_2.ppt
ARM_2.pptARM_2.ppt
ARM_2.ppt
 
ARM7_Architecture.ppt
ARM7_Architecture.pptARM7_Architecture.ppt
ARM7_Architecture.ppt
 
ARM7TDMI-S_CPU.ppt
ARM7TDMI-S_CPU.pptARM7TDMI-S_CPU.ppt
ARM7TDMI-S_CPU.ppt
 
arm_3.ppt
arm_3.pptarm_3.ppt
arm_3.ppt
 
ARM Embedded System Essentials + ZLG.docx
ARM Embedded System Essentials + ZLG.docxARM Embedded System Essentials + ZLG.docx
ARM Embedded System Essentials + ZLG.docx
 
ARM 嵌入式系统实验教程(二)扩展实验.docx
ARM 嵌入式系统实验教程(二)扩展实验.docxARM 嵌入式系统实验教程(二)扩展实验.docx
ARM 嵌入式系统实验教程(二)扩展实验.docx
 
ARM 嵌入式系统实验教程(1).docx
ARM 嵌入式系统实验教程(1).docxARM 嵌入式系统实验教程(1).docx
ARM 嵌入式系统实验教程(1).docx
 
IOT Persentation1.pdf
IOT Persentation1.pdfIOT Persentation1.pdf
IOT Persentation1.pdf
 

Recently uploaded

Gaya Call Girls #9907093804 Contact Number Escorts Service Gaya
Gaya Call Girls #9907093804 Contact Number Escorts Service GayaGaya Call Girls #9907093804 Contact Number Escorts Service Gaya
Gaya Call Girls #9907093804 Contact Number Escorts Service Gayasrsj9000
 
Call Girls in Dwarka Sub City 💯Call Us 🔝8264348440🔝
Call Girls in Dwarka Sub City 💯Call Us 🔝8264348440🔝Call Girls in Dwarka Sub City 💯Call Us 🔝8264348440🔝
Call Girls in Dwarka Sub City 💯Call Us 🔝8264348440🔝soniya singh
 
(ANIKA) Wanwadi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(ANIKA) Wanwadi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(ANIKA) Wanwadi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(ANIKA) Wanwadi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
Kalyan callg Girls, { 07738631006 } || Call Girl In Kalyan Women Seeking Men ...
Kalyan callg Girls, { 07738631006 } || Call Girl In Kalyan Women Seeking Men ...Kalyan callg Girls, { 07738631006 } || Call Girl In Kalyan Women Seeking Men ...
Kalyan callg Girls, { 07738631006 } || Call Girl In Kalyan Women Seeking Men ...Pooja Nehwal
 
定制加拿大滑铁卢大学毕业证(Waterloo毕业证书)成绩单(文凭)原版一比一
定制加拿大滑铁卢大学毕业证(Waterloo毕业证书)成绩单(文凭)原版一比一定制加拿大滑铁卢大学毕业证(Waterloo毕业证书)成绩单(文凭)原版一比一
定制加拿大滑铁卢大学毕业证(Waterloo毕业证书)成绩单(文凭)原版一比一zul5vf0pq
 
如何办理(UCLA毕业证书)加州大学洛杉矶分校毕业证成绩单留信学历认证原版一比一
如何办理(UCLA毕业证书)加州大学洛杉矶分校毕业证成绩单留信学历认证原版一比一如何办理(UCLA毕业证书)加州大学洛杉矶分校毕业证成绩单留信学历认证原版一比一
如何办理(UCLA毕业证书)加州大学洛杉矶分校毕业证成绩单留信学历认证原版一比一ga6c6bdl
 
Call Girls In Andheri East Call 9892124323 Book Hot And Sexy Girls,
Call Girls In Andheri East Call 9892124323 Book Hot And Sexy Girls,Call Girls In Andheri East Call 9892124323 Book Hot And Sexy Girls,
Call Girls In Andheri East Call 9892124323 Book Hot And Sexy Girls,Pooja Nehwal
 
Slim Call Girls Service Badshah Nagar * 9548273370 Naughty Call Girls Service...
Slim Call Girls Service Badshah Nagar * 9548273370 Naughty Call Girls Service...Slim Call Girls Service Badshah Nagar * 9548273370 Naughty Call Girls Service...
Slim Call Girls Service Badshah Nagar * 9548273370 Naughty Call Girls Service...nagunakhan
 
Hifi Defence Colony Call Girls Service WhatsApp -> 9999965857 Available 24x7 ...
Hifi Defence Colony Call Girls Service WhatsApp -> 9999965857 Available 24x7 ...Hifi Defence Colony Call Girls Service WhatsApp -> 9999965857 Available 24x7 ...
Hifi Defence Colony Call Girls Service WhatsApp -> 9999965857 Available 24x7 ...srsj9000
 
(SANA) Call Girls Landewadi ( 7001035870 ) HI-Fi Pune Escorts Service
(SANA) Call Girls Landewadi ( 7001035870 ) HI-Fi Pune Escorts Service(SANA) Call Girls Landewadi ( 7001035870 ) HI-Fi Pune Escorts Service
(SANA) Call Girls Landewadi ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
VIP Call Girl Saharanpur Aashi 8250192130 Independent Escort Service Saharanpur
VIP Call Girl Saharanpur Aashi 8250192130 Independent Escort Service SaharanpurVIP Call Girl Saharanpur Aashi 8250192130 Independent Escort Service Saharanpur
VIP Call Girl Saharanpur Aashi 8250192130 Independent Escort Service SaharanpurSuhani Kapoor
 
Vip Noida Escorts 9873940964 Greater Noida Escorts Service
Vip Noida Escorts 9873940964 Greater Noida Escorts ServiceVip Noida Escorts 9873940964 Greater Noida Escorts Service
Vip Noida Escorts 9873940964 Greater Noida Escorts Serviceankitnayak356677
 
哪里办理美国宾夕法尼亚州立大学毕业证(本硕)psu成绩单原版一模一样
哪里办理美国宾夕法尼亚州立大学毕业证(本硕)psu成绩单原版一模一样哪里办理美国宾夕法尼亚州立大学毕业证(本硕)psu成绩单原版一模一样
哪里办理美国宾夕法尼亚州立大学毕业证(本硕)psu成绩单原版一模一样qaffana
 
FULL ENJOY - 8264348440 Call Girls in Hauz Khas | Delhi
FULL ENJOY - 8264348440 Call Girls in Hauz Khas | DelhiFULL ENJOY - 8264348440 Call Girls in Hauz Khas | Delhi
FULL ENJOY - 8264348440 Call Girls in Hauz Khas | Delhisoniya singh
 
Beautiful Sapna Call Girls CP 9711199012 ☎ Call /Whatsapps
Beautiful Sapna Call Girls CP 9711199012 ☎ Call /WhatsappsBeautiful Sapna Call Girls CP 9711199012 ☎ Call /Whatsapps
Beautiful Sapna Call Girls CP 9711199012 ☎ Call /Whatsappssapnasaifi408
 
Call Girls Delhi {Rs-10000 Laxmi Nagar] 9711199012 Whats Up Number
Call Girls Delhi {Rs-10000 Laxmi Nagar] 9711199012 Whats Up NumberCall Girls Delhi {Rs-10000 Laxmi Nagar] 9711199012 Whats Up Number
Call Girls Delhi {Rs-10000 Laxmi Nagar] 9711199012 Whats Up NumberMs Riya
 
VVIP Pune Call Girls Warje (7001035870) Pune Escorts Nearby with Complete Sat...
VVIP Pune Call Girls Warje (7001035870) Pune Escorts Nearby with Complete Sat...VVIP Pune Call Girls Warje (7001035870) Pune Escorts Nearby with Complete Sat...
VVIP Pune Call Girls Warje (7001035870) Pune Escorts Nearby with Complete Sat...Call Girls in Nagpur High Profile
 
Call Girls in Nagpur Bhavna Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Bhavna Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Bhavna Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Bhavna Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Alambagh Call Girl 9548273370 , Call Girls Service Lucknow
Alambagh Call Girl 9548273370 , Call Girls Service LucknowAlambagh Call Girl 9548273370 , Call Girls Service Lucknow
Alambagh Call Girl 9548273370 , Call Girls Service Lucknowmakika9823
 

Recently uploaded (20)

Gaya Call Girls #9907093804 Contact Number Escorts Service Gaya
Gaya Call Girls #9907093804 Contact Number Escorts Service GayaGaya Call Girls #9907093804 Contact Number Escorts Service Gaya
Gaya Call Girls #9907093804 Contact Number Escorts Service Gaya
 
Call Girls in Dwarka Sub City 💯Call Us 🔝8264348440🔝
Call Girls in Dwarka Sub City 💯Call Us 🔝8264348440🔝Call Girls in Dwarka Sub City 💯Call Us 🔝8264348440🔝
Call Girls in Dwarka Sub City 💯Call Us 🔝8264348440🔝
 
(ANIKA) Wanwadi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(ANIKA) Wanwadi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(ANIKA) Wanwadi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(ANIKA) Wanwadi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
Kalyan callg Girls, { 07738631006 } || Call Girl In Kalyan Women Seeking Men ...
Kalyan callg Girls, { 07738631006 } || Call Girl In Kalyan Women Seeking Men ...Kalyan callg Girls, { 07738631006 } || Call Girl In Kalyan Women Seeking Men ...
Kalyan callg Girls, { 07738631006 } || Call Girl In Kalyan Women Seeking Men ...
 
定制加拿大滑铁卢大学毕业证(Waterloo毕业证书)成绩单(文凭)原版一比一
定制加拿大滑铁卢大学毕业证(Waterloo毕业证书)成绩单(文凭)原版一比一定制加拿大滑铁卢大学毕业证(Waterloo毕业证书)成绩单(文凭)原版一比一
定制加拿大滑铁卢大学毕业证(Waterloo毕业证书)成绩单(文凭)原版一比一
 
如何办理(UCLA毕业证书)加州大学洛杉矶分校毕业证成绩单留信学历认证原版一比一
如何办理(UCLA毕业证书)加州大学洛杉矶分校毕业证成绩单留信学历认证原版一比一如何办理(UCLA毕业证书)加州大学洛杉矶分校毕业证成绩单留信学历认证原版一比一
如何办理(UCLA毕业证书)加州大学洛杉矶分校毕业证成绩单留信学历认证原版一比一
 
Call Girls In Andheri East Call 9892124323 Book Hot And Sexy Girls,
Call Girls In Andheri East Call 9892124323 Book Hot And Sexy Girls,Call Girls In Andheri East Call 9892124323 Book Hot And Sexy Girls,
Call Girls In Andheri East Call 9892124323 Book Hot And Sexy Girls,
 
Slim Call Girls Service Badshah Nagar * 9548273370 Naughty Call Girls Service...
Slim Call Girls Service Badshah Nagar * 9548273370 Naughty Call Girls Service...Slim Call Girls Service Badshah Nagar * 9548273370 Naughty Call Girls Service...
Slim Call Girls Service Badshah Nagar * 9548273370 Naughty Call Girls Service...
 
Hifi Defence Colony Call Girls Service WhatsApp -> 9999965857 Available 24x7 ...
Hifi Defence Colony Call Girls Service WhatsApp -> 9999965857 Available 24x7 ...Hifi Defence Colony Call Girls Service WhatsApp -> 9999965857 Available 24x7 ...
Hifi Defence Colony Call Girls Service WhatsApp -> 9999965857 Available 24x7 ...
 
(SANA) Call Girls Landewadi ( 7001035870 ) HI-Fi Pune Escorts Service
(SANA) Call Girls Landewadi ( 7001035870 ) HI-Fi Pune Escorts Service(SANA) Call Girls Landewadi ( 7001035870 ) HI-Fi Pune Escorts Service
(SANA) Call Girls Landewadi ( 7001035870 ) HI-Fi Pune Escorts Service
 
VIP Call Girl Saharanpur Aashi 8250192130 Independent Escort Service Saharanpur
VIP Call Girl Saharanpur Aashi 8250192130 Independent Escort Service SaharanpurVIP Call Girl Saharanpur Aashi 8250192130 Independent Escort Service Saharanpur
VIP Call Girl Saharanpur Aashi 8250192130 Independent Escort Service Saharanpur
 
Vip Noida Escorts 9873940964 Greater Noida Escorts Service
Vip Noida Escorts 9873940964 Greater Noida Escorts ServiceVip Noida Escorts 9873940964 Greater Noida Escorts Service
Vip Noida Escorts 9873940964 Greater Noida Escorts Service
 
哪里办理美国宾夕法尼亚州立大学毕业证(本硕)psu成绩单原版一模一样
哪里办理美国宾夕法尼亚州立大学毕业证(本硕)psu成绩单原版一模一样哪里办理美国宾夕法尼亚州立大学毕业证(本硕)psu成绩单原版一模一样
哪里办理美国宾夕法尼亚州立大学毕业证(本硕)psu成绩单原版一模一样
 
FULL ENJOY - 8264348440 Call Girls in Hauz Khas | Delhi
FULL ENJOY - 8264348440 Call Girls in Hauz Khas | DelhiFULL ENJOY - 8264348440 Call Girls in Hauz Khas | Delhi
FULL ENJOY - 8264348440 Call Girls in Hauz Khas | Delhi
 
Beautiful Sapna Call Girls CP 9711199012 ☎ Call /Whatsapps
Beautiful Sapna Call Girls CP 9711199012 ☎ Call /WhatsappsBeautiful Sapna Call Girls CP 9711199012 ☎ Call /Whatsapps
Beautiful Sapna Call Girls CP 9711199012 ☎ Call /Whatsapps
 
Call Girls Delhi {Rs-10000 Laxmi Nagar] 9711199012 Whats Up Number
Call Girls Delhi {Rs-10000 Laxmi Nagar] 9711199012 Whats Up NumberCall Girls Delhi {Rs-10000 Laxmi Nagar] 9711199012 Whats Up Number
Call Girls Delhi {Rs-10000 Laxmi Nagar] 9711199012 Whats Up Number
 
VVIP Pune Call Girls Warje (7001035870) Pune Escorts Nearby with Complete Sat...
VVIP Pune Call Girls Warje (7001035870) Pune Escorts Nearby with Complete Sat...VVIP Pune Call Girls Warje (7001035870) Pune Escorts Nearby with Complete Sat...
VVIP Pune Call Girls Warje (7001035870) Pune Escorts Nearby with Complete Sat...
 
Call Girls in Nagpur Bhavna Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Bhavna Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Bhavna Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Bhavna Call 7001035870 Meet With Nagpur Escorts
 
9953330565 Low Rate Call Girls In Jahangirpuri Delhi NCR
9953330565 Low Rate Call Girls In Jahangirpuri  Delhi NCR9953330565 Low Rate Call Girls In Jahangirpuri  Delhi NCR
9953330565 Low Rate Call Girls In Jahangirpuri Delhi NCR
 
Alambagh Call Girl 9548273370 , Call Girls Service Lucknow
Alambagh Call Girl 9548273370 , Call Girls Service LucknowAlambagh Call Girl 9548273370 , Call Girls Service Lucknow
Alambagh Call Girl 9548273370 , Call Girls Service Lucknow
 

20090814102834_嵌入式C与C++语言精华文章集锦.docx

  • 1. Embedded C / C + + language the essence of the article highlights C / C + language struct deep exploration ........................................... ................................. 2 In C + + extern "C" meaning deep exploration ......................................... ............................... 7 Efficient C language programming recipe ........................................... .................................... 11 Want to become embedded programmers should know 0x10 basic problem ..................................... .................... 15 C language embedded systems programming practice ........................................... ................................ 22 One of the C language embedded systems programming practice: background papers ...................................... ...................... 22 C language embedded systems programming practice: software architecture articles ..................................... ................... 24 C language embedded systems programming practice: memory operations ...................................... .................... 30 C language embedded systems programming practice: screen operation ...................................... .................... 36 C language embedded systems programming practice of: keyboard operation ...................................... .................... 43 Six C language embedded systems programming practice: performance optimization ...................................... .................... 46 C / C + + the language void and the void pointer Deep Exploration ........................................ ......................... 50 C / C + + language variable parameter list Deep Exploration ........................................ ............................... 54 C / C + + array name and pointer difference between deep exploration ........................................ ............................. 60 C / C + + programmers candidates common interview questions-depth analysis of (1) .................................... .......................... 62 C / C + + programmers candidates common interview questions in-depth analysis (2) .................................... .......................... 67 A well-known foreign companies face questions unraveling the ........................................... ........................... 74 C / C + + advanced features of the structure - the designated members of the median .................................. ..................... 78 C / C + + in the near-instruction, far pointers and giant pointer ..................................... .............................. 80 From two classic questions about the C / C + + in the Commonwealth of the use of the (union) ................................. ..................... 81 Real-life experience of ARM-based embedded Linux transplant ......................................... ....................... 83 Real-life experience of ARM-based embedded Linux transplantation (1) - Basic Concepts .................................. ......... 83 ARM-based embedded Linux transplantation real experience (2) - BootLoader ................................... ...... 96 Real-life experience of ARM-based embedded Linux transplantation (3) - the operating system .................................. ........ 111
  • 2. ARM-based embedded Linux transplantation real experience (4) - Device Driver .................................. ........ 120 ARM-based embedded Linux transplantation real experience (5) - Application Examples .................................. ........ 135 Layman Linux device driver programming ............................................. .......................... 144 1.Linux kernel module ............................................. ................................. 144 2. Character device driver ............................................ ............................... 146 3. Concurrency control device driver .......................................... ............................. 151 4. Equipment blocking and non-blocking operation ......................................... ............................ 157 2 C / C + language struct Deep Exploration Source: PConline author: Song Baohua 1. Struct huge role Faced with a large C / C + + program, look on the use of the struct we can programming through its writers Inspection for evaluation. Because a large C / C + + program is bound to involve some (or even large) the combination of data structures, these nodes Isomers can be the original sense of belonging to a whole data together. To some extent, it will not use the struct, how to use it struct is the difference between a sign of whether the developers with a rich development experience. Is not a simple network protocol, communication control, embedded systems, C / C + + programming, we often want to send a stream of bytes (char Up a whole array), but the combination of a variety of data, its manifestations is a structure. Inexperienced developers often need to send the content in order to save char array through a pointer offset The method of transmission network packets, and other information. Doing programming complex, error-prone, and are subject to change once the control methods and communication protocols, procedures Will be carried out in great detail modifications. An experienced developer flexibility in the use of the structure, to give an example, the hypothetical network or control protocol needs to send three Text, its format were packetA, packetB, packetC: struct structA { int a; char b; }; struct structB { char a; short b; }; struct structC {
  • 3. int a; char b; float c; } Excellent programmers designed such that the message sent: struct CommuPacket { 3 int iPacketType; / / packet type flag union / / every time you send three packets using the union { struct structA packetA; struct structB packetB; struct structC packetC; } }; Performing packet transmission, transmitted directly a whole struct CommuPacket. Assume that the send function prototype is as follows: / / PSendData: first address to send a stream of bytes, iLen: To send a length Send (char * pSendData, unsigned int iLen); The sender can directly call send the the struct CommuPacket an instance sendCommuPacket: Send ((char *) & sendCommuPacket, sizeof (CommuPacket)); Assume that the receiver function prototype is as follows: / / PRecvData: first address to send a stream of bytes, iLen: To receive length / / Return value: the number of bytes actually received unsigned int Recv (char * pRecvData, unsigned int iLen); Receiver can be directly called as follows and the received data is saved in struct CommuPacket an instance recvCommuPacket: Recv ((char *) & recvCommuPacket, sizeof (CommuPacket)); Then determine the type of message and dealt with accordingly: switch (recvCommuPacket. iPacketType) { case PACKET_A: ... / / A class packet processing break; case PACKET_B: Packet processing ... / / B class break; case PACKET_C: Packet processing ... / / C class break; } Most noteworthy in the above procedure Send ((char *) & sendCommuPacket, sizeof (CommuPacket)); Recv ((char *) & recvCommuPacket, sizeof (CommuPacket)); In the cast: (char *) & sendCommuPacket, (char *) & recvCommuPacket address of first, and then converted to a char pointer to
  • 4. This can directly to handle byte stream function. Using this mandatory type of transformation, we can also facilitate the preparation of the program, for example, in which the memory initialization of sendCommuPacket can Like calling the standard library function memset (): memset ((char *) & sendCommuPacket, 0, sizeof (CommuPacket)); 2 members of the struct alignment Intel, Microsoft and other companies have a similar interview questions: # Include <iostream.h> 4 # Pragma pack (8) struct example1 { short a; long b; }; struct example2 { char c; example1 struct1; short e; }; # Pragma pack () int main (int argc, char * argv []) { example2 struct2; cout << sizeof (example1) << endl; cout << sizeof (example2) << endl; cout << (unsigned int) (& struct2.struct1) - (unsigned int) (& struct2) << endl; return 0; } Asked enter the result of the program is it? The answer is: 8 16 4 Do not understand? Still do not understand? The following eleven to: The 2.1 naturally on sector struct is a composite data type, its constituent elements, both variables can be basic data types (such as int, long, float, etc.) can also Data unit complex data types (such as array, struct, union, etc.). For the structure, the compiler will automatically alignment of the member variables To improve the operation efficiency. By default, the compiler to allocate space for each member of the structure of their natural community (natural alignment) conditions. Each Members in accordance with their order of declaration are sequentially stored in memory, the same as the address of the first member and the entire structure of the address. The natural logarithm sector (natural alignment) that default alignment is a member of the largest
  • 5. members of the structure size aligned. For example: struct naturalalign { char a; short b; char c; }; In the above structure, size maximum is short, its length is 2 bytes, and thus the the char members in the structure a, c are 2 units aligned, sizeof (naturalalign) results equal to 6; If read as follows: struct naturalalign 5 { char a; int b; char c; }; The result is apparently to 12. 2.2 specified on the sector In general, by the following method to change the default on the boundary conditions: • Use the directive # pragma pack (n), the compiler will be aligned in accordance with the n bytes; • Use directive # pragma pack (), to cancel custom byte alignment. Note: If you specify # pragma pack (n) n is greater than the size of the largest member in the structure, it does not work, the structure Still on the sector in accordance with the maximum size of members. For example: # Pragma pack (n) struct naturalalign { char a; int b; char c; }; # Pragma pack () When n alignment for 4,8,16, the sizeof (naturalalign) of results is equal to 12. And when n is 2 , Play a role, such that sizeof (naturalalign) result is 6. VC + + 6.0 compiler, we can specify its sector (see Figure 1), and its mode of operation to select projetct> the setting> C / C + + menu, specified in the struct member alignment you want on the sector. Figure 1 is specified on the sector in the VC + + 6.0 6 Further, through __attribute ((aligned (n))) can also make the role of a member of the structure body is aligned in the N-byte boundary, but
  • 6. Is it less, and thus does not explain in detail. 2.3 interview questions answers At this point, we can Intel, Microsoft interview questions comprehensive answer. Second line # pragma pack (8) program specified on the sector, but due to the members of the struct example1 size 4 (long variable size, 4), so the struct example1 still 4 bytes on the sector, struct example1 size 8, line 18 output; struct example2 contains struct example1, the maximum size itself contain simple data members of 2 (short Variable e), but because it contains a struct example1, and struct example1 largest member size 4, struct the example2 also should be four pairs of circles, # pragma pack (8) is specified on the boundary of the struct example2 does not work, it is on line 19 The output result is 16; As members of the struct example2 to 4 units of the sector, its char variable c should complement the three empty and subsequently is Members struct1 memory space, 20 lines of output. C and C + + between struct deep distinction In C + + language struct with the function of the "class" with the keyword class difference is that the members of the struct variable And function the default access permissions for the public, but class is private. For example, the definition of the struct class and class categories: struct structA { char a; ... } class classB { char a; ... } Then: structA a; a.a = 'a'; / / access public members, legal classB b; b.a = 'a'; / / access private members, illegal Many papers wrote here that has been given a C + + struct and class all differences, but in fact not the case, another point It needs to be noted is: Struct in C + + is fully compatible with maintaining a struct in C (which is consistent with the C + + original intention - a better c ") Thus, the following operation is legitimate: / / Define the struct struct structA
  • 7. { char a; char b; int c; }; 7 structA a = {'a', 'a', 1}; / / defined directly given initial That the struct can be defined when directly to the {} of its members variable initial values, and the class is not in the classic bibliography Thinking C + + 2nd edition of this point is emphasized. 4. Struct Programming Note Take a look at the following program: 1. # Include <iostream.h> 2. Struct structA 3 { 4. Int iMember; 5. Char * cMember; 6}; 7. Int main (int argc, char * argv []) 8 { 9. StructA instant1, instant2; 10. Char c = 'a'; 11. Instant1.iMember = 1; 12. Instant1.cMember = &c; 13. Instant2 = instant1; 14. Cout << * (instant1.cMember) << endl; 15. * (Instant2.cMember) = 'b'; 16. Cout << * (instant1.cMember) << endl; 17. Return 0; } 14 lines of output: a 16 lines of output: b Why? 15 line instant2 modifications change the value of a member instant1! The reason is that the line 13 instant2 = instant1 assignment statement is variable one by one copy, which makes instant1 and the cMember in instant2 point to the same piece of memory, which the modification of instant2 is on instant1 modify. In the C language, when the structure pointer members, we must pay attention to whether the assignment statement in the two instances Pointer members point to the same piece of memory. In the C + + language, when the structure pointer members, we need to rewrite the the struct copy constructor and "=" Operator overloading. In C + + extern "C" meaning deep exploration Author: Song Baohua e-mail: 21cnbao@21cn.com Source: Pacific Internet 1 Introduction
  • 8. C + + language originally create "a better C", but this does not mean that the C + +, C-like language of global variables and functions Used to compile and link mode is identical to the C language. As a desire language compatible with C, C + + retains part of the procedural language Introduction characteristics (called "not completely object-oriented"), and thus it does not belong to any kind of global variables and functions can define the world. However, C + +, after all, is an object-oriented programming language, in order to support function overloading, C + + global function approach with C There are obviously different. Speaking from the standard header files A company had given a face questions as follows: Interview questions Why the standard header files have similar structures below? # Ifndef __ INCvxWorksh # Define __ INCvxWorksh # Ifdef __ cplusplus extern "C" { # Endif / * ... * / # Ifdef __ cplusplus } # Endif # Endif / * __ INCvxWorksh * / Analysis Clearly, the role of compile macros in the header file # ifndef __ INCvxWorksh # define __ INCvxWorksh The # endif " Prevent the header files are repeated references. Then # Ifdef __ cplusplus extern "C" { # Endif # Ifdef __ cplusplus } # Endif The role, then what is it? In the following, we will one by one. Deep Inside extern "C" extern "C" contains a double meaning, literally can be obtained: First, it modified target "extern"; Second, It modified target is "C". Let's take a detailed interpretation of the meaning of a two-fold. (1) is defined function or variable extern "C" extern type; extern C / C + + language shows that the scope of functions and global variables visibility keywords, the keyword tells the compiler, Its declaration of functions and variables can be used in the module or modules. Remember, the following statement: extern int a;
  • 9. Just a variable declaration is not in define variables, not for a distributed memory space. Variable a for all modules Can only be defined as a global variable, otherwise there will be a connection error. Typically, the module in the module header files available to other modules referenced in function and global variable declaration extern keyword. For example, if the global variables and functions defined in the module A module B For reference only contains the the module A header files can. In this way, Call function in module A module B in the compilation phase, module B can not find the function, but it does not error; it will Find this function module A compiler generates object code from the connection phase. The keywords extern corresponding static, global variables and functions can only be modified in the module. Therefore, a Function or variable may only use this module, which can not be modified extern "C". (2) is modified extern "C" variables and functions in accordance with the compilation and linking of the C language way; Compile not add extern "C" declaration 9 First, take a look at C + +, how to compile the C-like function. As an object-oriented language, C + + supports function overloading, procedural language C is not supported. Function is C + + compiler in character No. library name with the C language is different. For example, assume that a function prototype: void foo (int x, int y); The function C compiler symbol library name _foo, C + + compiler will generate the like _foo_int_int like Name (different compiler may generate a different name, but use the same mechanism to generate a new name called "mangled name "). _foo_int_int this name contains the name of the function, the number of function parameters and the type of information, C + + is to rely on this mechanism to Function overloading. For example, in C + +, the function void foo (int x, int y) void foo (int x, float y) The compiler generates the symbol is not the same, the latter _foo_int_float. Similarly, variables in C + + in addition to support for local variables, but also support the class member variables and global variables. Class into the user program Member variable may be global variables of the same name, we have to differentiate. " Essence, the compiler during compile time, similar to the processing of the function, Also took a unique name for the class variables, global variable name of the name with the same name in the user program. Connection not add extern "C" declaration Assumptions in module A, C + + header files as follows: / / The module A header file moduleA.h # Ifndef MODULE_A_H # Define MODULE_A_H int foo (int x, int y); # Endif Module B refer to the function:
  • 10. / / Module B file moduleB.cpp # Include "moduleA.h" foo (2,3); In fact, looking _foo_int_int the target file moduleA.obj connection phase, the connector will be generated from the module A such The sign! Add extern "C" statement after compiling and linking Plus extern "C" declaration module A header file becomes: / / The module A header file moduleA.h # Ifndef MODULE_A_H # Define MODULE_A_H extern "C" int foo (int x, int y); # Endif Still call module B implementation file foo (2,3), the result is: (1) Module A compiler generates object code for foo, not its name, the special treatment, the use of the C language; (2) connector in object code module B looking for foo (2,3) called looking for is unmodified symbol name _foo. Declared in module A function foo extern "C" type, and module B contains extern int foo (int x, int y), then the module the B module A can not be in the function; vice versa. Therefore, can be summarized in one sentence extern "C" the real purpose of the statement (in any language any grammatical characteristics of the birth Are not arbitrary and, from the real world, demand-driven. We think you can not only stay in this language is how To do, but also to ask why it is you want to do, what the motive is, so that we can be more in- depth understanding of the many issues): C + + and C and other languages mixed programming. Understand the motives of the establishment of the C + +, extern "C" We turn next to a concrete analysis of the extern "C" usually use skills. 4.extern "C" idiom 10 (1) reference functions and variables in C language, C + + contains the C language header files (assuming cExample.h), into Line following treatment: extern "C" { # Include "cExample.h" } Header files in the C language, its external function can only be designated as extern type extern "C" statement is not supported in the C language, Compiler syntax errors. C file contains the extern "C" will appear. Author written in C + + source code reference to the C function examples project contains three files are as follows: / * C language header file: cExample.h * / # Ifndef C_EXAMPLE_H # Define C_EXAMPLE_H
  • 11. extern int add (int x, int y); # Endif / * C language file: cExample.c * / # Include "cExample.h" int add (int x, int y) { return x + y; } / / C + + files, invoke add: cppFile.cpp extern "C" { # Include "cExample.h" } int main (int argc, char * argv []) { add (2,3); return 0; } If C + + calls a C language prepared by the DLL when the DLL header file declares the interface function should be added extern "C" {}. (2) The reference in C C + + language functions and variables, C + + header files need to add extern "C", but not in the C language Declared extern "C" can directly reference the header files should only be declared as C file in C + + as defined in extern "C" function The extern Type. The author to write the C reference C + + source code of the function in the example project contains three files are as follows: / / C + + header files cppExample.h # Ifndef CPP_EXAMPLE_H # Define CPP_EXAMPLE_H extern "C" int add (int x, int y); # Endif / / C + + implementation file cppExample.cpp # Include "cppExample.h" int add (int x, int y) 11 { return x + y; } / * C file cFile.c / * This will compile error: # include cExample.h "* / extern int add (int x, int y); int main (int argc, char * argv []) { add (2, 3);
  • 12. return 0; } If the in-depth understanding of the extern "C" as set forth in the three play a role in the compilation and linking stages, will be able to truly understand this section Elaborated from C + + reference C functions and C reference to the C + + function usage. Section 4 gives the example code, you need to pay special attention to each Details. Efficient C language programming recipe Write simple and efficient C code, which is a goal pursued by many software engineers. In this paper, some experience and experience in the work to do related to the exposition, wrong place Please Advise. 1 recruit: space for time The biggest contradiction in the computer program is a contradiction of space and time, then reverse thinking from this perspective, to consider the efficiency of the program, we will have to solve Problem First strokes - space for time. For example: string assignment. Method A, the usual way: # Define LEN 32 char string1 [LEN]; memset (string1, 0, LEN); strcpy (string1, "This is an example!!" Method B: const char string2 [LEN] = "This is an example!" char * cp; cp = string2; (When using the direct pointer to the operation.) As can be seen from the above example, the efficiency of the A and B can not be compared. Under the same storage space, B directly use the pointer can be operated, and A needs to call The two characters function to complete. B's disadvantage flexibility A good. A better flexibility in a string content needs to change frequently; If Method B, stored many strings, though they take a lot of memory, but to obtain a high efficiency of program execution. Real-time requirements of the system, memory, there are some that I recommend you use the tricks. The edge of the tricks trick - macro function rather than a function. The following are examples: Method C: # Define bwMCDR2_ADDRESS 4 # Define bsMCDR2_ADDRESS 17 int BIT_MASK (int_bf) { return ((IU << (bw # # _bf)) -1) << (bs # # _bf);
  • 13. } void SET_BITS (int_dst, int_bf, int_val) { _dst = ((_dst) & ~ (BIT_MASK (_bf))) I (((_val) <<< (Bs # # _bf)) & (BIT_MASK (_bf))) } SET_BITS (MCDR2, MCDR2_ADDRESS, RegisterNumb er); Method D: # Define bwMCDR2_ADDRESS 4 # Define bsMCDR2_ADDRESS 17 # Define bmMCDR2_ADDRESS BIT_MASK (MCDR2_ADDRESS) # Define BIT_MASK (_bf) (((1U << (bw # # _bf)) -1) << (Bs # # _bf) # Define SET_BITS (_dst, _bf, _val) ((_dst) = ((_dst) & ~ (BIT_MASK (_bf))) I (((_val) << (Bs # # _bf)) & (BIT_MASK (_bf)))) SET_BITS (MCDR2, MCDR2_ADDRESS, RegisterNumb er); The difference lies in the function and macro function, a macro function takes up a lot of space, while the function takes time. We want to know, the function call is to use the system Stack to save the data, if the compiler stack checking option, usually in the head of the function will be embedded in some assembly statement to check the current stack; same time, CPU should Save and restore the current scene in the function call, push and popped operations, function calls, so need some CPU time. The macro function does not exist this asked Problems. Macro function only as a pre-written code embedded in the current program does not produce the function call, so it is just taking up space in the frequent calls to the same macro Function when the phenomenon is especially prominent. D method is the best I have seen set manipulation functions, is part of the ARM's source, a lot of features in just three lines, covering almost all the Bit manipulation functions. C method is a variant of the taste of them need to carefully understand. 2 strokes: mathematical methods to solve the problem Now our interpretation of the second measure of efficient C language - mathematical methods to solve the problem. Mathematics is the mother of the computer, there is no basis and foundation of mathematics, there would be no development of a computer program, using some mathematical methods will program The efficiency of the implementation of magnitude improvement. Following are examples, and, of 1 to 100,. Method E int I, j; Method F
  • 14. int I; 13 for (I = 1; I <= 100; I + +) { j + = I; } I = (100 * (1 +100)) / 2 This example use case is a mathematical impressed me the most, my hungry computer first teacher test me. I was only in third grade, but unfortunately I do not know with Formula NX (N +1) / 2 to solve this problem. Method E loop 100 times before solving the problem, that is at least 100 assignment, 100 judgment, 200 Additions (I and j); Method F only with an addition, a multiplication, division 1. The effect of natural self- evident. So now when I was editing program More brains to find rules to maximize the power of mathematics to improve the efficiency of the program running. 3 strokes: Use-bit operating Efficient C language to write the third measure - use bit operation to reduce the division and modulo arithmetic. In the computer program, the data bit is the smallest unit of data that can operate, in theory, can be used "calculation" to complete all of the operations and operation. Usually a bit operation Is used to control the hardware, or do the use of the data conversion, however, can effectively improve the efficiency of running flexible bit operating. Example table is as follows: Method G int I, J; I = 257/8; J = 456% 32; Method H int I, J; I = 257 >> 3; J = 456 - (456 >> 4 << 4); Literally as if H ratio G trouble a lot, but a closer look at the assembly code will understand the method G is called basic the modulo functions and the division function Both function calls, there are a lot of assembly code and register to participate in computing; method H is only a few words related to the compilation of the code more concise and efficient. Of course, Due to the different compiler, efficiency may not differ much, However, I am currently experiencing MS C, ARM C point of view, the efficiency gap is still not small. Related compilation Code is not listed here. Is transported 用这招 Note that, the problems that may arise because of the different CPU. For example, on a PC 用这招 programs written through debugging, and on the PC, When transplanted into a 16-bit machine platform may generate code hidden. So only in certain advanced before you can use this trick. 4 strokes: compilation of embedded
  • 15. Efficient C language programming nirvana the fourth trick - embedded compilation. "The eyes of the people familiar with assembly language, C language program is garbage." Although this view is extreme, but it has its reason. Assembly language is valid The highest rate of computer language, however, can not rely on it to write an operating system? So, in order to get the high efficiency of the program, we had to adopt alternative side Law - embedded compilation, mixed programming. For example the array assignment to array each byte match. char string1 [1024], string2 [1024]; 14 Method I int I; for (I = 0; I <1024; I + +) * (String2 + I) = * (string1 + I) Method J # Int I; for (I = 0; I <1024; I + +) * (String2 + I) = * (string1 + I); # Else # Ifdef_ARM_ _asm { MOV R0, string1 MOV R1, string2 MOV R2, # 0 loop: LDMIA R0!, [R3-R11] STMIA R1!, [R3-R11] ADD R2, R2, # 8 CMP R2, # 400 BNE loop } # Endif Method I is the most common method, used 1024 cycles; method J is different depending on the platform a distinction between the ARM platform, embedded assembler only 128 Cycles to complete the same operation. There are friends will say, why not use the standard memory copy function? This is because in the source data may contain data for 0 bytes, so the standard library functions will be ahead of the end and will not complete the requested operation. This routine is typically applied to the LCD data copy process. Root According to different CPUs, skilled use of the embedded assembler, can greatly improve the efficiency of program execution. Although this is nirvana, but will pay a heavy price if easily use. It is embedded assembler, it limits the portability of the program, the program in Different platforms transplant process, Crouching Tiger, Hidden Dragon, and danger! Meanwhile, the
  • 16. tricks are also contrary to the idea of modern software engineering only in compelling circumstances Can be used. Remember. Highly efficient programming using C language, my experience. Initiate this article, please experts to share their experience. I hope to give a better Method we can work together to improve our programming skills. Taken from the microcontroller and embedded systems applications 2003.9 15 Want to be 0x10 basic questions embedded programmers should know - | Endeaver 2006-3-8 16:16:00 The C language test is a necessary and effective method of recruitment of embedded systems programmers. All these years, I participate in both organized this test, in this process I realized that these measurements The test can provide a lot of useful information with the interviewer and the interviewee, setting aside the pressure of the interview aside, this test is quite interesting. From the perspective of the interviewee, you learn a lot about the title or the invigilator. This test is only a question to show their knowledge of the details of the ANSI standard, rather than technical skills Design? This stupid question? To know the result of the ASCII value of a character. These problems the study focused on the ability of system calls and memory allocation strategy it? This indicates that the topic May spend time on the PC and not on the embedded system. If the answer to any questions is "yes", then I know I have to seriously consider whether I should do the job. From the interviewer's perspective, a test may be able to reveal several qualities of the candidate: the most basic, you can understand the the candidate C language level. Anyway, look at how this man Answered that he would not issue full of interesting. Candidate in good intuition to make informed choices, or just guessing blindly? When the candidate stuck on an issue is to find an excuse, or the performance of Genuine curiosity on the issue, see this as the opportunity to learn it? I find this information as useful as their test scores. With these in mind, I decided to live out some real hope these headaches exam Questions and Answers for embedded systems, looking for work is to give people a little help. These issues are these annual real Interpersonal encounter. Some of these questions is difficult, but they should be able to give you a little inspiration. This test is suitable for candidates of different levels, the most junior level of the candidate's results will be poor, experienced programmers should have good results. Some ask in order to allow you to be able to decide Preference of questions, each question has not been assigned scores If you choose exam for you, your own scores assigned by you mean. Preprocessor (Preprocessor) Preprocessor directives # define statements in a constant used to indicate how many seconds in a year (ignoring leap years) # Define SECONDS_PER_YEAR (60 * 60 * 24 * 365) UL I would like to see a few things:
  • 17. •; basic knowledge of the # define syntax (for example: You can not end with a semicolon, the use of braces, etc.) •; know preprocessor will calculate the value of the constant expression directly write the year you how to calculate the number of seconds rather than the actual value calculated clearer price. •; aware of this expression will make a 16-bit machine integer overflow - so use to the long integer symbol L, tells the compiler that this constant is the long integer. •; if you used in your expressions UL (unsigned long), then you have a good starting point. Remember, first impressions are very important. Write a "standard" macro MIN, this macro input two parameters and returns the smaller one. # Define MIN (A, B) ((A) <= (B)? (A): (B)) This test is designed for the purpose of the following: •; basic knowledge of the # define macro applications. This is very important, because until Embedding (inline) operator becomes part of the standard C macro is convenient to generate only embed code The law, in order to achieve the required performance for embedded systems, embedded code often must. •; triple conditional operator knowledge. This operator exists in C language because it allows the compiler to produce more optimized code than if-then-else, it is very important to understand this usage. •; understand the macro Carefully parameters in parentheses up •; I also use this to begin to discuss the macro side effects, such as: What happens when you write the following code? least = MIN (* p + +, b); What is the purpose of the preprocessor directive # error? If you do not know the answer, see Reference 1. This problem it is useful to distinguish between a normal folks and the nerds. Only the nerds read Appendix C language textbooks to find out about The answer to this problem. Of course, if you are not looking for a nerd, then the candidate better hope that they do not know the answer. Infinite loop (Infinite loops) 4. Embedded systems often use to an infinite loop, how kind of you to write in C infinite loop? 16 The problem with a few solutions. My preferred solution is: while (1) { ?} Some programmers prefer the program as follows: for (; ;) { ?} The way to achieve that embarrassed me, because this syntax does not exactly how the matter in the end. If a candidate gives this as a solution, I will use this as an opportunity to explore their The basic principle of doing so. If their answer is: "I was taught to do so, but did not think why." This will leave a bad impression.
  • 18. The third option is to use goto Loop: ... goto Loop; Candidates who are given the above program, which shows that he is an assembly language programmer (which is probably a good thing) or he want to get into a new field of BASIC / FORTRAN programmers. Data declarations (Data declarations) Variable a following definition is given a) an integer (An integer) b) a pointer to an integer pointer (A pointer to an integer The) c) a pointer to a pointer to a pointer, it points to the pointer is pointing to an integer (A pointer to a pointer to an intege) r d) an array of 10 integer (An array of 10 integers) e) an array of 10 pointers, the pointer is a pointer to an integer number. (An array of 10 pointers to integers) f) a pointer to a pointer to an array of 10 integers (A pointer to an array of 10 integers) g) a pointer to a function, the function takes an integer argument and returns an integer (A pointer to a function that takes an integer as an argument and returns an integer) h) an array of 10 pointers, the pointer to a function, the function is an integer argument and returns an integer (An array of ten pointers to functions t hat take an integer argument and return an integer) The answer is: a) int a; / / An integer b) int * a; / / A pointer to an integer c) int ** a; / / A pointer to a pointer to an integer d) int a [10]; / / An array of 10 integers e) int * a [10]; / / An array of 10 pointers to integers f) int (* a) [10]; / / A pointer to an array of 10 integers g) int (* a) (int); / / A pointer to a function a that takes an integer argument and returns an integer h) int (* a [10]) (int); / / An array of 10 pointers to functions that take an integer argument and return an integer It is often claimed that there are several issues here that a brief look at the book in order to answer the question, I agree with this. When I wrote this article, in order to determine the correctness of the syntax, I do check Look book. But when I interview, I expect to be asked this question (or similar). Since the time of the interview, I'm sure I know the answer to this question. Candidates who do not know all the answers (or at least most of the answers), then there would be no for the interview and to prepare for the interview if the interviewer does not prepare, then he can What are the preparations? 17
  • 19. Static What is the role of the static keyword? This simple question is rarely answered completely. Three distinct role in the C language, the keyword static: •; in the body of the function, a is declared as static variables in this function is called to maintain its value unchanged. •; within the module (but function in vitro), a declared as static variables within the module with a function to access, but not access other functions outside the module. It is a local global variables Amount. •; within the module, a declared as static function can only be called by other functions within this module. That is, this function is limited to use in the local declaration module within. Most candidates correctly answered the first part correctly answer the second part, the same few people understand the third. This is a candidate serious drawback, because he apparently Do not know the benefits and importance of localization data and code range. Const 7. Keyword const mean? I just heard the interviewer said: "const means constant," I know I'm dealing with an amateur. Dan Saks last year, has been completely in his article summarizes the const All usage ESP (translator: Embedded Systems Programming) every reader should be very familiar with the const can do and can not do if you never Read the article say that const means "read-only" as long as you can. Although the answer is not entirely the answer, but I accept it as a correct answer. (If you want to know More detailed answer, carefully read the the Saks article. ) If the candidate correctly answer this question, I will ask him an additional problem: The following statements are What does it mean? const int a; int const a; const int * a; int * const a; int const * a const; / ****** / The role of the first two is the same, a is a constant integer. The third means a is a pointer to a constant integer pointer (that is, the integer is not modified, but the pointer). The fourth Mean a often is a pointer to an integer pointer (ie, the integer pointer can be modified, but the pointer is not modified). Last a point often means a whole Type the number of regular pointer (that is, the integer pointer can not modify the pointer itself may not be modified). If the candidate correctly answer these questions, then he gave me to stay Under a good impression. Incidentally, perhaps you might ask, even without the keyword const, or can easily write the correct function of the program, then why is so dear to shut Key word const it? I have the following several reasons: •; role of the const keyword is very useful for people to read your code to convey information, in fact, declare a parameter for the constant parameters of the user application purpose is to tell. If
  • 20. You have to spend a lot of time to clean up the garbage left by other people, you will quickly learn to appreciate this extra piece of information. (Of course, know how to use const, rarely leave the mess for others to clean Reasonable. ) •; through some additional information to the optimizer, use the const keyword may be able to generate more compact code. •; reasonably use the const keyword allows the compiler to naturally protect those who do not want to change the parameters, and code changes to prevent unintentional. In short, this can reduce bug Appear. Volatile 8 What are the implications of keyword volatile? Given three different examples. Defined as volatile variable is that this variable may be unexpectedly changed, so the compiler will not go assuming the value of this variable. Accurate to say is that the optimizer used in This variable must always be carefully re-reads the value of this variable, instead of using the backup stored in the register. Here are a few examples of the volatile variable: 18 •; the parallel device hardware registers (such as: Status Register) •; an interrupt service routine access to non-automatic variables (Non-automatic variables) •; multi-threaded applications, shared by several task variables People do not know the answer to this question will not be hired. I think this is a distinction between C programmer and embedded systems programmers the basic problem. The guys often engage embedded with hardware interrupt The RTOS and so dealing with all of these require volatile variables. Do not know how volatile will bring disaster. Assumption that the interviewee correctly answered a problem (doubt whether it will be the case), I will probe a little deeper, look at this guy is not straight is to understand the full significance of volatile. •; parameter either const volatile can also do? Explain why. •; a pointer can be volatile? Explain why. •; What is wrong with the following function: int square (volatile int * ptr) { return * ptr ** ptr; } Here is the answer: •; An example is a read-only status register. It is volatile because it may be an unexpected change. It is const because the program should not attempt to modify it. •; Although this is not very common. An example is when a service routine modifies a pointer to a buffer pointer. •; This code is a little abnormal. The purpose of this code is used to return the pointer * ptr points to the value of the square, * ptr points to a volatile parameter, the compiler will generate something like the following Code:
  • 21. int square (volatile int * ptr) { int a, b; a = * ptr; b = * ptr; return a * b; } * Ptr, values may change unexpectedly, a and b may be different. As a result, this code could return the value of the square is not what you expect! The correct code is as follows: long square (volatile int * ptr) { int a; a = * ptr; return a * a; } Bit operation (Bit manipulation) Embedded systems always bit operating variables or register. Given an integer variable a, write two pieces of code, first set a bit, the second to clear a bit. In the above two operations to keep the other bits unchanged. There are three basic reaction on this issue •; does not know how to start. The interviewee can not have done any embedded systems work. •; Use bit fields. Bit fields are thrown into the C language dead things, it ensures that your code is not portable between different compilers, but also to ensure that your code is not Reusable. I recently had the misfortune to see the driver written by Infineon for its more complex communication chip, it used bit fields and therefore completely useless to me, because the other side of my compiler Style implemented the bit fields. The moral: Never let a non-embedded guy stick the edges of the actual hardware. •; operation with # defines and bit masks. This is a highly portable method, the method should be used. The best solution is as follows: # Define BIT3 (0x1 << 3) static int a; void set_bit3 (void) { a | = BIT3; } void clear_bit3 (void) { a & = ~ BIT3; } Some people like to define a mask at the same time define some constants, which is acceptable to set and clear values. I would like to see a few key points: constants, | = and & = ~ operator. Access to fixed memory location (Accessing fixed memory locations)
  • 22. 10. Embedded systems often requires the programmer to access a specific memory location characteristics. In a project, it is required to set an absolute address 0x67a9 integer variable value 0xaa6 6. The compiler is a pure ANSI compiler. Write code to accomplish this task. This question tests whether you know in order to access an absolute address cast to an integer number (typecast) as a legal pointer. The realization of this problem with the personal style And different. Typical of similar code as follows: int * ptr; ptr = (int *) 0x67a9; * Ptr = 0xaa55; A more obscure approach is: A more obscure: * (Int * const) (0x67a9) = 0xaa55; Even if your taste runs more to the second solution, but I suggest you use the first option in the interview. Interrupt (Interrupts) 11. Interrupt is an important part of embedded systems, which led to many compiler vendors offer an extension - the standard C support interrupt. With representatives of fact, a new key Word __interrupt. The following code keyword __interrupt to define an interrupt service subroutine (ISR) Please comment on this code. __interrupt double compute_area (double radius) { 20 double area = PI * radius * radius; printf (" nArea =% f", area); return area; } There are too many errors in this function, and even people I do not know where to start: •; ISR can not return a value. If you do not understand this, then you will not be hired. •; ISR can not pass parameters. If you do not see this, you are hiring the opportunity equivalent to the first. •; many processors / compilers, floating point are generally not re-entrant. Some processor / compiler need to let the amount at the register stack, some processor / compiler is not allowed in the IS R do floating-point operations. In addition, ISR should be short and efficient, floating-point operations in the ISR is unwise. The •; line of succession to the third point, printf () often reentrant and performance. If you lost the third and fourth points, I will not be too difficult for you. Needless to say, if you can get two points, Your employment prospects are looking increasingly bright. ***** Code examples (Code examples) 12 What is the output of the following code, and why? void foo (void) {
  • 23. unsigned int a = 6; int b = -20; (A + b> 6)? Puts ("> 6"): puts ("<= 6"); } This question tests whether you understand the integer promotion rules in C language, I have found some developers are very poorly understood. No matter what, this unsigned integer problems answer is that the output is "6." The reason is that all operand expression symbol types and unsigned types are automatically converted to unsigned type. -20 Become a very large positive integer, so The result of the expression is greater than 6. It should be used frequently unsigned data types of embedded systems is very important. If you got the wrong answer to this question, you will to Not the job of the edge. 13. Evaluate the following code fragment: unsigned int zero = 0; unsigned int compzero = 0xFFFF; / * 1's complement of zero * / For an int type is not 16-bit processor, the above code is incorrect. Should be written as follows: unsigned int compzero = ~ 0; This question really reveal whether the candidate understands the importance of the word length of the processor. In my experience, good embedded programmers are accurately understand the details of the hardware and its limitations, however, P C computer program often can not be avoided as a hardware troubles. This stage, the candidates are either completely dejected or determined to win confidence. If the candidate is not very good, so this test in the end. But should obviously Try doing quite well, then I throw in the following additional issues, these problems are more difficult, I think only the very best candidates will do good. Asking these questions, I hope that more Candidate to cope with the problem, not the answer. No matter how you when this entertainment ... 21 Dynamic memory allocation (Dynamic memory allocation) 14, although unlike the less common non-embedded computer, embedded system, or the process of dynamically allocated memory from the heap (heap). Embedded systems, dynamic allocation of memory may be sent What is raw? Here, I would expect the user to mention memory fragmentation, problems with garbage collection, variable execution time, and so on. In ESP, this topic has been widely discussed (mainly PJ Plauger, his explanation is far more than any explanation I mentioned here), all go back and look at these magazines! Having lulled into a sense of false security, I have come up with such a Small programs: What is the output of the following code fragment, and why? char * ptr; if ((ptr = (char *) malloc (0)) == NULL)
  • 24. else puts ("Got a null pointer"); puts ("Got a valid pointer"); This is an interesting question. Recently in one of my colleagues inadvertently 0 value passed to the functions malloc, have been a legitimate pointer, I thought about this. This is above Code, the code output "Got a valid pointer". I use this to start a discussion of this issue, take a look at whether the interviewee thought of the library routines doing it right. Get the right The answer is of course important, but the way to solve the problem and more importantly, you do the basic principles of decision. Typedef : 15 Typedef in C language frequently used to declare an existing data type synonyms. Can also use the preprocessor to do something similar. For example, think about the following example: # Define dPS struct s * typedef struct s * tPS; The intent of the above two cases are to be defined the the dPS and tPS as a pointers to structure s. Which method is better? (If any) and why? This is a very delicate issue, and anyone who gets this issue (legitimate reasons) is to be congratulated. The answer is to: typedef better. Consider the following example: dPS p1, p2; tPS p3, p4; First expands to struct s * p1, p2; . The above code defines p1 as a pointer to the structure, p2 an actual structure, which is probably not what you want. The second example is correctly defined p3 and p4 pointer. Obscure syntax 16. C language agree with some shocking structure, the following structure is legal, if it do? int a = 5, b = 7, c; c = a + + + b; 22 This issue will be the quiz, as a happy ending. Whether you believe it or not, the above example is perfectly grammatical. The problem is that the compiler how to deal with it? Level is not high for the compiler Actually debate this issue, according to the best principles, the compiler should be able to handle as much as possible, all legal usage. Therefore, the above code is treated as: c = a + + + b; Therefore, the code held the line a = 6, b = 7, c = 12. If you know the answer, or to guess the correct answer, well done. If you do not know the answer, I do not put this as a problem. I found this the biggest benefit is that this is a 'code Writing style, the readability of the code, the code can be modified a good topic. Well, guys, you have now done all the tests. This is my C language test questions, I joyfully finish it, I
  • 25. hope you read it in the same mood. If it is This is a good test, and then try to go are used in your job search process. God knows maybe after a year or two, I do not work now, need to find a. Nigel Jones is a consultant, now live in Maryland, when he is not underwater, you can be found in more than one range of embedded project him. He was very pleased to receive letters from readers, he The email address is: NAJones@compuserve.com. References •; Jones, Nigel, "In Praise of the # error directive," Embedded Systems Programming, September 1999, p. 114. •; Jones, Nigel, "Efficient C Code for Eight-bit MCUs," Embedded Systems Programming, November 1998, p. 66 C language embedded systems programming practice One of the C language embedded systems programming practice: background papers Author: Song Baohua Update :2005-08-30 Source: yesky.com Unlike most forms of software programming, embedded systems programming based on a specific hardware platform, will require that its programming language with strong hardware operation can be directly Force. Undoubtedly, assembly language with such qualities. However, due to the complexity of assembly language development process, it is not a general choice for embedded system development. In contrast, the C language - an advanced low-level "language, the best choice for embedded system development. The author in embedded systems development process, Again and again to feel the subtleties of the C language, indulge the convenience brought by the C language for embedded development. Figure 1 shows the hardware platform based on this discussion, in fact, this is the most embedded systems hardware platform. It comprises two parts: (1) a general-purpose processor-centric protocol processing module for network control protocol processing; (2) a digital signal processor (DSP) as the center of the signal processing module, for modulation, demodulation and digital / analog signal conversion. This discussion is mainly around the general-purpose processor centric protocol processing module, because it involves more specific C language programming skills. While the DSP The programming is focused on digital signal processing algorithms, mainly related to the knowledge in the field of communication, is not the focus of this discussion. 23 Focus on the discussion of the popular C programming skills embedded systems, protocol processing module of the system does not select a particular CPU, choosing instead a well-known CPU core Piece - 80186, every learning Microcomputer Principle readers should this chip has a basic understanding of, and more familiar with its instruction set. 80186 wordlength 16, the memory space can be addressed to 1MB, the only real address mode. C language compiler generated pointer 32 (double word), and high 16-bit segment address low 16 segment offset a period of up to 64KB.
  • 26. Figure 1 System architecture FLASH and RAM protocol processing module is almost essential equipment for each embedded system, the former is used to store programs, the latter when the program is running commands and The storage location of the data. Flash and RAM bit width selected by the system are 16, consistent with the CPU. Real-time clock chip for system timing, given the current year, month, date and specific time (hours, minutes, seconds and milliseconds) can be set after a period of time that Interrupt to the CPU or set the alarm time comes to CPU interrupt (similar to the alarm clock function). Go sexual NVRAM (nonvolatile RAM) having a power-down without losing data characteristics, the setting information can be used for the preservation system, such as the network protocol parameters. In the system Power down or restart, you can still read the information of the previous settings. 8 bits wide, smaller than the CPU word length. The article deliberately chosen a CPU word length is inconsistent Create the conditions for the memory chips, after a discussion. UART complete the CPU parallel conversion data transmission with the RS-232 serial data transmission, it can be received [1 to MAX_BUFFER byte to the CPU in Off, MAX_BUFFER UART chip storage bytes received the maximum buffer. The keyboard controller and display controller complete control of the system man-machine interface. The above is a complete embedded system hardware architecture, the actual system may contain fewer peripherals. Chose a complete system, A more comprehensive discussion of all aspects of embedded systems C language programming skills in order to later, all equipment will become the target of the analysis later. Embedded systems need good software development environment support, because the target resource-constrained embedded systems, it is not possible on which to build large, complex open Development environment, and thus the development environment and the target operating environment separated from each other. Therefore, the development of embedded application software is usually open on the host (Host) Development environment, application coding and cross-compiler, and then establish a connection to the host with the target (Target), the application is downloaded to the target machine for cross compliance Trial, after commissioning and optimization, and finally the application curing to the target machine is actually running. CAD-UL embedded application software development environment for x86 processor, it runs on top of the Windows operating system, x86 processor can generate target 24 Code and downloaded through the PC's COM port (RS-232 serial port) or Ethernet port to run on the target machine, as shown in Figure 2. Reside in the FLASH memory of the target machine monitor program can monitor users on the host Windows debugging platform debug commands to get the value of the CPU registers and the storage space of the target machine, the I / O space within Yung. Figure 2 cross-development environment The subsequent chapters from the software architecture, memory operations, the operation of the
  • 27. screen, keyboard operation, performance optimization and other aspects on the C language programming of embedded systems skills. Soft Pieces of architecture is a macro concept, little contact with the specific hardware; memory operations involved the system FLASH, RAM and NVRAM chip;-screen operation involves The display controller and real-time clock; keyboard operation mainly related to the keyboard controller; performance optimization skills given some specific program of reducing the time and space consumption. In our practice journey will go through the 25 mark, the these checkpoints main is divided into two categories, skill and strong applicability; a class of common sense, The theory some sense. C language embedded systems programming practice of two: software architecture articles Author: Song Baohua Update Date :2005-22 Module division Plan module division is planning mean, what reasonable means will be a lot of software is divided into independent part of a series of functional cooperation to complete the system requirements. C language as a structured programming language module division main basis function (by function division of an error in the object-oriented design, Newton's law encountered a> theory of relativity), C language modular program design need to understand the following concepts: (1) module that is a combination of a. C file and a. H file, is a statement for the module interface header file (. H); (2) a module available to other modules call external functions and data to be dubbed. H file extern keyword to declare; (3) modules within the required functions and global variables in c beginning of the file preceded by the static keyword to declare; (4) never defined variables. H file! The difference is that the definition of the definition of variables and declare variables will produce the memory allocation operation, assembly stage almost Read; statement you just told to look for external functions and variables module contains the statement from the other modules in the connection phase. Such as: / * Module1.h * / int a = 5; / * Module 1. defined in the h file int a * / / * Module1. C * / # Include "module1.h" / * Module 1 Module 1 contains the h file * / 25 / * Module2. C * / # Include "module1.h" / * Module 2 contains the module 1. H file * / / * Module3. C * / # Include "module1.h" / * Module 1 Module 3 contains the h file * / A result of the above procedures are defined in modules 1,2,3 integer variable a, a different module corresponds to a different address unit, never in this world Such a procedure is required. The correct approach is: / * Module1.h * /
  • 28. extern int a; / * declared in the module 1 h files int a * / / * Module1. C * / # Include "module1.h" / * Module 1 Module 1 contains the h file * / int a = 5; / * defined in module 1. c file int a * / / * Module2. C * / # Include "module1.h" / * Module 2 contains the module 1. H file * / / * Module3. C * / # Include "module1.h" / * Module 1 Module 3 contains the h file * / If the module 1,2,3 operating a corresponding with a memory unit. An embedded system usually consists of two types of modules: (1) Hardware driver module, a module corresponding to a particular hardware; (2) software function module, the module division shall meet the requirements of low coupling and high cohesion. Multi-task or single-task The so-called "single-task system" refers to the system is unable to support concurrent multi-task operation, macro serially perform a task. The multi-task system macro and Line (micro serial) to "perform multiple tasks. Concurrent execution of multiple tasks usually rely on a multitasking operating system (OS), the core of the multi-tasking OS, system scheduler, it uses a task control block (the TCB) To manage the task scheduling function. TCB, including the current state of the task priority, to wait for the event or resource, the task program code starting address, initial stack pointer Needles and other information. The scheduler task is activated, the use of these information. In addition, TCB is also used to store the task context (context). Tasks on All information below is when a task execution is stopped, to be saved. Typically, the context is the current state of the computer that the various storage The contents of the. When a task switch occurs, the context of the currently running task is stored in TCB, and context of the task to be executed from its TCB removed Into the various registers. Typical examples of embedded multi-tasking OS such as Vxworks, ucLinux. An embedded OS is not a distant thing of the altar, we can use less than 1,000 26 Lines of code to achieve a function most simple OS kernel for the 80186 processor, the author is prepared to do this work, and hope that the contribution of everyone to be able to experience. The choice of the multi-task or single task depends on whether large software system. For example, the vast majority of mobile apps are multitasking, but also Some PHS protocol stack is a single task, no operating system, they turn calls the main handler of various software modules to simulate multi-tasking environment. Typical architecture of single-task program (1) started from the specified address when the CPU is reset; (2) jumps to perform at the startup of assembly code; (3) to jump to the user main program main, completed in the main: a first test of the various hardware devices;
  • 29. b. initialize each software module; c. enter an infinite loop (infinite loop), call processing function of each module User main program and module handling functions in C language. User main program last entered an infinite loop, the preferred solution is: while (1) { } Some programmers would write: for (; ;) { } This syntax does not exactly express the meaning of the code for (; ;) do not see what, only to figure out the for (; ;) in C language means unconditional loop before Understand its meaning. Here are several "well-known" infinite loop: (1) The operating system is an infinite loop; (2) WIN32 program is an infinite loop; (3) embedded system software is an infinite loop; (4) the threads of a multithreaded program processing function is an infinite loop. You may argue loudly said: "everything is not absolute, 2, 3 and 4 are not dead cycle". Yes, you are right, but you can not get fresh Flowers and applause. In fact, this is not a dead end, because the world has never needed a processed several message shouted to OS kill it The WIN32 program does not require a beginning RUN end their embedded systems do not need to somehow start to do something to get rid of the thread. Have Time, not too strict manufacturing convenience but trouble. Have you noticed that five of the TCP / IP protocol stack beyond the rigorous ISO / OSI seven-layer protocol stack popularity to become something In fact the standard? Users often discuss: printf ("% d,% d", + + i, i + +); / * What is the output? * / c = a + + + b; / * c =? * / And other similar issues. Faced with these problems, we can only send a heartfelt sigh: There are many interesting things in the world waiting for us to digest food intake. In fact, embedded systems to run to the end of the world. Interrupt service routine Interrupt is the important component in the embedded system, but does not include an interrupt in the standard C. The many compiled developers the interrupt support, the increase in the standard C The new keyword is used to mark the interrupt service routine (ISR), similar to __interrupt, # program interrupt. When a function is defined as the ISR The time, the compiler will automatically increase for the function interrupt service routine to the need to interrupt the scene pushed and popped code.
  • 30. Interrupt service routine need to meet the following requirements: (1) can not return value; (2) can not pass parameters to the ISR; (3) ISR should be as short and pithy; (4) printf (char * lpFormatString, ...) function will bring reentrant and performance issues, can not be used in the ISR. The development of a project, we have designed a queue just to interrupt, the interrupt service routine, the type is added to the queue, the infinite loop in the main program Continuously scan interrupt queue whether there is an interruption, remove the first in the queue an interrupt type, and dealt with accordingly. / * Store interrupt queue * / typedef struct tagIntQueue { int intType; / * interrupt type * / struct tagIntQueue * next; } IntQueue; IntQueue lpIntQueueHead; __interrupt ISRexample () { 28 int intType; intType = GetSystemType (); QueueAddTail (lpIntQueueHead, intType) ;/ * at the end of the queue to join the new interrupt * / } Determine whether there is interrupt the main program loop: While (1) { If (! IsIntQueueEmpty ()) { intType = GetFirstInt (); switch (intType) / * is not much like the WIN32 program message analytic functions? * / { / * Interrupt type resolution is very similar to the message-driven * / case xxx: / * we call "interrupt-driven", right? * / ... break; case xxx: ... break; ... } } } The interrupt service routine designed by the above method is very small, the actual work by the main program execution.
  • 31. Hardware driver module A hardware driver module should normally include the following functions: (1) the interrupt service routine (ISR) (2) hardware initialization a. modify registers, set hardware parameters (such as UART should set its baud rate, AD / DA device should set its sample rate, etc.); b. interrupt service routine entry address is written to the interrupt vector table: / * Set the interrupt vector table * / m_myPtr = make_far_pointer (0l); / * return void far type pointer to void far ** / m_myPtr + = ITYPE_UART; / * ITYPE_UART: uart interrupt service routine * / / * Relative to the interruption to the scale first address offset * / 29 * M_myPtr = & UART _Isr; / * UART _Isr: UART's interrupt service routine * / The control line of the CPU (3) is provided for the hardware If the control line for PIO (Programmable I / O) and control signals set corresponding to the CPU internal registers it as a control signal; set the CPU internal interrupt mask bits for the device, set the interrupt (level-triggered or edge- triggered). (4) provide for the operation of the device interface functions. For LCD driver module should draw pixels, draw lines, draw matrix display Character dot function; For real-time minutes drive modules need to provide access to the time, set time function. C of object-oriented In object-oriented language which the emergence of the concept of a class. A class is a collection of a specific operation of the specific data. The class contains two areas: data and operations. The struct in C language is merely a collection of data, we can use the function pointer struct simulation data and operations as a "class". The following C The program simulates a simple "class": # Ifndef C_Class # Define C_Class struct # Endif C_Class A { C_Class A * A_this; / * this pointer * / void (* Foo) of (C_Class A * A_this); / * Behavior: function pointer * / int a; / * data * / int b; }; We can use the C language to simulate the three characteristics of object-oriented: encapsulation, inheritance and polymorphism, but more often, we just need the data and behavior Package to solve the confusion problem of software architecture. C to simulate the purpose of object-oriented thinking is to simulate the behavior itself, but rather to solve some cases using the C language Process when the overall program framework structure fragmented, disjointed data and functions. This example we will see in subsequent chapters. Summary
  • 32. This paper describes the software architecture of embedded systems programming knowledge module division, multi-task or single-task selected, the typical architecture of single-task program Interrupt service program, hardware driver module design, given the macro contains the main elements of an embedded system software. Remember: the software architecture is the soul of the software! Unstructured program terrifying, debugging, testing, maintenance, upgrades are extremely difficult. Small force force force 2005-09-21 17:29 30 C language embedded systems programming practice: memory operations Author: Song Baohua Update Date :2005-22 Data pointer Embedded systems programming, often require corresponding MOV instruction in the memory unit to read and write specific content, assembler, and in addition to other programming in C / C + + outside The language substantially no ability to directly access the absolute address. With the actual debugging of embedded systems, multi-has the absolute address of the C language pointer unit content Reading and writing skills. Operating memory pointer directly occur in the following situations: (1) I / O chip is positioned in the storage space of the CPU rather than the I / O space, and register corresponding to a particular address; (2) between the two CPU communication to the dual port RAM, CPU needs a lot of unit of the dual-port RAM (called mail box) writing contents in the other CPU production Generate an interrupt; (3) to read the Chinese characters and English font burned in ROM or FLASH specific unit. For example: unsigned char * p = (unsigned char *) 0xF000FF00; * P = 11; The significance of the above procedures written in the absolute address 0xF0000 +0 xFF00 (80186 use the 16-bit address and 16-bit offset address) 11. In absolute address pointer to pointer to increment from the result of the subtraction operation depends on the type of pointer to the data. Example p + + the result is p = 0xF000FF01, p points int, namely: int * p = (int *) 0xF000FF00; p + + (or + + p) the result is equal to: p = p + sizeof (int), and p-(or the-p) of the result is p = p- sizeof (int). Similarly, if the implementation of: long int * p = (long int *) 0xF000FF00; The results of the p + + (or + + p) of the equivalent to: p = p + sizeof (long int), and p-(or the-p) the result is p = p-sizeof (long int). Remember: CPU in bytes units addressing the C language pointer to point to the length of the data types for self-increment and decrement. Understand that the pointer to direct manipulation Memory is very important. Function pointer We must first understand the following three questions: 31
  • 33. (1) C language function names correspond directly to the address of the instruction code generated by the function in memory, so the name of the function can be directly assigned to a pointer to a function; (2) function is called is actually the same as "jumps + parameter passing the treatment + return location stack" essentially the core of the operation is a function to generate the target-generation The first address of the code assigned to the CPU PC register; (3) because of the nature of the function call code to execute the jump to an address unit, so you can "call" a function that does not exist entities Halo? Please read on: Microcomputer principle "textbook out you can get any one university, the book talks about 186 the CPU starts to jump to an absolute address 0xFFFF0 (on Should the C language pointer 0xF000FFF0 0xF000 segment address, 0xFFF0 segment offset) implementation, consider the following code: typedef void (* lpFunction) (); / * define a parameter, no return type of the function pointer type * / / * Define a function pointer to the CPU starts the execution of the first instruction position * / lpFunction lpReset = (lpFunction) 0xF000FFF0; lpReset (); / * call the function * / In the above program, we did not see any function entity, but we did perform this function call: lpReset (), it is actually from the To the role of "soft reboot" to jump to the location of the first after the start of the CPU to execute instructions. Remember: function without it, the only set of instructions to the ear; You can call a function of the body of the function, essentially just change An address to start executing instructions! Array vs. dynamic application Dynamic memory in embedded systems application there are more stringent requirements than the general system programming, this is because the embedded system's memory space is often very limited Inadvertently memory leak will soon lead to the collapse of the system. So make sure you malloc and free in pairs, if you write such a program: char * function (void) { char * p; p = (char *) malloc (...); if (p == NULL) ...; ... / * A series of p-operation * / return p; } Somewhere call function () will run out of memory function in dynamic application free, as follows: 32 char * q = function (); ... free (q);
  • 34. The above code is obviously unreasonable, because of the violation of the principle of malloc and free in pairs, ie "who apply, who is going to release" principle. Does not satisfy this Principle, will lead to the increase of the degree of coupling of the code, because the user needs to know the details of its internal function function is called! Correct approach is to apply in the call at the memory, and pass the function the function, as follows: char * p = malloc (...); if (p == NULL) ...; function (p); ... free (p); p = NULL; Function function receives the parameters p, as follows: void function (char * p) { ... / * A series of p-operation * / } Basically, the dynamic application memory with a large array of replacement. Programming novice, I recommend you to maximize the use of the array! Embedded systems to Bo The big mind receiving defective, can not "Heiner" error. After all, the most stupid way to practice hard magic Guo Jingsheng over the witty but Van political error to take the counter- revolutionary road Yang Kang. Given principles: (1) as far as the selection of the array, the array can not be cross-border access (truth over the step is the fallacy array across boundaries honorably fulfill a confusion of embedded Into the system); (2) If you are using a dynamic application, the application must determine whether the application is successful, and the malloc and free pairs! Const keyword const means "read-only". The functionality of the code is very important, but also older students heaved the following differences, if you do not know the difference between them, and have been in the program Sector fought for many years, it can only say that this is a sad: const int a; int const a; const int * a; int * const a; 33 int const * a const; (1) the role of the const keyword is very useful for people to read your code to convey information. For example, add the const keyword before the function parameter means This parameter will not be modified in the body of the function are input parameters. When there is more than one parameter, the caller of the function can whether by virtue of their parameters const Off
  • 35. The key word, clearly identify which input parameters and output parameters of what is possible. (2) a reasonable use of the const keyword allows the compiler to naturally protect those who do not want to change the parameters, to prevent unintentional code changes, such You can reduce the emergence of the bug. const in C + + language contains a richer meaning, only C language means: "read-only the ordinary variables", can be referred to as "can not be changed Variable "(This statement seems to be a mouthful, but it is the most accurate expression of the nature of the C language const), the constant need in the compilation phase remains only to # define Macro definition! Therefore follows that the procedure is illegal in the C language: const int SIZE = 10; char a [SIZE]; / * illegal: compile phase can not be used in variable * / Keyword volatile Writing C language compiler will optimize the code, for example, the following code: int a, b, c; a = inWord (0x100); / * read I / O space 0x100 port content stored in a variable * / b = a; a = inWord (0x100); / * read again the I / O space 0x100 port content stored in a variable * / c = a; Is likely to be the compiler optimization is: int a, b, c; a = inWord (0x100); / * read I / O space 0x100 port content stored in a variable * / b = a; c = a; But the results of this optimization may result in an error, if the content of the I / O space 0x100 port in the implementation of other programs after the first read operation is written to the new value, In fact, the contents read out of the 2nd read operation different from the first, the value of b and c should be different. Variable a definition with the volatile keyword can prevent the compiler Similar optimization of the device, the correct approach is to: volatile int a; volatile variables may be used in the following situations: (1) parallel device hardware registers (such as: the state register, example code, belong to this category); 34 (2) a non-automatic variable (interrupt service routine access to global variables); (3) multi-threaded applications, shared by several task variables. CPU word length is inconsistent with the memory bit wide processing Mentioned in the background papers, deliberately chose a CPU word length is inconsistent memory chips, is to conduct the discussion in this section address the CPU word length and kept The bit width of the reservoir is inconsistent. 80186 word length is 16, and the NVRAM is 8 bits wide, and in this case, we need to be provided to as NVRAM read and write bytes, words The interface, as follows: typedef unsigned char BYTE; typedef unsigned int WORD; / * Function: read the NVRAM bytes
  • 36. * Parameters: wOffset, the reading position offset relative NVRAM base address * Returns: byte read to value * / extern BYTE ReadByteNVRAM (WORD wOffset) { Why LPBYTE lpAddr = (BYTE *) (NVRAM + wOffset * 2); / * Offset to × 2? * / return * lpAddr; } / * Function: read the NVRAM word * Parameters: wOffset, the reading position offset relative NVRAM base address * Returns: Read the word * / extern WORD ReadWordNVRAM (WORD wOffset) { WORD wTmp = 0; LPBYTE lpAddr; / * Read high byte * / Why lpAddr = (BYTE *) (NVRAM + wOffset * 2); / * offset to × 2? * / wTmp + = (* lpAddr) * 256; / * Read the low byte * / Why lpAddr = (BYTE *) (NVRAM + (wOffset +1) * 2); / * offset to × 2? * / wTmp + = * lpAddr; return wTmp; } / * Function: to write a byte in the NVRAM * Parameters: wOffset writing position offset relative to the base address in the NVRAM * ByData, bytes to be written * / 35 extern void WriteByteNVRAM (WORD wOffset, BYTE byData) { ... } / * Function: to the NVRAM write a word * / * Parameters: wOffset writing position offset relative to the base address in the NVRAM * WData, want to write the word * / extern void WriteWordNVRAM (WORD wOffset, WORD wData) { ... } Zi Gong asked, saying: Why offset multiplied by 2? Confucius: a look at Figure 1, 16-bit 80186 and interconnection between eight NVRAM can only address lines A1 its A0 the CPU itself A0 and NVRAM connection. Therefore, The NVRAM address can only be an even address, so each unit marched to 0x10! Figure 1 CPU NVRAM address lines
  • 37. The Zigong ask: So why 80186 does not address lines A0 A0 connection with the NVRAM? Confucius: to see IT Analects "Microcomputer Principle articles" that tells the sage composed of about a computer. Summary This paper focuses on the memory operation in embedded systems C programming skills. Master and in-depth understanding of the data pointer, function pointers, dynamic application memory const and volatile keywords related knowledge, the basic requirements of a good C language programmers. When we have a firm grasp of these skills, We have learned 99% of the C language, because of the connotations of the best in the C language are embodied in the memory operations. The reason we use in embedded systems C language programming, 99% of memory because of its powerful ability to operate! If you love programming, you love the C language; If you love the C language, you love pointer; If you love pointer please you love pointer to a pointer! C language embedded systems programming practice: screen operation Author: Song Baohua Update Date :2005-22 Chinese Processing To solve the problem, often used in embedded systems is not a complete character base, often only need to provide a limited number of Chinese characters for the necessary Display function. For example, a microwave oven on the LCD does not need to provide the functionality of the displayed "Email"; one to provide an air conditioner on the LCD of the Chinese character display function without To display a short message, and so on. But a mobile phone, PHS, you usually need to include complete 汉字库. If the included 汉字库 complete, then, by the internal code to calculate the offset of the character font library is very simple: the Chinese character library is arranged in order of location , The first byte of the character area code, and after a bit number of bytes of the word. 94 characters each district records, the bit number compared with the position of the word in the area. Because Chinese characters in the Chinese character library specific location is calculated as follows: 94 (area code -1) + bit number -1. Minus 1 because the array is based on the area code begins bit No. 1 open Beginning. Simply multiply the number of bytes that can be occupied by a character font: (94 * (area codes -1) + bit number -1) * number of bytes occupied by a character font, 16 * 16 dot matrix characters The library, for example, the formula was: (94 * (area code -1) + (bit number -1)) * 32. Chinese character library records from the 32 bytes from the position of the word font information. Contains more complete character base system, we can calculate the position of the matrix above rules. However, if only to provide a small amount of Chinese characters do? For example, a few 10 to a few hundred? The best practice is to: Define the macro: # Define EX_FONT_CHAR (value) # Define EX_FONT_UNICODE_VAL (value) (value),
  • 38. # Define EX_FONT_ANSI_VAL (value) (value), Define the structure: typedef struct _wide_unicode_font16x16 { WORD value; / * internal code * / BYTE data [32]; / * font dot matrix * / } Unicode; # Define CHINESE_CHAR_NUM ... / * the kanji number of * / Font storage with an array: Unicode chinese [CHINESE_CHAR_NUM] = { { EX_FONT_CHAR ("industry") EX_FONT_UNICODE_VAL (0x4e1a) 37 {0x04, 0x40, 0x04, 0x40, 0x04, 0x40, 0x04, 0x44, 0x44, 0x46, 0x24, 0x4c, 0x24, 0x48, 0x14, 0x50, 0x1c, 0x50, 0x14, 0x60, 0x04, 0x40, 0x04, 0x40, 0x04, 0x44, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00} } { EX_FONT_CHAR ("in") EX_FONT_UNICODE_VAL (0x4e2d) {0x01, 0x00, 0x01, 0x00, 0x21, 0x08, 0x3f, 0xfc, 0x21, 0x08, 0x21, 0x08, 0x21, 0x08, 0x21, 0x08, 0x21, 0x08, 0x3f, 0xf8, 0x21, 0x08, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00} } { EX_FONT_CHAR ("cloud") EX_FONT_UNICODE_VAL (0x4e91) {0x00, 0x00, 0x00, 0x30, 0x3f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0xff, 0xfe, 0x03, 0x00, 0x07, 0x00, 0x06, 0x40, 0x0c, 0x20, 0x18, 0x10, 0x31, 0xf8, 0x7f, 0x0c, 0x20, 0x08, 0x00, 0x00} } { EX_FONT_CHAR ("pieces") EX_FONT_UNICODE_VAL (0x4ef6) {0x10, 0x40, 0x1a, 0x40, 0x13, 0x40, 0x32, 0x40, 0x23, 0xfc, 0x64, 0x40, 0xa4, 0x40, 0x28, 0x40, 0x2f, 0xfe, 0x20, 0x40, 0x20, 0x40, 0x20, 0x40, 0x20, 0x40, 0x20, 0x40, 0x20, 0x40, 0x20, 0x40} } } Specific Chinese characters to be displayed, simply from the array of internal codes and the same
  • 39. characters in the code to get the font. If the front of the Chinese characters in the array to Within the code size of the order, and you can find more efficient binary search method to the matrix of the Chinese characters. This method is a very effective organization of small Store, it can ensure that the program has a very good structure. System time display Time, the system can be read from the NVRAM system generated general With NVRAM seconds interrupts per second read time and displayed on the LCD. About when Between the display, there is a question of efficiency. Time, changes in the 60 seconds it is only once a minute, 60 minutes before the hour change, if Every time we will read the time on the screen completely re-refresh system and waste a lot of time. A better approach is our time display function static variables are stored in hours, minutes, seconds, and only when its content changes update Its display. extern void DisplayTime (...) { 38 static BYTE byHour, byMinute, bySecond; BYTE byNewHour, byNewMinute, byNewSecond; byNewHour = GetSysHour (); byNewMinute = GetSysMinute (); byNewSecond = GetSysSecond (); if (byNewHour! = byHour) { / * Hours * / byHour = byNewHour; } if (byNewMinute! = byMinute) { / * Minutes * / byMinute = byNewMinute; } if (byNewSecond! = bySecond) { / * Seconds * / bySecond = byNewSecond; } } This example also incidentally as proof of the power of the static keyword in C language. Of course, in the C + + language, static has a more powerful Wei Force, it makes some of the data and functions from the "object" and become part of the "class" of this characteristic is its numerous outstanding achievements in the software design. Animation display The animation does not matter, it does not matter no more way to go still picture, will become the animation. To different still displayed on the screen as the time changes,
  • 40. Screen, that is the essence of the animation. So, in an embedded system on the LCD to be displayed animation, requires the help of a timer. No hardware or software timer world Is impossible to imagine: (1) there is no timer, an operating system will not be able to time slice rotation, so can not multi- task scheduling, so they no longer into more than one Tasking operating system; (2) there is no timer, a multimedia player software will not work, because it does not know when it should switch to the next frame; (3) there is no timer, a network protocol will not be able to operate because of its timeout and retransmit the packet transmission can not be informed when, and can not be done at a specific time special Given task. Therefore, there is no timer will mean that no operating system, no network, no multimedia, this will be what darkness? Therefore, a reasonable and flexible use Types of timers, is the most basic needs of a software person! 80186-based chip embedded systems, we need the help of a hardware timer interrupt as a software timer interrupt occurs, change screen display Display content. "Xx: xx" in the time display alternately with or without colon, every time seconds interrupt occurs, call ShowDot: 39 void ShowDot () { static BOOL bShowDot = TRUE; / * once again experience the power of the static keyword * / if (bShowDot) { showChar (':', xPos, yPos); } else { showChar ('', xPos, yPos); } bShowDot =! bShowDot; } Menu operation Brains of countless people finally appeared, in this section, we will see a little bit object-oriented thinking, even in the C language used soft Pieces of structure such as what will be changed! I once was a fool, menu engage halo, given such a system: Figure 1 menu example Requirements on the keyboard "← →" key to switch the menu focus, if tap OK on the keyboard when the user focus at a menu CANCEL key to call the focus Menu handling functions corresponding. I once innocently doing so: / * Press the OK button * / void onOkKey () { / * Judgment on what the focus of the menu press the Ok key, call the appropriate handler
  • 41. function * / Switch (currentFocus) { case MENU1: menu1OnOk (); break; case MENU2: menu2OnOk (); break; ... } } 40 / * Press the Cancel key * / void onCancelKey () { / * Judgment on what the focus of the menu press the Cancel key, call the appropriate handler function * / Switch (currentFocus) { case MENU1: menu1OnCancel (); break; case MENU2: menu2OnCancel (); break; ... } } Finally one day, I do this: / * Attributes of the menu and the operation of a "package" together * / typedef struct tagSysMenu { char * text; / * menu text * / BYTE xPos; / * menu on the LCD x coordinate * / BYTE yPos; / * menu on the LCD y coordinates * / void (* onOkFun) (); / * press the menu the ok key processing function pointer * / void (* onCancelFun) (); / * pointer on the menu, press the cancel key processing functions * / } SysMenu, * LPSysMenu; When I define the menu, only this: static SysMenu menu [MENU_NUM] = { { "Menu1", 0, 48, menu1OnOk, menu1OnCancel } And
  • 42. { "Menu2", 7, 48, menu2OnOk, menu2OnCancel } And { "Menu3", 7, 48, menu3OnOk, menu3OnCancel } 41 And { "Menu4", 7, 48, menu4OnOk, menu4OnCancel } ... }; OK and CANCEL keys processing becomes: / * Press the OK button * / void onOkKey () { menu [currentFocusMenu]. onOkFun (); } / * Press the Cancel key * / void onCancelKey () { menu [currentFocusMenu]. onCancelFun (); } Procedure is greatly simplified, and also began with good scalability. We only use of the package in the object-oriented thinking, let the program structure clear its junction Fruit is almost in the system in the case without the need to modify the program to add more menu key handler of the system remains unchanged. Object-oriented true God! Analog MessageBox function MessageBox function in the Windows programming the Super Mengliao, I do not know how many beginners, the first to use the function. Remember the first time we Windows MessageBox output "Hello, World!" Dialog box appears strange feeling it? Not statistics, how many programmers to learn this world Windows programming from MessageBox ("Hello, World!", ...). Widespread in my undergraduate school, with a vocabulary called "'Hello, World' Level programmer ", refers to the entry-level programmers, but it seems that the saying 'Hello, World' class" funny and image. Figure 2 classic Hello, World! Figure 2 shows the two eternal classic Hello, World dialog box, one has only to "OK", one contains the "OK", "Cancel." Yes, MessageBox Indeed, but should also have two categories! This is completely determined by the specific application requirements. Embedded system did not give us the MessageBox, but given its powerful, we need to simulate, an analog MessageBox function:
  • 43. 42 / ****************************************** / * Function name: MessageBox / * Function Description: The pop-up dialog box, displayed to remind the user of the information / * Parameters: lpStr --- string output information to remind the user / * TYPE --- output, format (ID_OK = 0, ID_OKCANCEL = 1) / * Return value: return to the dialog box to receive the keys, there are only two KEY_OK, KEY_CANCEL / ****************************************** typedef enum TYPE {ID_OK, ID_OKCANCEL} MSG_TYPE; extern BYTE MessageBox (LPBYTE lpStr, BYTE TYPE) { BYTE keyValue = -1; ClearScreen (); / * Clear the screen * / DisplayString (xPos, yPos, lpStr, TRUE); / * Display the string * / / * Whether to show the decision of the dialog box, type OK, cancel * / switch (TYPE) { case ID_OK: DisplayString (13, yPos + High +1, "OK", 0); break; case ID_OKCANCEL: DisplayString (8, yPos + High +1, "OK", 0); DisplayString (17, yPos + High +1, "Cancel", 0); break; default: break; } DrawRect (0, 0, 239, yPos + High +16 +4); / * draw a frame * / / * MessageBox is a modal dialog, blocking running, waiting for the button * / while ((keyValue! = KEY_OK) | | (keyValue! = KEY_CANCEL)) { keyValue = getSysKey (); } / * Return key type * / if (keyValue == KEY_OK) { return ID_OK; } else { return ID_CANCEL; } } 43 Above function we usually use the MessageBox VC + + how some similarities? To achieve this
  • 44. function, you will see it in the embedded system The magical effect is endless. Summary This is the deepest one of skill in this series of articles, which provides embedded system screen display of some very clever approach, and the flexibility to use them, We will no longer be plagued by messy on the LCD display content. The screen is an important auxiliary embedded systems survive terrifying the display will get away with another user. Screen programming, if handled properly, will be the software system, The most confusing part, I have suffered. C language embedded systems programming practice of: keyboard operation Author: Song Baohua Update Date :2005-22 Processing function keys The problem is that of the function keys, the user interface is not fixed, and the choice of user function key will allow the screen is in a different display state. For example, the main screen, such as Figure 1: Figure 1 of the main screen When users press the Enter key on the set XX, the screen switches to set XX of the interface, as shown in Figure 2: Switch to XX screen How to determine whether the user program in which screen and calls the corresponding function key processing functions, but also to ensure a good structure in the program status screen, is a A question worth considering. Let's take a look at the "window" concept used in the WIN32 programming, message (message) is sent to a different window, the window message processing function 44 (A callback function) was eventually called, the window message processing function is called according to the type of the message in the window corresponding processing function. By this way, the Win32 effective organization of different window, and processing the message in the case of different window. We learn that: (1) a different screen analogy the WIN32 in different windows, the window of the various elements (menus, buttons, etc.) included in the window being; (2) to each screen provides a function key "message processing function, the function receive key information as a parameter; (3) screen function keys "message processing function to determine the types of buttons and the current focus elements, and calls the corresponding elements of the key processing functions. / * Window elements, message processing function package in the window * / struct windows { BYTE currentFocus; ELEMENT element [ELEMENT_NUM]; void (* messageFun) (BYTE keyValue); ... };
  • 45. / * Message processing function * / void messageFunction (BYTE keyValue) { BYTE i = 0; / * Get the focus element * / while ((element [i]. ID! = currentFocus) && (i <ELEMENT_NUM)) { i + +; } / * Message map "* / if (i <ELEMENT_NUM) { switch (keyValue) { case OK: element [i]. OnOk (); break; ... } } } The process is similar to corresponding elements key function in the window message processing function call "message map", which is that we learn from the WIN32 programming. Program To a realm, a lot of things are the same. Elsewhere thinking can be used to take over for me, "ism" programming. 45 In this example, if we would like to play a little larger, and we can learn from the processing MESSAGE_MAP method in the MFC, we can also learn MFC scheduled Defined several sophisticated macros to achieve the "message map". Dealing with the number keys User to enter numbers when an A input, an input corresponds to a display position on the screen (x coordinate, y coordinate). In addition, the program further Record of the location of the input value, user digital input is the best way to define a structure so effectively organize, coordinate and numerical bundled: / * User digital input structure * / typedef struct tagInputNum { The BYTE byNum; / * receives user input assignment * / BYTE xPos; / * digital input on the screen display position of the x coordinate * / BYTE yPos; / * digital input on the screen display position y coordinates * / } InputNum, * LPInputNum; Receive user input can define an array of structures, with the array to form a complete digital: InputNum inputElement [NUM_LENGTH]; / * receive user digital input array * / / * Digital key handler * / extern void onNumKey (BYTE num) {
  • 46. if (num == 0 | | num == 1) / * receive only binary input * / { / * Display on the screen the user input * / DrawText (inputElement [currentElementInputPlace]. XPos, inputElement [currentElementInputPlace]. yPos, "% 1d", num); / * Input assigned to the array element * / inputElement [currentElementInputPlace]. byNum = num; / * The focus and the cursor right * / moveToRight (); } } Every digital input coordinates and enter the value of bundled digital key processing functions more structural organization program, the program appeared to be very compact. Organize user input Continue the example of the two, in 2 onNumKey function, just to get every one of the numbers, and therefore we need to be converted to valid data, give an example To XXX data into effective method is: / * Converted into binary data bits valid data: XXX * / void convertToXXX () { 46 BYTE i; XXX = 0; for (i = 0; i <NUM_LENGTH; i + +) { XXX + = inputElement [i]. ByNum * power (2, NUM_LENGTH - i - 1); } } Instead, we may also need to be displayed on the screen valid data bit, because we also need to be able to reverse conversion: / * Valid data into binary data bits: XXX * / void convertFromXXX () { BYTE i; XXX = 0; for (i = 0; i <NUM_LENGTH; i + +) { inputElement [i]. byNum = XXX / power (2, NUM_LENGTH - i - 1)% 2; } } In the above examples, of course, because the data is binary, with a power function is not a good choice, direct use of efficient "<< >>" shift operation, we Only to illustrate the convenience of the problem. Just think, if the user input is decimal, power function may be the only choice. Summary The this keyboard operation involved in all aspects: the function key processing, digital key