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

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

Интервал:

Закладка:

Сделать

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

USB BASED MICROCONTROLLER INPUT/OUTPUT PORT

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

In this project a PIC18F4550 type microcontroller is connected

to a PC through the USB link.

A Visual Basic program runs on the PC where the user enters the

bits to be set or cleared on PORTB of the microcontroller. The

PC sends a command to the microcontroller requesting it to set

or reset the required bits of the microcontroller PORTB. In addition,

the PORTB data can be requested from the microcontroller and displayed

on the PC.

The microcontroller is operated from a 8MHz crystal, but the CPU

clock frequency is increased to 48MHz. Also, the USB module operates

with 48MHz.

The commands are:

From PC to microcontroller: P=nT (Send data byte n to PORTB)

P=?? (Give me PORTB data)

From microcontroller to PC: P=nT (Here is my PORTB data)

Author: Dogan Ibrahim

Date: September 2007

File: USB2.C

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

#include "C:\Program Files\Mikroelektronika\mikroC\Examples\EasyPic4\extra_examples\HIDlibrary\USBdsc.c"

unsigned char Read_buffer[64];

unsigned char Write_buffer[64];

unsigned char num,i;

//

// Timer interrupt service routine

//

void interrupt() {

HID_InterruptProc(); // Keep alive

TMR0L = 100; // Reload TMR0L

INTCON.TMR0IF = 0; // Re-enable TMR0 interrupts

}

//

// Start of MAIN program

//

void main() {

ADCON1 = 0xFF; // Set PORTB to digital I/O

TRISB = 0; // Set PORTB to outputs

PORTB = 0; // PORTB all 0s to start with

//

// Set interrupt registers to power-on defaults

// Disable all interrupts

//

INTCON=0;

INTCON2=0xF5;

INTCON3=0xC0;

RCON.IPEN=0;

PIE1=0;

PIE2=0;

PIR1=0;

PIR2=0;

//

// Configure TIMER 0 for 20ms interrupts. Set prescaler to 256

// and load TMR0L to 156 so that the time interval for timer

// interrupts at 8MHz is 256*156*0.5 = 20ms

//

// The timer is in 8-bit mode by default

//

T0CON = 0x47; // Prescaler = 256

TMR0L = 100; // Timer count is 256-156 = 100

INTCON.TMR0IE = 1; // Enable T0IE

T0CON.TMR0ON = 1; // Turn Timer 0 ON

INTCON = 0xE0; // Enable interrupts

//

// Enable USB port

//

Hid_Enable(&Read_buffer, &Write_buffer);

Delay_ms(1000);

Delay_ms(1000);

//

// Read from the USB port. Number of bytes read is in num

//

for(;;) // do forever

{

num=0;

while (num != 4) {

num = Hid_Read();

}

if (Read_buffer[0] == 'P' && Read_buffer[1] == '=' &&

Read_buffer[2] == '?' && Read_Buffer[3] == '?') {

TRISB = 0xFF;

Write_buffer[0] = 'P';

Write_buffer[1] = '=';

Write_buffer[2] = PORTB;

Write_buffer[3] = 'T';

Hid_Write(&Write_buffer, 4);

} else {

if (Read_buffer[0] == 'P' && Read_buffer[1] == '=' &&

Read_buffer[3] == 'T') {

TRISB = 0;

PORTB = Read_buffer[2];

}

}

}

Hid_Disable();

}

картинка 284

Figure 8.32: mikroC program listing of the project

The program checks the format of the received command. For P=?? type commands, PORTB is configured as inputs, PORTB data is read into Write_buffer[2] , and Write_buffer is sent to the PC, where Write_buffer[0] =“P,” Write_buffer[1] =“=”, and Write_buffer[3] =“T” as follows:

if (Read_buffer[0] == 'P' && Read_buffer[1] == '=' &&

Read_buffer[2] == '?' && Read_Buffer[3] == '?') {

TRISB = 0xFF;

Write_buffer[0] = 'P';

Write_buffer[1] = '=';

Write_buffer[2] = PORTB;

Write_buffer[3] = 'T';

Hid_Write(&Write_buffer, 4);

}

For P=nT type commands, PORTB is configured as outputs and Read_buffer[2] is sent to PORTB as follows:

if (Read_buffer[0] == 'P' && Read_buffer[1] == '=' &&

Read_buffer[3] == 'T') {

TRISB = 0;

PORTB = Read_buffer[2];

}

The microcontroller clock should be set as in Project 8.1 (i.e., both the CPU and the USB module should have 48MHz clocks). The other configurations bits should also be set as described in the previous problem.

Testing the Project

The project can be tested using one of the methods described in the previous project. If you are using the Visual Basic program, send data to the microcontroller and make sure the correct LEDs are turned on. Then connect some of the PORTB pins to logic 0 and click the CLICK TO RECEIVE button. The microcontroller will read its PORTB data and send it to the PC, where it will be displayed on the PC screen.

The project can also be tested using the HID terminal of mikroC IDE. The steps are:

• Start the HID terminal.

• Send a command to the microcontroller to turn on the LEDs (e.g., P=1T ) and make sure the correct LEDs are turned on (in this case, LEDs 0, 4, and 5 should turn on, corresponding to the data pattern “0011 0001”).

• Connect bits 2 and 3 of PORTB to logic 1 and the other six bits to ground.

• Send command P=?? to the microcontroller.

• The PC will display the number 12, corresponding to bit pattern “0000 1100”.

The Visual Basic program listing of the project is given in Figure 8.33. Only the main program is given here, as the library declarations are the same as in Figure 8.19. The program jumps to subroutine OnRead when data arrives at the USB bus. The format of this data is checked to be in the format P=nT, and if the format is correct, the received data byte is displayed in the text box.

' vendor and product IDs

Private Const VendorID = 4660

Private Const ProductID = 1

' read and write buffers

Private Const BufferInSize = 8

Private Const BufferOutSize = 8

Dim BufferIn(0 To BufferInSize) As Byte

Dim BufferOut(0 To BufferOutSize) As Byte

Private Sub Command1_Click()

Form_Unload (0)

End

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

Интервал:

Закладка:

Сделать

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