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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

/* Example of nested for loops */

for(i = 0; i < 10; i++) {

for(j = 0; j < 5; j++) {

Statements;

}

}

In the following example, the sum of all the elements of a 3×4 matrix M is calculated and stored in a variable called Sum :

/* Add all elements of a 3x4 matrix */

Sum = 0;

for(i = 0; i < 3; i++) {

for(j = 0; j < 4; j++) {

Sum = Sum + M[i][j];

}

}

Since there is only one statement to be executed, the preceding example could also be written as:

/* Add all elements of a 3x4 matrix */

Sum = 0;

for(i = 0; i < 3; i++) {

for(j = 0; j < 4; j++) Sum = Sum + M[i][j];

}

while Statement The syntax of a while statement is:

while (condition) {

Statements;

}

Here, the statements are executed repeatedly until the condition becomes false, or the statements are executed repeatedly as long as the condition is true. If the condition is false on entry to the loop, then the loop will not be executed and the program will continue from the end of the while loop. It is important that the condition is changed inside the loop, otherwise an endless loop will be formed.

The following code shows how to set up a loop to execute 10 times, using the while statement:

/* A loop that executes 10 times */

k = 0;

while (k < 10) {

Statements;

k++;

}

At the beginning of the code, variable k is 0. Since k is less than 10, the while loop starts. Inside the loop the value of k is incremented by 1 after each iteration. The loop repeats as long as k 10 and is terminated when k = 10. At the end of the loop the value of k is 10.

Notice that an endless loop will be formed if k is not incremented inside the loop:

/* An endless loop */

k = 0;

while (k < 10) {

Statements;

}

An endless loop can also be formed by setting the condition to be always true:

/* An endless loop */

while (k == k) {

Statements;

}

Here is an example of calculating the sum of numbers from 1 to 10 and storing the result in a variable called sum:

/* Calculate the sum of numbers from 1 to 10 */

unsigned int k, sum;

k = 1;

sum = 0;

while(k <= 10) {

sum = sum + k;

k++;

}

It is possible to have a while statement with no body. Such a statement is useful, for example, if we are waiting for an input port to change its value. An example follows where the program will wait as long as bit 0 of PORTB (PORTB.0) is at logic 0. The program will continue when the port pin changes to logic 1:

while(PORTB.0 == 0); // Wait until PORTB.0 becomes 1

or

while(PORTB.0);

It is also possible to have nested while statements.

do Statement A do statement is similar to a while statement except that the loop executes until the condition becomes false, or, the loop executes as long as the condition is true. The condition is tested at the end of the loop. The syntax of a do statement is:

do {

Statements;

} while (condition);

The first iteration is always performed whether the condition is true or false. This is the main difference between a while statement and a do statement. The following code shows how to set up a loop to execute 10 times using the do statement:

/* Execute 10 times */

k = 0;

do {

Statements;

k++;

} while (k < 10);

The loop starts with k = 0, and the value of k is incremented inside the loop after each iteration. At the end of the loop k is tested, and if k is not less than 10, the loop terminates. In this example because k = 0 is at the beginning of the loop, the value of k is 10 at the end of the loop.

An endless loop will be formed if the condition is not modified inside the loop, as shown in the following example. Here k is always less than 10:

/* An endless loop */

k = 0;

do {

Statements;

} while (k < 10);

An endless loop can also be created if the condition is set to be true all the time:

/* An endless loop */

do {

Statements;

} while (k == k);

It is also possible to have nested do statements.

Unconditional Modifications of Flow

goto Statement A goto statement can be used to alter the normal flow of control in a program. It causes the program to jump to a specified label. A label can be any alphanumeric character set starting with a letter and terminating with the colon (“:”) character.

Although not recommended, a goto statement can be used together with an if statement to create iterations in a program. The following example shows how to set up a loop to execute 10 times using goto and if statements:

/* Execute 10 times */

k = 0;

Loop:

Statements;

k++;

if (k < 10) goto Loop;

The loop starts with label Loop and variable k = 0 at the beginning of the loop. Inside the loop the statements are executed and k is incremented by 1. The value of k is then compared with 10 and the program jumps back to label Loop if k 10. Thus, the loop is executed 10 times until the condition at the end becomes false. At the end of the loop the value of k is 10.

continue and break Statements continue and break statements can be used inside iterations to modify the flow of control. A continue statement is usually used with an if statement and causes the loop to skip an iteration. An example follows that calculates the sum of numbers from 1 to 10 except number 5:

/* Calculate sum of numbers 1,2,3,4,6,7,8,9,10 */

Sum = 0;

i = 1;

for(i = 1; i <= 10; i++) {

if (i == 5) continue; // Skip number 5

Sum = Sum + i;

}

Similarly, a break statement can be used to terminate a loop from inside the loop. In the following example, the sum of numbers from 1 to 5 is calculated even though the loop parameters are set to iterate 10 times:

/* Calculate sum of numbers 1,2,3,4,5 */

Sum = 0;

i = 1;

for(i = 1; i <= 10; i++) {

if (i > 5) break; // Stop loop if i > 5

Sum = Sum + i;

}

3.1.20 Mixing mikroC with Assembly Language Statements

It sometimes becomes necessary to mix PIC microcontroller assembly language statements with the mikroC language. For example, very accurate program delays can be generated by using assembly language statements. The topic of assembly language is beyond the scope of this book, but techniques for including assembly language instructions in mikroC programs are discussed in this section for readers who are familiar with the PIC microcontroller assembly languages.

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

Интервал:

Закладка:

Сделать

Похожие книги на «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