Ibrahim Dogan - Advanced PIC Microcontroller Projects in C

Здесь есть возможность читать онлайн «Ibrahim Dogan - Advanced PIC Microcontroller Projects in C» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Burlington, Год выпуска: 2008, ISBN: 2008, Издательство: Elsevier Ltd, Жанр: Программирование, Компьютерное железо, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Advanced PIC Microcontroller Projects in C: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Advanced PIC Microcontroller Projects in C»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

• The only project book on the PIC 18 series using the C programming language
• Features 20 complete, tried and test projects
• Includes a CD-ROM of all the programs, hex listings, diagrams, and data sheets

Advanced PIC Microcontroller Projects in C — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Advanced PIC Microcontroller Projects in C», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

unsigned char Q[2][2] = { {1,0}, {0,1} };

3.1.15 Pointers

Pointers are an important part of the C language, as they hold the memory addresses of variables. Pointers are declared in the same way as other variables, but with the character (“*”) in front of the variable name. In general, pointers can be created to point to (or hold the addresses of) character variables, integer variables, long variables, floating point variables, or functions (although mikroC currently does not support pointers to functions).

In the following example, an unsigned character pointer named pnt is declared:

unsigned char *pnt;

When a new pointer is created, its content is initially unspecified and it does not hold the address of any variable. We can assign the address of a variable to a pointer using the (“&”) character:

pnt = &Count;

Now pnt holds the address of variable Count. Variable Count can be set to a value by using the character (“*”) in front of its pointer. For example, Count can be set to 10 using its pointer:

*pnt = 10; // Count = 10

which is the same as

Count = 10; // Count = 10

Or, the value of Count can be copied to variable Cnt using its pointer:

Cnt = *pnt; // Cnt = Count

Array Pointers

In C language the name of an array is also a pointer to the array. Thus, for the array:

unsigned int Total[10];

The name Total is also a pointer to this array, and it holds the address of the first element of the array. Thus the following two statements are equal:

Total[2] = 0;

and

*(Total + 2) = 0;

Also, the following statement is true:

&Total[j] = Total + j

In C language we can perform pointer arithmetic which may involve:

• Comparing two pointers

• Adding or subtracting a pointer and an integer value

• Subtracting two pointers

• Assigning one pointer to another

• Comparing a pointer to null

For example, let’s assume that pointer P is set to hold the address of array element Z[2]:

P = &Z[2];

We can now clear elements 2 and 3 of array Z, as in the two examples that follow. The two examples are identical except that in the first example pointer P holds the address of Z[3] at the end of the statements, and it holds the address of Z[2] at the end of the second set of statements:

*P = 0; // Z[2] = 0

P = P + 1; // P now points to element 3 of Z

*P = 0; // Z[3] = 0

or

*P = 0; // Z[2] = 0

*(P + 1) = 0; // Z[3] = 0

A pointer can be assigned to another pointer. In the following example, variables Cnt and Tot are both set to 10 using two different pointers:

unsigned int *i, *j; // declare 2 pointers

unsigned int Cnt, Tot; // declare two variables

i = Cnt; // i points to Cnt

*i = 10; // Cnt = 10

j = i; // copy pointer i to pointer j

Tot = *j; // Tot = 10

3.1.16 Structures

A structure can be used to collect related items that are then treated as a single object. Unlike an array, a structure can contain a mixture of data types. For example, a structure can store the personal details (name, surname, age, date of birth, etc.) of a student.

A structure is created by using the keyword struct , followed by a structure name and a list of member declarations. Optionally, variables of the same type as the structure can be declared at the end of the structure.

The following example declares a structure named Person :

struct Person {

unsigned char name[20];

unsigned char surname[20];

unsigned char nationality[20];

unsigned char age;

}

Declaring a structure does not occupy any space in memory; rather, the compiler creates a template describing the names and types of the data objects or member elements that will eventually be stored within such a structure variable. Only when variables of the same type as the structure are created do these variables occupy space in memory. We can declare variables of the same type as the structure by giving the name of the structure and the name of the variable. For example, two variables Me and You of type Person can be created by the statement:

struct Person Me, You;

Variables of type Person can also be created during the declaration of the structure as follows:

struct Person {

unsigned char name[20];

unsigned char surname[20];

unsigned char nationality[20];

unsigned char age;

} Me, You;

We can assign values to members of a structure by specifying the name of the structure, followed by a dot (“.”) and the name of the member. In the following example, the age of structure variable Me is set to 25, and variable M is assigned to the value of age in structure variable You :

Me.age = 25;

M = You.age;

Structure members can be initialized during the declaration of the structure. In the following example, the radius and height of structure Cylinder are initialized to 1.2 and 2.5 respectively:

struct Cylinder {

float radius;

float height;

} MyCylinder = {1.2, 2.5};

Values can also be set to members of a structure using pointers by defining the variable types as pointers. For example, if TheCylinder is defined as a pointer to structure Cylinder, then we can write:

struct Cylinder {

float radius;

float height;

} *TheCylinder;

TheCylinder->radius = 1.2;

TheCylinder->height = 2.5;

The size of a structure is the number of bytes contained within the structure. We can use the sizeof operator to get the size of a structure. Considering the above example,

sizeof(MyCylinder)

returns 8, since each float variable occupies 4 bytes in memory.

Bit fields can be defined using structures. With bit fields we can assign identifiers to bits of a variable. For example, to identify bits 0, 1, 2, and 3 of a variable as LowNibble and to identify the remaining 4 bits as HighNibble we can write:

struct {

LowNibble : 4;

HighNibble : 4;

} MyVariable;

We can then access the nibbles of variable MyVariable as:

MyVariable.LowNibble = 12;

MyVariable.HighNibble = 8;

In C language we can use the typedef statements to create new types of variables. For example, a new structure data type named Reg can be created as follows:

typedef struct {

unsigned char name[20];

unsigned char surname[20];

unsigned age;

} Reg;

Variables of type Reg can then be created in the same way other types of variables are created. In the following example, variables MyReg , Reg1 , and Reg2 are created from data type Reg :

Reg MyReg, Reg1, Reg2;

The contents of one structure can be copied to another structure, provided that both structures are derived from the same template. In the following example, structure variables of the same type, P1 and P2, are created, and P2 is copied to P1:

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Advanced PIC Microcontroller Projects in C»

Представляем Вашему вниманию похожие книги на «Advanced PIC Microcontroller Projects in C» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Advanced PIC Microcontroller Projects in C»

Обсуждение, отзывы о книге «Advanced PIC Microcontroller Projects in C» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x