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

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

Интервал:

Закладка:

Сделать

{

case Plus:

Calc = Op1 + Op2; // If ADD

break;

case Minus:

Calc = Op1 - Op2; // If Subtract

break;

case Multiply:

Calc = Op1 * Op2; // If Multiply

break;

case Divide:

Calc = Op1 / Op2; // If Divide

break;

}

LongToStr(Calc, op); // Convert to string in op

//

// Remove leading blanks

//

j=0;

for(i=0;i<=11;i++) {

if (op[i] != ' ') // If a blank

{

lcd[j]=op[i];

j++;

}

}

Lcd_Out_Cp(lcd); // Display result

Delay_ms(5000); // Wait 5 seconds

Lcd_Cmd(LCD_CLEAR);

}

}

картинка 224

Figure 6.48: Program listing

Function getkeypad receives a key from the keypad. We start by sending a 1 to column 1, and then we check all the rows. When a key is pressed, a logic 1 is detected in the corresponding row and the program jumps out of the while loop. Then a for loop is used to find the actual key pressed by the user as a number from 0 to 15.

It is important to realize that when a key is pressed or released, we get what is known as contact noise, where the key output pulses up and down momentarily, producing a number of logic 0 and 1 pulses at the output. Switch contact noise is usually removed either in hardware or by programming in a process called contact debouncing. In software the simplest way to remove the contact noise is to wait for about 20ms after a switch key is pressed or switch key is released. In Figure 6.46, contact debouncing is accomplished in function getkeypad .

Program Using a Built-in Keypad Function

In the program listing in Figure 6.48, a function called getkeypad has been developed to read a key from the keyboard. The mikroC language has built-in functions called Keypad_Read and Keypad_Released to read a key from a keypad when a key is pressed and when a key is released respectively. Figure 6.49 shows a modified program (KEYPAD2.C) listing using the Keypad_Released function to implement the preceding calculator project. The circuit diagram is the same as in Figure 6.46.

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

CALCULATOR WITH KEYPAD AND LCD

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

In this project a 4 x 4 keypad is connected to PORTB of a PIC18F452

microcontroller. Also an LCD is connected to PORTC. The project is a simple

calculator which can perform integer arithmetic.

The keys are labeled as follows:

1 2 3 4

5 6 7 8

9 0 Enter

+ − * /

In this program mikroC built-in functions are used.

Author: Dogan Ibrahim

Date: July 2007

File: KEYPAD2.C

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

#define Enter 12

#define Plus 13

#define Minus 14

#define Multiply 15

#define Divide 16

//

// Start of MAIN program

//

void main() {

unsigned char MyKey, i,j,lcd[5],op[12];

unsigned long Calc, Op1, Op2;

TRISC = 0; // PORTC are outputs (LCD)

//

// Configure LCD

//

Lcd_Init(&PORTC); // LCD is connected to PORTC

Lcd_Cmd(LCD_CLEAR);

Lcd_Out(1,1, "CALCULATOR"); // Display CALCULATOR

Delay_ms(2000);

Lcd_Cmd(LCD_CLEAR);

//

// Configure KEYPAD

//

Keypad_Init(&PORTB); // Keypad on PORTB

//

// Program loop

//

for(;;) // Endless loop

{

MyKey = 0;

Op1 = 0;

Op2 = 0;

Lcd_Out(1,1, "No1: "); // Display No1:

while(1) {

do // Get first number

MyKey = Keypad_Released();

while(!MyKey);

if (MyKey == Enter) break; // If ENTER pressed

if (MyKey == 10) MyKey = 0; // If 0 key pressed

Lcd_Chr_Cp(MyKey + '0');

Op1 = 10*Op1 + MyKey;

}

Lcd_Out(2,1, "No2: "); // Display No2:

while(1) // Get second no

{

do

MyKey = Keypad_Released(); // Get second number

while(!MyKey);

if (MyKey == Enter) break; // If ENTER pressed

if (MyKey == 10) MyKey = 0; // If 0 key pressed

Lcd_Chr_Cp(MyKey + '0');

Op2 = 10*Op2 + MyKey;

}

Lcd_Cmd(LCD_CLEAR);

Lcd_Out(1,1, "Op: "); // Display Op:

do

MyKey = Keypad_Released(); // Get operation

while(!MyKey);

Lcd_Cmd(LCD_CLEAR);

Lcd_Out(1,1, "Res="); // Display Res=

switch(MyKey) // Perform the operation

{

case Plus:

Calc = Op1 + Op2; // If ADD

break;

case Minus:

Calc = Op1 - Op2; // If Subtract

break;

case Multiply:

Calc = Op1 * Op2; // If Multiply

break;

case Divide:

Calc = Op1 / Op2; // If Divide

break;

}

LongToStr(Calc, op); // Convert to string

//

// Remove leading blanks

//

j=0;

for(i=0;i<=11;i++) {

if (op[i] != ' ') // If a blank

{

lcd[j]=op[i];

j++;

}

}

Lcd_Out_Cp(lcd); // Display result

Delay_ms(5000); // Wait 5 seconds

Lcd_Cmd(LCD_CLEAR);

}

}

картинка 225

Figure 6.49: Modified program listing

Before using the Keypad_Released function we have to call the Keypad_Init function to tell the microcontroller what the keypad is connected to. Keypad_Released detects when a key is pressed and then released. When released, the function returns a number between 1 and 16 corresponding to the key pressed. The remaining parts of the program are the same as in Figure 6.48.

PROJECT 6.10 — Serial Communication–Based Calculator

Project Description

Serial communication is a simple means of sending data long distances quickly and reliably. The most common serial communication method is based on the RS232 standard, in which standard data is sent over a single line from a transmitting device to a receiving device in bit serial format at a prespecified speed, also known as the baud rate, or the number of bits sent each second. Typical baud rates are 4800, 9600, 19200, 38400, etc.

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

Интервал:

Закладка:

Сделать

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