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

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

Интервал:

Закладка:

Сделать

Assembly language instructions can be included in a mikroC program by using the keyword asm (or _asm , or __asm ). A group of assembly instructions or a single such instruction can be included within a pair of curly brackets. The syntax is:

asm {

assembly instructions

}

Assembly language style comments (a line starting with a semicolon character) are not allowed, but mikroC does allow both types of C style comments to be used with assembly language programs:

asm {

/* This assembly code introduces delay to the program*/

MOVLW 6 // Load W with 6

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

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

}

User-declared C variables can be used in assembly language routines, but they must be declared and initialized before use. For example, C variable Temp can be initialized and then loaded to the W register as:

unsigned char Temp = 10;

asm {

MOVLW Temp // W = Temp = 10

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

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

}

Global symbols such as predefined port names and register names can be used in assembly language routines without having to initialize them:

asm {

MOVWF PORTB

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

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

}

3.2 PIC Microcontroller Input-Output Port Programming

Depending on the type of microcontroller used, PIC microcontroller input-output ports are named as PORTA, PORTB, PORTC, and so on. Port pins can be in analog or digital mode. In analog mode, ports are input only and a built-in analog-to-digital converter and multiplexer circuits are used. In digital mode, a port pin can be configured as either input or output. The TRIS registers control the port directions, and there are TRIS registers for each port, named as TRISA, TRISB, TRISC, and so on. Clearing a TRIS register bit to 0 sets the corresponding port bit to output mode. Similarly, setting a TRIS register bit to 1 sets the corresponding port bit to input mode.

Ports can be accessed as a single 8-bit register, or individual bits of a port can be accessed. In the following example, PORTB is configured as an output port and all its bits are set to a 1:

TRISB = 0; // Set PORTB as output

PORTB = 0xFF; // Set PORTB bits to 1

Similarly, the following example shows how the 4 upper bits of PORTC can be set as input and the 4 lower bits of PORTC can be set as output:

TRISC = 0xF0;

Bits of an input-output port can be accessed by specifying the required bit number. In the following example, variable P2 is loaded with bit 2 of PORTB:

P2 = PORTB.2;

All the bits of a port can be complemented by the statement:

PORTB = ~PORTB;

3.3 Programming Examples

In this section, some simple programming examples are given to familiarize the reader with programming in C.

Example 3.2

Write a program to set all eight port pins of PORTB to logic 1.

Solution 3.2

PORTB is configured as an output port, and then all port pins are set to logic 1 by sending hexadecimal number 0xFF:

void main() {

TRISB = 0; // Configure PORTB as output

PORTB = 0xFF; // Set all port pins to logic a

}

Example 3.3

Write a program to set the odd-numbered PORTB pins (bits 1, 3, 5, and 7) to logic 1.

Solution 3.3

Odd-numbered port pins can be set to logic 1 by sending the bit pattern 10101010 to the port. This bit pattern is the hexadecimal number 0xAA and the required program is:

void main() {

TRISB = 0; // Configure PORTB as output

PORTB = 0xAA; // Turn on odd numbered port pins

}

Example 3.4

Write a program to continuously count up in binary and send this data to PORTB. Thus PORTB requires the binary data:

00000000

00000001

00000010

00000011

........

........

11111110

11111111

00000000

........

Solution 3.4

A for loop can be used to create an endless loop, and inside this loop the value of a variable can be incremented and then sent to PORTB:

void main() {

unsigned char Cnt = 0;

for(;;) // Endless loop

{

PORTB = Cnt; // Send Cnt to PORTB

Cnt++; // Increment Cnt

}

}

Example 3.5

Write a program to set all bits of PORTB to logic 1 and then to logic 0, and to repeat this process ten times.

Solution 3.5

A for statement can be used to create a loop to repeat the required operation ten times:

void main() {

unsigned char j;

for(j = 0; j < 10; j++) // Repeat 10 times

{

PORTB = 0xFF; // Set PORTB pins to 1

PORTB = 0; // Clear PORTB pins

}

}

Example 3.6

The radius and height of a cylinder are 2.5cm and 10cm respectively. Write a program to calculate the volume of this cylinder.

Solution 3.6

The required program is:

void main() {

float Radius = 2.5, Height = 10;

float Volume;

Volume = PI * Radius * Radius * Height;

}

Example 3.7

Write a program to find the largest element of an integer array having ten elements.

Solution 3.7

At the beginning, variable m is set to the first element of the array. A loop is then formed and the largest element of the array is found:

void main() {

unsigned char j;

int m, A[10];

m = A[0]; // First element of array

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

if(A[j] > m) m = A[j];

}

}

Example 3.8

Write a program using a while statement to clear all ten elements of an integer array M.

Solution 3.8

As shown in the program that follows, NUM is defined as 10 and variable j is used as the loop counter:

#define NUM 10

void main() {

int M[NUM];

unsigned char j = 0;

while (j < NUM) {

M[j] = 0;

j++;

}

}

Example 3.9

Write a program to convert the temperature from °C to °F starting from 0°C, in steps of 1°C up to and including 100°C, and store the results in an array called F.

Solution 3.9

Given the temperature in °C, the equivalent in °F is calculated using the formula:

F = (C – 32.0)/1.8

A for loop is used to calculate the temperature in °F and store in array F:

void main() {

float F[100];

unsigned char C;

for(C = 0; C <= 100; C++) {

F[C] = (C – 32.0) / 1.8;

}

}

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

Интервал:

Закладка:

Сделать

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