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 main() {

unsigned char j;

double PI = 3.14159, rads;

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

rads = j * PI /180.0;

angle = sin(rad);

Trig_Sine[j] = angle;

}

}

картинка 98

Figure 4.27: Calculating the sine of angles 0 to 90

String Library

The functions in the String library are used to perform string and memory manipulation operations. Table 4.9 lists the commonly used functions in this library.

Table 4.9: Commonly used String library functions

Function Description
strcat, strncat Append two strings
strchr, strpbrk Locate the first occurrence of a character in a string
strcmp, strncmp Compare two strings
strcpy, strncpy Copy one string into another one
strlen Return the length of a string
Example 4.17

Write a program to illustrate how the two strings “MY POWERFUL” and “COMPUTER” can be joined into a new string using String library functions.

Solution 4.17

The required program listing is shown in Figure 4.28 (program JOIN.C). The mikroC String library function strcat is used to join the two strings pointed to by p1 and p2 into a new string stored in a character array called New_String .

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

JOINING TWO STRINGS

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

This program shows how two strings can be joined to obtain a new string.

mikroC library function strcat is used to join the two strings pointed to by

p1 and p2 into a new string stored in character array New_String.

Programmer: Dogan Ibrahim

File: JOIN.C

Date: May, 2007

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

void main() {

const char *p1 = "MY POWERFUL "; // First string

const char *p2 = "COMPUTER"; // Second string

char New_String[80];

strcat(strcat(New_String, p1), p2); // join the two strings

}

картинка 99

Figure 4.28: Joining two strings using function strcat

4.3.7 Miscellaneous Library

The functions in the Miscellaneous library include routines to convert data from one type to another type, as well as to perform some trigonometric functions. Table 4.10 lists the commonly used functions in this library.

Table 4.10: Commonly used Miscellaneous library functions

Function Description
ByteToStr Convert a byte into string
ShortToStr Convert a short into string
WordToStr Convert an unsigned word into string
IntToStr Convert an integer into string
LongToStr Convert a long into string
FloatToStr Convert a float into string
Bcd2Dec Convert a BCD number into decimal
Dec2Bcd Convert a decimal number into BCD

The following general programs illustrate the use of various library routines available with the mikroC language.

Example 4.18

Write a function to convert the string pointed to by p into lowercase or uppercase, depending on the value of a mode parameter passed to the function. If the mode parameter is nonzero, then convert to lowercase, otherwise convert it to uppercase. The function should return a pointer to the converted string.

Solution 4.18

The required program listing is given in Figure 4.29 (program CASE.C). The program checks the value of the mode parameter, and if this parameter is nonzero the string is converted to lowercase by calling function ToLower , otherwise the function ToUpper is called to convert the string to uppercase. The program returns a pointer to the converted string.

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

CONVERT A STRING TO LOWER/UPPERCASE

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

This program receives a string pointer and a mode parameter. If the mode is 1

then the string is converted to lowercase, otherwise the string is converted

to uppercase.

Programmer: Dogan Ibrahim

File: CASE.C

Date: May, 2007

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

unsigned char *Str_Convert(unsigned char *p, unsigned char mode) {

unsigned char *ptr = p;

if (mode != 0) {

while (*p != '\0') *p++ = ToLower(*p);

} else {

while (*p != '\0') *p++ = ToUpper(*p);

}

return ptr;

}

картинка 100

Figure 4.29: Program for Example 4.18

Example 4.19

Write a program to define a complex number structure, then write functions to add and subtract two complex numbers. Show how you can use these functions in a main program.

Solution 4.19

Figure 4.30 shows the required program listing (program COMPLEX.C). At the beginning of the program, a data type called complex is created as a structure having a real part and an imaginary part. A function called Add is then defined to add two complex numbers and return the sum as a complex number. Similarly, the function Subtract is defined to subtract two complex numbers and return the result as a complex number. The main program uses two complex numbers, a and b, where,

a = 2.0 – 3.0j

b = 2.5 + 2.0j

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

COMPLEX NUMBER ADDITION AND SUBTRACTION

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

This program creates a data structure called complex having a real part and

an imaginary part. Then, functions are defined to add or subtract two complex

numbers and store the result in another complex number.

The first complex number is, a = 2.0 – 2.0j

The second complex number is, b = 2.5 + 2.0j

The program calculates, c = a + b

and, d = a − b

Programmer: Dogan Ibrahim

File: COMPLEX.C

Date: May, 2007

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

/* Define a new data type called complex */

typedef struct {

float real;

float imag;

} complex;

/* Define a function to add two complex numbers and return the result as

a complex number */

complex Add(complex i, complex j) {

complex z;

z.real = i.real + j.real;

z.imag = i.imag + j.imag;

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

Интервал:

Закладка:

Сделать

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