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

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

Интервал:

Закладка:

Сделать

3.4 Summary

There are many assembly and high-level languages for the PIC18 series of microcontrollers. This book focuses on the mikroC compiler, since it is easy to learn and a free demo version is available that allows users to develop programs as large as 2K in size.

This chapter presented an introduction to the mikroC language. A C program may contain a number of functions and variables plus a main program. The beginning of the main program is indicated by the statement void main() .

A variable stores a value used during the computation. All variables in C must be declared before they are used. A variable can be an 8-bit character, a 16-bit integer, a 32-bit long, or a floating point number. Constants are stored in the flash program memory of PIC microcontrollers, so using them avoids using valuable and limited RAM memory.

Various flow control and iteration statements such as if, switch, while, do, break , and so on have been described in the chapter, with examples.

Pointers are used to store the addresses of variables. As we shall see in the next chapter, pointers can be used to pass information back and forth between a function and its calling point. For example, pointers can be used to pass variables between a main program and a function.

3.5 Exercises

1. Write a C program to set bits 0 and 7 of PORTC to logic 1.

2. Write a C program to count down continuously and send the count to PORTB.

3. Write a C program to multiply each element of a ten element array by 2.

4. Write a C program to add two matrices P and Q. Assume that the dimension of each matrix is 3×3 and store the result in another matrix called W.

5. Repeat Exercise 4 but this time multiply matrices P and Q and store the product in matrix R.

6. What do the terms variable and constant mean?

7. What does program repetition mean? Describe the operation of while, do-while, and for loops in C.

8. What is an array? Write example statements to define the following arrays:

a) An array of ten integers

b) An array of thirty floats

c) A two-dimensional array having six rows and ten columns

9. Trace the operation of the following loops. What will be the value of variable z at the end of each loop?

a)

unsigned char j = 0, z = 0;

while (j < 10) {

z++;

j++;

}

b)

unsigned char z = 10;

for (j = 0; j < 10; j++) z--;

10. Given the following variable definitions, list the outcome of the following conditional tests in terms of “true” or “false”:

unsigned int a = 10, b = 2;

if (a > 10)

if (b >= 2)

if(a == 10)

if (a > 0)

11. Write a program to calculate whether a number is odd or even.

12. Determine the value of the following bitwise operations using AND, OR, and EXOR operations:

Operand 1: 00010001

Operand 2: 11110001

13. How many times does each of the following loops iterate, and what is the final value of the variable j in each case?

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

b) for(j = 1; j < 10; j++)

c) for(j = 0; j <= 10; j++)

d) for(j = 0; j <= 10; j += 2)

e) for(j = 10; j > 0; j -= 2)

14. Write a program to calculate the sum of all positive integer numbers from 1 to 100.

15. Write a program to evaluate factorial n, where 0! and 1! evaluate to 1 and n! = n × (n – 1)!

16. Write a program to calculate the average value of the numbers stored in an array. Assume that the array is called M and has twenty elements.

17. Modify the program in Exercise 16 to find the smallest and largest values of the array. Store the smallest value in a variable called Sml and the largest value in a variable called Lrg .

18. Derive equivalent if-else statements for the following tests:

a) (a > b) ? 0 : 1

b) (x < y) ? (a > b) : (c > d)

19. Given that f1 and f2 are both floating point variables, explain why the following test expression controlling the while loop may not be safe:

do {

...............

...............

} while(f1 != f2);

Why would the problem not occur if both f1 and f2 were integers? How would you correct this while loop?

20. What can you say about the following while loop?

k = 0;

Total = 0;

while (k < 10) {

Sum++;

Total += Sum;

}

21. What can you say about the following for loop?

Cnt = 0;

for (;;) {

Cnt++;

}

CHAPTER 4

Functions and Libraries in mikroC

4.1 mikroC Functions

A function is a self-contained section of code written to perform a specifically defined action. Functions are usually created when a single operation must be performed in different parts of the main program. It is, moreover, good programming practice to divide a large program into a number of smaller, independent functions. The statements within a function are executed by calling (or invoking) the function.

The general syntax of a function definition is shown in Figure 4.1. The data type indicates the type of data returned by the function. This is followed by the name of the function and then a set of parentheses, within which the arguments, separated by commas, are declared. The body of the function, which includes the function’s operational code, is written inside a set of curly brackets.

type name (parameter1, parameter2, ……) {

……………

function body

……………

}

картинка 69

Figure 4.1: General syntax of a function definition

In the sample function definition that follows, the function, named Mult , receives two integer arguments, a and b, and returns their product. Note that using parentheses in a return statement is optional:

int Mult(int a, int b) {

return (a*b);

}

When a function is called, it generally expects to be given the number of arguments expressed in the function’s argument list. For example, the preceding function can be called as:

z = Mult(x, y);

where variable z has the data type int . Note that the arguments declared in the function definition and the arguments passed when the function is called are independent of each other, even if they have the same name. In the preceding example, when the function is called, variable x is copied to a and variable y is copied to b on entry into function Mult .

Some functions do not return any data. The data type of such functions must be declared as void . For example:

void LED(unsigned char D) {

PORTB = D;

}

void functions can be called without any assignment statements, but the parentheses are needed to tell the compiler that a function call is made:

LED();

Also, some functions do not have any arguments. In the following example, the function, named Compl , complements PORTC of the microcontroller. It returns no data and has no arguments:

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

Интервал:

Закладка:

Сделать

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