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

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

Интервал:

Закладка:

Сделать

Declare Sub hidSetReadNotify Lib "mcHID.dll" Alias "SetReadNotify" (ByVal pHandle As Long, ByVal pValue As Boolean)

Declare Function hidIsReadNotifyEnabled Lib "mcHID.dll" Alias "IsReadNotifyEnabled" (ByVal pHandle As Long) As Boolean

Declare Function hidIsAvailable Lib "mcHID.dll" Alias "IsAvailable" (ByVal pVendorID As Long, ByVal pProductID As Long) As Boolean

' windows API declarations - used to set up messaging...

Private Declare Function CallWindowProc Lib user32 Alias "CallWindowProcA" (ByVal lpPrevWndFunc As Long, ByVal hwnd As Long, ByVal Msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long

Private Declare Function SetWindowLong Lib user32 Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long

' windows API Constants

Private Const WM_APP = 32768

Private Const GWL_WNDPROC = -4

' HID message constants

Private Const WM_HID_EVENT = WM_APP + 200

Private Const NOTIFY_PLUGGED = 1

Private Const NOTIFY_UNPLUGGED = 2

Private Const NOTIFY_CHANGED = 3

Private Const NOTIFY_READ = 4

' local variables

Private FPrevWinProc As Long ' Handle to previous window procedure

Private FWinHandle As Long ' Handle to message window

' Set up a windows hook to receive notification

' messages from the HID controller DLL - then connect

' to the controller

Public Function ConnectToHID(ByVal pHostWin As Long) As Boolean

FWinHandle = pHostWin

ConnectToHID = hidConnect(FWinHandle)

FPrevWinProc = SetWindowLong(FWinHandle, GWL_WNDPROC, AddressOf WinProc)

End Function

' Unhook from the HID controller and disconnect...

Public Function DisconnectFromHID() As Boolean

DisconnectFromHID = hidDisconnect

SetWindowLong FWinHandle, GWL_WNDPROC, FPrevWinProc

End Function

' This is the procedure that intercepts the HID controller messages...

Private Function WinProc(ByVal pHWnd As Long, ByVal pMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long

If pMsg = WM_HID_EVENT Then

Select Case wParam

' HID device has been plugged message...

Case Is = NOTIFY_PLUGGED

MainForm.OnPlugged (lParam)

' HID device has been unplugged

Case Is = NOTIFY_UNPLUGGED

MainForm.OnUnplugged (lParam)

' controller has changed...

Case Is = NOTIFY_CHANGED

MainForm.OnChanged

' read event...

Case Is = NOTIFY_READ

MainForm.OnRead (lParam)

End Select

End If

' next...

WinProc = CallWindowProc(FPrevWinProc, pHWnd, pMsg, wParam, lParam)

End Function

картинка 271

Figure 8.19: Visual Basic program for the PC end of USB link

The Microcontroller Software

The microcontroller receives the command P=nT from the PC and sends data byte n to PORTB. The listing of the microcontroller program (USB.C) without the USB code is shown in Figure 8.20. The program configures PORTB as digital output.

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

USB BASED MICROCONTROLLER 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.

The command sent by the PC to the microcontroller is in the following format:

P=nT

where n is the byte the microcontroller is requested to send to PORTB of the

microcontroller.

Author: Dogan Ibrahim

Date: September 2007

File: USB.C

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

void main() {

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

TRISB = 0; // Set PORTB to outputs

PORTB = 0; // Clear all outputs

}

картинка 272

Figure 8.20: Microcontroller program without the USB code

Generating the USB Descriptor File

The USB descriptor file must be included at the beginning of the mikroC program. This descriptor file is created using the Tools menu option of the mikroC compiler as follows:

• Select Tools→HID Terminal

• A new form should be displayed. Click on the Descriptor tab and the form shown in Figure 8.21 is displayed.

Figure 821 Creating the USBdsc descriptor file The important parameters to - фото 273

Figure 8.21: Creating the USBdsc descriptor file

• The important parameters to enter here are vendor ID (VID), product ID (PID), input buffer size, output buffer size, vendor name (VN), and product name (PN). Note that the VID and PID are in hexadecimal format and that the values entered here must be the same as the ones used in the Visual Basic program when generating the code using the EasyHID wizard. Choose VID=1234 (equivalent to decimal 6460), PID=1, input buffer size=4, output buffer size=4, and any names you like for the VN and PN fields.

• Check the mikroC compiler.

• Clicking the CREATE button will ask for a folder name and then create descriptor file USBdsc in this folder. Rename this file to have extension “.C” (i.e., the full file name should be USBdsc.C) and then copy it to the following folder (other required mikroC files are already in this folder, so it makes sense to copy USBdsc.C here as well).

C:\Program Files\Mikroelektronika\mikroC\Examples\EasyPic4\extra_examples\HID-library\USBdsc.c

Do not modify the contents of file USBdsc.C. A listing of this file is given on the CDROM.

The microcontroller program listing with the USB code included is shown in Figure 8.22 (program USB1.C). At the beginning of the program the USB descriptor file USBdsc.C is included. The operation of the USB link requires the microcontroller to keep the connection alive by sending keep-alive messages to the PC every several milliseconds. This is achieved by setting up a timer interrupt service routine using TIMER 0. Inside the timer interrupt service routine the mikroC USB function HID_InterruptProc is called. Timer TMR0L is reloaded and timer interrupts are re-enabled just before returning from the interrupt service routine.

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

USB BASED MICROCONTROLLER OUTPUT PORT

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

In this project a PIC18F4550 type microcontroller is connected

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

Интервал:

Закладка:

Сделать

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