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

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

Интервал:

Закладка:

Сделать

float Area(float radius);

This function prototype could also be declared as:

float Area(float);

Function prototypes should be declared at the beginning of a program. Function definitions and function calls can then be made at any point in the program.

Example 4.5

Repeat Example 4.4 but declare LowerToUpper as a function prototype.

Solution 4.5

Figure 4.7 shows the program where function LowerToUpper is declared as a function prototype at the beginning of the program. In this example, the actual function definition is written after the main program.

/**********************************************************************

LOWERCASE TO UPPERCASE

=========================

This program converts the lowercase character in variable Lc to uppercase

and stores in variable Uc.

Programmer: Dogan Ibrahim

File: LTOUPPER2.C

Date: May, 2007

************************************************************************/

unsigned char LowerToUpper(unsigned char);

/* Start of main program */

void main() {

unsigned char Lc, Uc;

Lc = 'r';

Uc = LowerToUpper(Lc);

}

/* Function to convert a lower case character to upper case */

unsigned char LowerToUpper(unsigned char c) {

if (c >= 'a' && c <= 'z') return (c - 0x20);

else return c;

}

картинка 75

Figure 4.7: Program using function prototype

One important advantage of using function prototypes is that if the function prototype does not match the actual function definition, mikroC will detect this and modify the data types in the function call to match the data types declared in the function prototype. Suppose we have the following code:

unsigned char c = 'A';

unsigned int x = 100;

long Tmp;

long MyFunc(long a, long b); // function prototype

void main() {

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

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

Tmp = MyFunc(c, x);

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

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

}

In this example, because the function prototype declares the two arguments as long , variables c and x are converted to long before they are used inside function MyFunc .

4.1.2 Passing Arrays to Functions

There are many applications where we may want to pass arrays to functions. Passing a single array element is straightforward, as we simply specify the index of the array element to be passed, as in the following function call which passes the second element (index = 1) of array A to function Calc . It is important to realize that an individual array element is passed by value (i.e., a copy of the array element is passed to the function):

x = Calc(A[1]);

In some applications we may want to pass complete arrays to functions. An array name can be used as an argument to a function, thus permitting the entire array to be passed. To pass a complete array to a function, the array name must appear by itself within the brackets. The size of the array is not specified within the formal argument declaration. In the function header the array name must be specified with a pair of empty brackets. It is important to realize that when a complete array is passed to a function, what is actually passed is not a copy of the array but the address of the first element of the array (i.e., the array elements are passed by reference , which means that the original array elements can be modified inside the function).

Some examples follow that illustrate the passing of a complete array to a function.

Example 4.6

Write a program to store the numbers 1 to 10 in an array called Numbers . Then call a function named Average to calculate the average of these numbers.

Solution 4.6

The required program listing is shown in Figure 4.8. Function Average receives the elements of array Numbers and calculates the average of the array elements.

/********************************************************************

PASSING AN ARRAY TO A FUNCTION

==============================

This program stores numbers 1 to 10 in an array called Numbers. Function

Average is then called to calculate the average of these numbers.

Programmer: Dogan Ibrahim

File: AVERAGE.C

Date: May, 2007

*********************************************************************/

/* Function to calculate the average */

float Average(int A[]) {

float Sum = 0.0, k;

unsigned char j;

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

Sum = Sum + A[j];

}

k = Sum / 10.0;

return k;

}

/* Start of the main program */

void main() {

unsigned char j;

float Avrg;

int Numbers[10];

for (j=0; j<10; j++) Numbers[j] = j+1;

Avrg = Average(Numbers);

}

картинка 76

Figure 4.8: Program passing an array to a function

Example 4.7

Repeat Example 4.6, but this time define the array size at the beginning of the program and then pass the array size to the function.

Solution 4.7

The required program listing is shown in Figure 4.9.

/*********************************************************************

PASSING AN ARRAY TO A FUNCTION

==============================

This program stores numbers 1 to N in an array called Numbers where N is

defined at the beginning of the program. Function Average is then called to

calculate the average of these numbers.

Programmer: Dogan Ibrahim

File: AVERAGE2.C

Date: May, 2007

***********************************************************************/

#define Array_Size 20

/* Function to calculate the average */

float Average(int A[], int N) {

float Sum = 0.0, k;

unsigned char j;

for (j=0; j

Sum = Sum + A[j];

}

k = Sum / N;

return k;

}

/* Start of the main program */

void main() {

unsigned char j;

float Avrg;

int Numbers[Array_Size];

for (j=0; j

Avrg = Average(Numbers, Array_Size);

}

картинка 77

Figure 4.9: Another program passing an array to a function

It is also possible to pass a complete array to a function using pointers. The address of the first element of the array is passed to the function, and the function can then manipulate the array as required using pointer operations. An example follows.

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

Интервал:

Закладка:

Сделать

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