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

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

Интервал:

Закладка:

Сделать

Usart_Init(9600); // Set baud rate

for (;;) // Endless loop

{

while(!User_Data_Ready()); // Wait for data byte

Temp = Usart_Read(); // Read data byte

Temp++; // Increment data byte

Usart_Write(Temp); // Send the byte byte

}

}

картинка 95

Figure 4.26: Program listing of Example 4.14

In PIC microcontrollers that have more than one USART, the second USART is accessed by appending a “2” to the end of the function (e.g., Usart_Write2 , Usart_Read2 , etc.).

4.3.5 Sound Library

Functions in the sound library make it possible to generate sounds in our applications. A speaker (e.g., a piezo speaker) should be connected to the required microcontroller port. The following functions are offered by the sound library:

• Sound_Init

• Sound_Play

Sound_Init

The Sound_Init function initializes the sound library and requires two parameters: the name and the bit number of the port where the speaker is connected. The address of the port name should be passed to the function. For example, if the speaker is connected to bit 3 of PORTB, then the function should be called as:

Sount_Init(&PORTB, 3);

Sound_Play

The Sound_Play function plays a sound at a specified port pin. The function receives two arguments: the period divided by 10 (TDIV) and the number of periods (N). The first parameter is the period in microcontroller cycles divided by 10. The second parameter specifies the duration (number of clock periods) of the sound.

The following formula calculates the value used as the first parameter:

Advanced PIC Microcontroller Projects in C - изображение 96

where

TDIV is the number to be used as the first parameter

F is the required sound frequency (Hz)

f is the microcontroller clock frequency (Hz)

Example 4.15

Write a program to play a sound at 1KHz, assuming the clock frequency is 4MHz. The required duration of the sound is 250 periods.

Solution 4.15

The first parameter is calculated as follows:

Since the required duration is 250 periods the function is called with the - фото 97

Since the required duration is 250 periods, the function is called with the parameters:

Sound_Play(100, 250);

4.3.6 ANSI C Library

The ANSI C library consists of the following libraries (further details on these libraries are available in the mikroC user manual):

• Ctype library

• Math library

• Stdlib library

• String library

Ctype Library

The functions in the Ctype library are mainly used for testing or data conversion. Table 4.6 lists the commonly used functions in this library.

Table 4.6: Commonly used Ctype library functions

Function Description
isalnum Returns 1 if the specified character is alphanumeric (a–z, A–Z, 0–9)
isalpha Returns 1 if the specified character is alphabetic (a–z, A–Z)
iscntrl Returns 1 if the specified character is a control character (decimal 0–31 and 127)
isdigit Returns 1 if the specified character is a digit (0–9)
islower Returns 1 if the specified character is lowercase
isprint Returns 1 if the specified character is printable (decimal 32–126)
isupper Returns 1 if the specified character is uppercase
toupper Convert a character to uppercase
tolower Convert a character to lowercase
Math Library

The functions in the Math library are used for floating point mathematical operations. Table 4.7 lists the commonly used functions in this library.

Table 4.7: Commonly used Math library functions

Function Description
acos Returns in radians the arc cosine of its parameter
asin Returns in radians the arc sine of its parameter
atan Returns in radians the arc tangent of its parameter
atan2 Returns in radians the arc tangent of its parameter where the signs of both parameters are used to determine the quadrant of the result
cos Returns the cosine of its parameter in radians
cosh Returns the hyperbolic cosine of its parameter
exp Returns the exponential of its parameter
fabs Returns the absolute value of its parameter
log Returns the natural logarithm of its parameter
log10 Returns the logarithm to base 10 of its parameter
pow Returns the power of a number
sin Returns the sine of its parameter in radians
sinh Returns the hyperbolic sine of its parameter
sqrt Returns the square root of its parameter
tan Returns the tangent of its parameter in radians
tanh Returns the hyperbolic sine of its parameter
Stdlib Library

The Stdlib library contains standard library functions. Table 4.8 lists the commonly used functions in this library.

Table 4.8: Commonly used Stdlib library functions

Function Description
abs Returns the absolute value
atof Converts ASCII character into floating point number
atoi Converts ASCII character into integer number
atol Converts ASCII character into long integer
max Returns the greater of two integers
min Returns the lesser of two integers
rand Returns a random number between 0 and 32767; function srand must be called to obtain a different sequence of numbers
srand Generates a seed for function rand so a new sequence of numbers is generated
xtoi Convert input string consisting of hexadecimal digits into integer
Example 4.16

Write a program to calculate the trigonometric sine of the angles from 0° to 90° in steps of 1° and store the result in an array called Trig_Sine .

Solution 4.16

The required program listing is shown in Figure 4.27 (program SINE.C). A loop is created using a for statement, and inside this loop the sine of the angles are calculated and stored in array Trig_Sine. Note that the angles must be converted into radians before they are used in function sin .

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

TRIGONOMETRIC SINE OF ANGLES 0 to 90 DEGREES

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

This program calculates the trigonometric sine of angles from 0 degrees to

90 degrees in steps of 1 degree. The results are stored in an array called

Trig_Sine.

Programmer: Dogan Ibrahim

File: SINE.C

Date: May, 2007

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

Интервал:

Закладка:

Сделать

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