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

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

Интервал:

Закладка:

Сделать

void Compl() {

PORTC = ~PORTC;

}

This function can be called as:

Compl();

Functions are normally defined before the start of the main program.

Some function definitions and their use in main programs are illustrated in the following examples:

Example 4.1

Write a function called Circle_Area to calculate the area of a circle where the radius is to be used as an argument. Use this function in a main program to calculate the area of a circle whose radius is 2.5cm. Store the area in a variable called Circ .

Solution 4.1

The data type of the function is declared as float. The area of a circle is calculated by the formula:

Area = πr²

where r is the radius of the circle. The area is calculated and stored in a local variable called s, which is then returned from the function:

float Circle_Area(float radius) {

float s;

s = PI * radius * radius;

return s;

}

Figure 4.2 shows how the function Circle_Area can be used in a main program to calculate the area of a circle whose radius is 2.5cm. The function is defined before the main program. Inside the main program the function is called to calculate and store the area in variable Circ.

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

AREA OF A CIRCLE

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

This program calls to function Circle_Area to calculate the area of a circle.

Programmer: Dogan Ibrahim

File: CIRCLE.C

Date: May, 2007

********************************************************************

/* This function calculates the area of a circle given the radius */

float Circle_Area(float radius) {

float s;

s = PI * radius * radius;

return s;

}

/* Start of main program. Calculate the area of a circle where radius = 2.5 */

void main() {

float r, Circ;

r = 2.5;

Circ = Circle_Area(r);

}

картинка 70

Figure 4.2: Program to calculate the area of a circle

Example 4.2

Write a function called Area and a function called Volume to calculate the area and volume of a cylinder respectively. Then write a main program to calculate the area and the volume of cylinder whose radius is 2.0cm and height is 5.0cm. Store the area in variable cyl_area and the volume in variable cyl_volume .

Solution 4.2

The area of a cylinder is calculated by the formula:

Area = 2πrh

where r and h are the radius and height of the cylinder. The volume of a cylinder is calculated by the formula:

Volume = πr²h

Figure 4.3 shows the functions that calculate the area and volume of a cylinder. The main program that calculates the area and volume of a cylinder whose radius=2.0cm and height=5.0cm is shown in Figure 4.4.

float Area(float radius, float height) {

float s;

s = 2.0*PI * radius*height;

return s;

}

float Volume(float radius, float height) {

float s;

s = PI *radius*radius*height;

return s;

}

картинка 71

Figure 4.3: Functions to calculate cylinder area and volume

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

AREA AND VOLUME OF A CYLINDER

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

This program calculates the area and volume of a cylinder whose radius is

2.0cm and height is 5.0cm.

Programmer: Dogan Ibrahim

File: CYLINDER.C

Date: May, 2007

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

/* Function to calculate the area of a cylinder */

float Area(float radius, float height) {

float s;

s = 2.0*PI * radius*height;

return s;

}

/* Function to calculate the volume of a cylinder */

float Volume(float radius, float height) {

float s;

s = PI *radius*radius*height;

return s;

}

/* Start of the main program */

void main() {

float r = 2.0, h = 5.0;

float cyl_area, cyl_volume;

cyl_area = Area(r, h);

cyl_volume(r, h);

}

картинка 72

Figure 4.4: Program that calculates the area and volume of a cylinder

Example 4.3

Write a function called LowerToUpper to convert a lowercase character to uppercase.

Solution 4.3

The ASCII value of the first uppercase character (‘A’) is 0x41. Similarly, the ASCII value of the first lowercase character (‘a’) is 0x61. An uppercase character can be converted to its equivalent lowercase by subtracting 0x20 from the character. The required function listing is shown in Figure 4.5.

unsigned char LowerToUpper(unsigned char c) {

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

else return c;

}

картинка 73

Figure 4.5: Function to convert lowercase to uppercase

Example 4.4

Use the function you created in Example 4.3 in a main program to convert letter ‘r’ to uppercase.

Solution 4.4

The required program is shown in Figure 4.6. Function LowerToUpper is called to convert the lowercase character in variable Lc to uppercase and store in Uc .

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

LOWERCASE TO UPPERCASE

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

This program converts the lowercase character in variable Lc to uppercase

and stores in variable Uc.

Programmer: Dogan Ibrahim

File: LTOUPPER.C

Date: May, 2007

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

/* 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;

}

/* Start of main program */

void main() {

unsigned char Lc, Uc;

Lc = 'r';

Uc = LowerToUpper(Lc);

}

картинка 74

Figure 4.6: Program calling function LowerToUpper

4.1.1 Function Prototypes

If a function is not defined before it is called, the compiler will generate an error message. One way around this problem is to create a function prototype. A function prototype is easily constructed by making a copy of the function’s header and appending a semicolon to it. If the function has parameters, giving names to these parameters is not compulsory, but the data type of the parameters must be defined. An example follows in which a function prototype called Area is declared and the function is expected to have a floating point type parameter:

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

Интервал:

Закладка:

Сделать

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