You are on page 1of 23

Nguy n Ng c H ng L p TKTL 40 HVKTQS

I NI

Hi n nay cc thi t b USB ngy cng ng d ng r ng ri, vi c lm ra cc


thi t b USB ang l c n thi t i v i t t c nh ng ai h c v
n t k c cc
n khng h c l nh v c ny c ng r t mu n n m b t n. Ph n l n cc thi t b
USB hi n nay u c s n driver c a cc nha cung c p th m ch c c fimware
cho cc con chip
u khi n. V i m c nh t lm ra m t thi t b USB t A n
Z (h i qu hihi) bao g m lm ph n c ng, vi t fimware, t o driver, v l p m t
giao di n trn my tnh
giao ti p v i thi t b USB m ta v a t o ra, h ng
n ny gip cho ng i h c c th lm t t c cc vi c .
c bi t l cc b n
sinh vin th c th y l vi c kh kh n, nh ng hy ch c h ng d n ny
n c th n m b t
c n v th y r ng n c ng th t l n gi n. Chng ta hy
cng nhau h c t p, nghin c u
giao th c USB cng ngy cng tr nn thng
ng v d hi u nh UART v yDo ph ng chm khi vi t bi ny l cng
n gi n cng t t, v ch c n ch n nh ng ci quan trong nh t. Hy v ng sau
khi c n t t c c b n c th t mnh lm
c m t Project theo mu n v
pht tri n n ty thch. V i ki n th c cn h n ch c th h ng d n ny cn
nhi u h n ch mong
c s ch gio c a t t c cc b n. Thanks!
Khng c vi c g kh, ch s lng khng b n. Vi c g kh c Sinh vin!

H n i, ngy 18/12/2008
Nguy n Ng c H ng

-1-

Nguy n Ng c H ng L p TKTL 40 HVKTQS

Ph n 1

Ph n c ng USB 2.0
1. Cc linh ki n chnh:
- Pic18f4550( ho c Pic18f2550 ).
ng USB ki u B.
- Cp USB 2 u ki u A v B.
- Th ch anh c tr s l b i c a 4, t c l c gi tr 4,8,12,16,20(Mhz).
t s linh ki n lm m ch tu ch n.
2.
m ch giao ti p n gi n:

ch trn th c t ti dng th ch anh 12M t 22p, v c s d ng m ch


chuy n i n ap dng Max232 giao ti p UART.
3.

u b ng m ch thi t k :
V khng c my nh nn khng ch p
c hnh ny.
4.
t s ch v ph n c ng:
- Th ch anh s d ng ph i l cc b i c a 4 v d 4M, 8M, 12M, 20M.
Yu c u ny l do t n s ho t ng c a bus USB l 12Mbs, chip
n t o ra t n s 4M t ngu n th nh anh, sau dng nhn t n t i
96M v ty thu c vo vi c c t bit chia t n
c p cho modul
USB v CPU.
- Khng nn b qua cc t ch ng nhi u chn t, chn ngu n c a
chp, t i chn n p ra c a v-usb.
- Dy cp USB 2 u nn mua ng b v i c ng USB ki u B v
khng nn dy cp qu di s gy suy gi m tn hi u.
-2-

Nguy n Ng c H ng L p TKTL 40 HVKTQS

- Nn t n d ng ngu n nui t c ng USB thay v ngu n ngoi v b


xung thm m t s t ch ng nhi u, n nh ngu n n u c n.
- Khi lm v i PIC18f2550 ti th y c n ph i n i tr chn PGM xu ng
t th chip m i ch y??
Vi c ti p theo l vi t fimware cho chip, sau t o driver v vi t dao di n
th c hi n vi c truy n nh n, t t c cc v n

c c p ph n 2 v ph n 3.
Ch r ng vi c m ph ng trn proteus 7.2 ch gip ta nh n bi t
c fimware
a ta vi t ng ch a qua vi c PC c pht hi n
c thi t b hay khng m
khng th dung n
t o driver b ng ph n m m WinDriver, c l do hai ph n
m ny khng t ng thch nhau.

-3-

Nguy n Ng c H ng L p TKTL 40 HVKTQS

Ph n 2:

Vi t Fimware cho Pic18f4550 ( ho c Pic18f2550)


1.
Trnh bin d ch:
C th vi t Fimware b ng t t c cc trnh bin d ch thng d ng, song theo ki n
a ti CCS l trnh bin d ch h tr vi t Fimware cho chp USB kh t t. Trong
v d c a CCS c cc v d cho c HID, Costume Driver v CDC.
ng th i cc
th vi n hm cho USB
c xy d ng t ng i thu n l i khi s d ng v v y r t
thu n l i cc b n c th nhanh chng th c hi n USB.
2.
Cc th c th nghi m:
Sau khi ph n c ng
c un i y
b n c th n p th
cc cc fimware c s n t ng thch v i ph n c ng v c m thi t b vo my tnh.
u ph n c ng ng v fimware t ng thch my tnh s thng bo Found
New Hardware v i h i ci t Driver cho thi t b . C n l u n u ph n m n
trong chp ci t t n s th ch anh khng kh p v i th ch anh ph n c ng s gy
ra l i v my tnh khng th nh n di n thi t b . N u khi t ng thch v th ch
anh m my tnh v n khng detect thi t b th c th ph n c ng c a b n v n cn
n ho c c ng USB c v n v ti p xc hy ki m tra k .
u thi t b c a b n khng b l i v fimware chnh xc:

Khi n i Driver hy t m th i b qua v th c hi n t o Driver m i cho n b ng


ph n m m WinDriver, khi t o xong Driver th thi t b s
ct
ng update
driver, chi ti t vi c t o driver
c h ng d n ph n 3.
3. Cc th vi n v hm s d ng chnh vi t USB:
C 3 file b n c n include vo project CCS c a b n l:
- #include <pic18_usb.h>
- #include <usb.c>
- #include <usb_desc_scope1.h>
Hai file trn c s n trong th vi n c a CCS ch a cc nh ngh a v cc hm ph c
cho giao ti p USB, file th 3 l file m t thi t b
c ch nh s a t file
usb_desc_scope.h ng c s n trong th vi n c a CCS
ph h p v i yu c u
a b n. Ngoi ra cn m t file n a l:
- #include .
ng d n/ usb_demo_bulk.h>
File ny khng c s n trong CCS nh cc file trn. N
c t o ra khi b n l p
t Project trn CCS qua PIC Wizard, tn file do b n t.
-1-

Nguy n Ng c H ng L p TKTL 40 HVKTQS

4. Cc hm u khi n v giao ti p USB:


Khi xem cc m ngu n c a cc file trn trong CCS, b n s th y r t nhi u hm v
nh ngh a kh hi u. Nh ng ph n l n b n s khng c n quan tm t i cc hm
v chng
c xy d ng
trnh bin d ch s d ng. Ci chng ta quan tm ch l
p hm User Functions m CCS xy d ng s n:
//// **************** USER FUNCTIONS *********************** ////
////
////
//// usb_init() - Initializes the USB stack, the USB peripheral and ////
////
attaches the unit to the usb bus. Enables
////
////
interrupts.
////
////
////
//// usb_init_cs() - A smaller usb_init(), does not attach unit ////
////
to usb bus or enable interrupts.
////
////
////
//// usb_put_packet() - Sends one packet to the host.
////
////
If you need to send a message that spans ////
////
more than one packet then see usb_puts() in ////
////
usb.c
////
////
////
//// usb_kbhit() - Returns true if OUT endpoint contains data from ////
////
host.
////
////
////
//// usb_rx_packet_size() - Returns the size of packet that was
////
////
received. usb_kbhit() must return TRUE else
////
////
this is not valid. Don't forget in USB there ////
////
are 0 len packets!
////
////
////
//// usb_get_packet() - Gets one packet that from the host.
////
////
usb_kbhit() must return true before you call ////
////
this routine or your data may not be valid. ////
////
Once usb_kbhit() returns true you want to ////
////
call this as soon as possible to get data ////
////
out of the endpoint buffer so the PC can ////
////
start sending more data, if needed.
////
////
This only receives one packet, if you are ////
////
trying to receive a multi-packet message ////
////
see usb_gets() in usb.c.
////
////
////
//// usb_detach() - De-attach USB from the system.
////
////
////
//// usb_attach() - Attach USB to the system.
////
////
////
//// usb_attached() - Returns TRUE if the device is attached to a ////
////
USB cable. A macro that looks at the defined ////
////
connection sense pin.
////
////
////
//// usb_task() - Keeps track of connection sense, calling
////
////
usb_detach() and usb_attach() when needed.
////
////
////
//// For more documentation on these functions read the comments at ////
-2-

Nguy n Ng c H ng L p TKTL 40 HVKTQS


//// each function.
////
////
////
//// The other functions defined in this file are for use by the
//// USB code, and is not meant to be used by the user.

////
////

Cc b n c th d dng tm hi u thm cch th c s d ng cc hm ny qua cc


Example v cc Comment c a CCS. V i cc hm ny b n c th
u khi n
modul USB c a pic18 kh linh ho t v c th m r ng chng
ph h p v i
c ch c a b n.
5.

o l i file m t thi t b usb_desc_scope1.h

#DEFINE USB_TOTAL_CONFIG_LEN

c th c hi n nh sau:

32 //config+interface+class+endpoint

//configuration descriptor
char const USB_CONFIG_DESC[] = {
//config_descriptor for config index 1
USB_DESC_CONFIG_LEN, //length of descriptor size
USB_DESC_CONFIG_TYPE,
//constant CONFIGURATION (0x02)
USB_TOTAL_CONFIG_LEN,0, //size of all data returned for this config
1,
//number of interfaces this device supports
0x01,
//identifier for this configuration. (IF we had more than one
configurations)
0x00,
//index of string descriptor for this configuration
0xC0,
//bit 6=1 if self powered, bit 5=1 if supports remote wakeup (we don't),
bits 0-4 reserved and bit7=1
0x32,
//maximum bus power required (maximum milliamperes/2) (0x32 =
100mA)
//interface descriptor 0 alt 0
USB_DESC_INTERFACE_LEN, //length of descriptor
USB_DESC_INTERFACE_TYPE, //constant INTERFACE (0x04)
0x00,
//number defining this interface (IF we had more than one interface)
0x00,
//alternate setting
2,
//number of endpoints, not counting endpoint 0.
0xFF,
//class code, FF = vendor defined
0xFF,
//subclass code, FF = vendor
0xFF,
//protocol code, FF = vendor
0x00,
//index of string descriptor for interface
//endpoint descriptor
USB_DESC_ENDPOINT_LEN, //length of descriptor
USB_DESC_ENDPOINT_TYPE, //constant ENDPOINT (0x05)
0x81,
//endpoint number and direction (0x81 = EP1 IN)
0x02,
//transfer type supported (0 is control, 1 is iso, 2 is bulk, 3 is interrupt)
USB_EP1_TX_SIZE & 0xFF,USB_EP1_TX_SIZE >> 8,
//maximum packet size
supported
0x01,
//polling interval in ms. (for interrupt transfers ONLY)
//endpoint descriptor
-3-

Nguy n Ng c H ng L p TKTL 40 HVKTQS


USB_DESC_ENDPOINT_LEN, //length of descriptor
USB_DESC_ENDPOINT_TYPE, //constant ENDPOINT (0x05)
0x01,
//endpoint number and direction (0x01 = EP1 OUT)
0x02,
//transfer type supported (0 is control, 1 is iso, 2 is bulk, 3 is interrupt)
USB_EP1_RX_SIZE & 0xFF,USB_EP1_RX_SIZE >> 8,
//maximum packet size
supported
0x01,
//polling interval in ms. (for interrupt transfers ONLY)
};
//****** BEGIN CONFIG DESCRIPTOR LOOKUP TABLES ********
//since we can't make pointers to constants in certain pic16s, this is an offset table to find
// a specific descriptor in the above table.
//NOTE: DO TO A LIMITATION OF THE CCS CODE, ALL HID INTERFACES MUST
START AT 0 AND BE SEQUENTIAL
//
FOR EXAMPLE, IF YOU HAVE 2 HID INTERFACES THEY MUST BE
INTERFACE 0 AND INTERFACE 1
#define USB_NUM_HID_INTERFACES 0
//the maximum number of interfaces seen on any config
//for example, if config 1 has 1 interface and config 2 has 2 interfaces you must define this
as 2
#define USB_MAX_NUM_INTERFACES 1
//define how many interfaces there are per config. [0] is the first config, etc.
const char USB_NUM_INTERFACES[USB_NUM_CONFIGURATIONS]={1};
#if (sizeof(USB_CONFIG_DESC) != USB_TOTAL_CONFIG_LEN)
#error USB_TOTAL_CONFIG_LEN not defined correctly
#endif

//////////////////////////////////////////////////////////////////
///
/// start device descriptors
///
//////////////////////////////////////////////////////////////////
//device descriptor
char const USB_DEVICE_DESC[] ={
USB_DESC_DEVICE_LEN,
//the length of this report
0x01,
//constant DEVICE (0x01)
0x10,0x01,
//usb version in bcd
0x00,
//class code (if 0, interface defines class. FF is vendor defined)
0x00,
//subclass code
0x00,
//protocol code
USB_MAX_EP0_PACKET_LENGTH,
//max packet size for endpoint 0. (SLOW
SPEED SPECIFIES 8)
0xd8,0x04,
//vendor id (0x04D8 is Microchip)
0x01,0x01,
//product id
0x00,0x01,
//device release number
-4-

Nguy n Ng c H ng L p TKTL 40 HVKTQS


0x01,
//index of string description of manufacturer. therefore we point to
string_1 array (see below)
0x02,
//index of string descriptor of the product
0x00,
//index of string descriptor of serial number
USB_NUM_CONFIGURATIONS //number of possible configurations
};

//////////////////////////////////////////////////////////////////
///
/// start string descriptors
/// String 0 is a special language string, and must be defined. People in U.S.A. can leave this
alone.
///
/// You must define the length else get_next_string_character() will not see the string
/// Current code only supports 10 strings (0 thru 9)
///
//////////////////////////////////////////////////////////////////
//the offset of the starting location of each string.
//offset[0] is the start of string 0, offset[1] is the start of string 1, etc.
const char USB_STRING_DESC_OFFSET[]={0,4,12};
#define USB_STRING_DESC_COUNT sizeof(USB_STRING_DESC_OFFSET)
char const USB_STRING_DESC[]={
//string 0
4, //length of string index
USB_DESC_STRING_TYPE, //descriptor type 0x03 (STRING)
0x09,0x04, //Microsoft Defined for US-English
//string 1
8, //length of string index
USB_DESC_STRING_TYPE, //descriptor type 0x03 (STRING)
'B',0,
'M',0,
'E',0,
//string 2
46, //length of string index
USB_DESC_STRING_TYPE, //descriptor type 0x03 (STRING)
'D',0,
'a',0,
'T',0,
'a',0,
' ',0,
'T',0,
'r',0,
'a',0,
'n',0,
's',0,
'f',0,
'e',0,
'r',0,
-5-

Nguy n Ng c H ng L p TKTL 40 HVKTQS


' ',0,
'B',0,
'u',0,
'l',0,
'k',0,
' ',0,
'N',0,
'N',0,
'H',0,
};
#ENDIF

n khng c n ph i ch nh s a g nhi u trong file ny, ch c n l u n m t s


m m ti nh d u b ng mu , t i c cc ch thch b ng ti ng anh
t r v ngh a c a chng. l s thi t b
c h tr giao ti p, s
m cu i,
vi c kh i t o cc
ng ng truy n v nh n, c c a gi truy n v ph ng th c
truy n.
y ti truy n theo lo i BULK. l nh ng thng s b n c n quan
tm nh ng khng c n s a.
Cc thng s sau l vendor id & product id n c th s a ty mi n l khng
trng v i thi t b c trong PC c a b n. Cu i cng l string index
n c s a
i theo tn m b n mong mu n, ch r ng chi u di c a chu i k t ph i ph
p v i khai bo.
Cn m t s khai bo n a nh ng ti vo trong file khc ti n vi c s a i, c
th
c trong file usb_demo_bulk.h
6. Qu n l file usb_demo_bulk.h:
Nh ni trn file ny
c t o ra khi ta l p Project trong CCS, by gi ta
thm vo trong m t s khai bo:
#include <18F4550.h>
#device adc=8
#FUSES NOWDT
#FUSES WDT128
#FUSES EC_IO
#FUSES NOPROTECT
#FUSES BROWNOUT
#FUSES BORV20
#FUSES NOPUT
#FUSES NOCPD
#FUSES STVREN
#FUSES NODEBUG
#FUSES NOLVP
#FUSES NOWRT
#FUSES NOWRTD
#FUSES IESO
#FUSES FCMEN
#FUSES PBADEN
#FUSES NOWRTC
#FUSES NOWRTB
#FUSES NOEBTR

//No Watch Dog Timer


//Watch Dog Timer uses 1:128 Postscale
//External clock
//Code not protected from reading
//Reset when brownout detected
//Brownout reset at 2.0V
//No Power Up Timer
//No EE protection
//Stack full/underflow will cause reset
//No Debug mode for ICD
//No low voltage prgming, B3(PIC16) or B5(PIC18) used for I/O
//Program memory not write protected
//Data EEPROM not write protected
//Internal External Switch Over mode enabled
//Fail-safe clock monitor enabled
//PORTB pins are configured as analog input channels on RESET
//configuration not registers write protected
//Boot block not write protected
//Memory not protected from table reads
-6-

Nguy n Ng c H ng L p TKTL 40 HVKTQS


#FUSES NOEBTRB
#FUSES NOCPB
#FUSES MCLR
#FUSES LPT1OSC
#FUSES NOXINST
#FUSES PLL3
#FUSES USBDIV
#FUSES VREGEN
#FUSES CPUDIV1
#FUSES HSPLL

//Boot block not protected from table reads


//No Boot Block code protection
//Master Clear pin enabled
//Timer1 configured for low-power operation
//Extended set extension and Indexed Addressing mode disabled
// PLL PreScaler 3

#use delay(clock=12000000)
#use rs232(baud=9600,parity=N,xmit=PIN_C6,rcv=PIN_C7,bits=8)
#DEFINE USB_HID_DEVICE FALSE
#define USB_EP1_TX_ENABLE
USB_ENABLE_BULK
//turn on EP1 for IN
bulk/interrupt transfers
#define USB_EP1_RX_ENABLE
USB_ENABLE_BULK
//turn on EP1 for OUT
bulk/interrupt transfers
#define USB_EP1_TX_SIZE 64 //size to allocate for the tx endpoint 1 buffer
#define USB_EP1_RX_SIZE 8 //size to allocate for the rx endpoint 1 buffer
void setup()
{
setup_adc_ports(AN0|VSS_VDD);
setup_adc(ADC_OFF);
setup_psp(PSP_DISABLED);
setup_spi(FALSE);
setup_wdt(WDT_OFF);
setup_timer_0(RTCC_INTERNAL);
setup_timer_1(T1_DISABLED);
setup_timer_2(T2_DISABLED,0,1);
setup_timer_3(T3_DISABLED|T3_DIV_BY_1);
setup_comparator(NC_NC_NC_NC);
setup_vref(FALSE);
setup_low_volt_detect(FALSE);
setup_oscillator(False);
}

Nh ng
m ch ti nh d u trn, b n c n l u r ng t n s th nh anh
ngoi s
c chia
c dao ng 4M y l yu c u b t bu c khi s d ng
PLL.
y ti dng th ch anh 12M nn PLL=3. M t s tham s khc b n c th
xem chi ti t trong datasheet.
Nh v y n y ta ch cn m t cng vi c n a l vi t hm main.
7. ch ng trnh chnh:
#include "E:\MICROCONTROL\PIC\USB\usb_demo_bulk.h"
#include <pic18_usb.h>
#include <usb_desc_scope1.h>
#include <usb.c>
void usb_debug_task(void)
{
-7-

Nguy n Ng c H ng L p TKTL 40 HVKTQS


static int8 last_connected;
static int8 last_enumerated;
int8 new_connected;
int8 new_enumerated;
new_connected=usb_attached();
new_enumerated=usb_enumerated();
if (new_connected && !last_connected)
printf("\r\n\nUSB connected, waiting for enumaration...");
if (!new_connected && last_connected)
printf("\r\n\nUSB disconnected, waiting for connection...");
if (new_enumerated && !last_enumerated)
printf("\r\n\nUSB enumerated by PC/HOST");
if (!new_enumerated && last_enumerated)
printf("\r\n\nUSB unenumerated by PC/HOST, waiting for enumeration...");
last_connected=new_connected;
last_enumerated=new_enumerated;
}
void main()
{
int8 out_data[2];
int8 in_data[2];
int8 send_timer=0;
int8 count=0;
int16 i;
setup();
// TODO: USER CODE!!
printf("\r\n Transfer BULK Example");
usb_init_cs();
while (TRUE)
{
usb_task();
usb_debug_task();
if(usb_enumerated())
{
if (!send_timer)
{
count++;
send_timer=250;
out_data[0]=count;
if (usb_put_packet(1, out_data, 1, USB_DTS_TOGGLE))
printf("\r\n<-- Sending 2 bytes: 0x%X", out_data[0]);
}
if (usb_kbhit(1))
{
usb_get_packet(1, in_data, 1);
-8-

Nguy n Ng c H ng L p TKTL 40 HVKTQS


printf("\r\n--> Received data: 0x%X",in_data[0]);;
}
send_timer--;
delay_ms(1);
}
}

b n ch ng trnh trn gi ng v i v d c a CCS. Trong ch ng trnh s d ng


hm usb_debug_task() dng
g r i b ng giao ti p UART, n u b n s d ng
laptop khng c c ng COM th c th thay chng b ng vi c hi n th ra LED.
Trong ch ng trnh chnh th c hi n c 250ms th truy n qua bus USB ln PC gi
tr count, gi tr ny sau m i l n truy n
c t ng ln 1, khi n gi tr 0xFF th
ng tr v 0. Trong ch ng trnh cn lin t c ki m tra xem
m cu i c
nh n
c d li u t PC khng, n u c th l y d li u trong b
m v bi n
in_data. C truy n v nh n u
c ki m tra b ng vi c hi n th qua UART. n
y ta hon t t vi c vi t fimware cho V K,
y ti dng PIC18F4550 vi c
vi t ch ng trnh cho PIC18f2550 khng c g khc.
Chng ta b t tay vo vi c t o driver cho thi t b v vi t m t ch ng trnh giao
di n n gi n b ng C#.

-9-

Nguy n Ng c H ng L p TKTL 40 HVKTQS

Ph n 3:
Vi t Ch ng Trnh C# giao ti p v i thi t b USB
1. T o Driver cho thi t b v t o cc th vi n hm giao ti p USB:
Cng vi c u tin m b n ph i lm v i WinDriver
t o Driver v cc
th vi n ph n m m cho ch ng trnh PC c a b n. Cc b c ti n hnh bao g m:
1.
n thi t b c a b n vo c ng USB trn my tnh computer:
2. Ch y DriverWizard v ch n thi t b c a b n:

hnh 1: M ho c t o m t WinDriver Project

Ch n thi t b c a b n trong list c a WinDriver:

-1-

Nguy n Ng c H ng L p TKTL 40 HVKTQS

Ch n pht ra file Driver v nh tn cho thi t b c a b n:

Ti p t c ch n next ta

c:

i y b n c th ki m tra vi c truy n nh n qua USB xem thi t b c a b n


ho t ng ch a. Vi c ti p theo l t o ra giao di n ban u v th vi n trn C#.
Click v bi u t ng Generate Code v ch n ngn ng m b n s d ng, hi n nay
ngn ng C# thng d ng v i nhi u ng i v c nhi u ti n ch h n so v i VB
nn
y ti ch n nh sau:

Cng vi c cn l i ch l OK v ch my ch y hihi.
-2-

Nguy n Ng c H ng L p TKTL 40 HVKTQS

Ch y Project trn Visual Studio 2005 b n c th th y WinDriver t o cho ta


t giao di n ban u
s d ng cc giao ti p USB, b n c th s d ng lun
giao di n ny th c hi n theo Project c a b n:

Ch r ng b n ph i Project/ Set as Startup Project tr c .


Nh ng
gip cho ng i m i h c c th hi u
c m t cch nhanh chng ti
xin t t o m t giao di n khc n gi n ng n g n h n b ng vi c s d ng cc th
vi n m WinDriver v a t o ra cho chng ta.
l hai th vi n
project_usb_4550_lib.dll (th vi n ny do ta t n cng v i tn Project khi t o
ra) v wdapi_dotnet921.dll hai th vin ny ch a cc l p v cc y quy n r t
u ch gip cho vi c qu n l v th c hin giao ti p b ng USB.

Cng vi c ti p theo c a chng ta l hy tam qun i ci giao di n m WinDriver


a t o ra trn, v b t tay vo t o m t giao di n c a chnh chng ta. V i
ph ng chm cng n gi n cng t t nn h ng d n ny ti ch t o m t giao
di n ch v i 2 Button v 2 textBox dng
u khi n nh sau:

-3-

Nguy n Ng c H ng L p TKTL 40 HVKTQS

y l song b c u tin, b c ti p theo l add 2 th vi n trn vo trong


project c a mnh v nghin c u cch s d ng chng. N u b n add thnh cng th
n s th y chng nh sau:

Ta hy xem chng c nh ng g ( vi c s
project_usb_4550_lib.dll):

d ng ch

y u trn th

vi n

Th vi n ny ch a 4 u quy n (delegates) dnh


t o cc s ki n quan tr ng
i bus USB v 4 l p, trong 3 l p
u khi n thi t b USB v m t l p
-4-

Nguy n Ng c H ng L p TKTL 40 HVKTQS

qu n l danh sch cc thi t b USB khc nhau


c gn vo PC. Chng ta hy
quan st c th h n v i cc u quy n v cc l p ny:
quy n D_USER_ATTACH_CALLBACK
d ng gn s ki n c
thi t b USB thch h p g n vo bus USB v i m t hm callback do b n t o ra
th ng l kh i t o vi c truy n nh n d li u.
quy n D_USER_DETACH_CALLBACK
c s d ng
gn s
ki n thi t b USB
c tho ra v i m t hm g i l i do b n xy d ng th ng
l thng bo cho ngu i s d ng v vi c Disconnect v k t thc vi c truy n nh n
quy n D_USER_TRANSFER_COMPLETION kh h u ch v n s
gn s ki n truy n nh n k t thc vo m t hm x l c vi t d li u usb do b n
xy d ng.
quy n D_USER_POWER_CHANGE_CALLBACK t
c s d ng
n v n lin quan n vi c bo ng thay i ngu n trn bus USB, b n c th
n d ng th c hi n cc bi n php b o m c t ngu n bus USB khi c s c .
p KEY_USB_Device ch a cc hm
th c hi n vi c ci t c u hnh
khc nhau cho thi t b USB hay hm c cc s hi u VP, IP v hm theo di
tr ng thi truy n nh n c a thi t b :

s l

p KEY_USB_DeviceManager th c hi n vi c qu n l thi t b USB v


ng thi t b USB
c g n vo:

p KEY_USB_Pipe c s l ng hm t ng i l n v chuyn d ng
c vi t d li u ki m tra tr ng thi truy n nh n, ki m sot vi c kh i ng v
ng cc
ng ng
L p Pipe_list th c hi n qu n l cc
ng ng vo ra c a thi t b .
p cc hm ny kh linh ho t v y
cho m i ng d ng USB v b n c ng
khng c n ph i tm hi u k t t c cc hm v chng ta ch c n lm vi c v i
t s hm nh t nh l
giao ti p.

By gi l n cng vi c kh nh t y, ta ph i vi t code lm sao cho khi g n


thi t b vo th n ph i nh n
c v th c hi n truy n pht d li u.
-5-

Nguy n Ng c H ng L p TKTL 40 HVKTQS

ng c a ti l dng Button1(tn l btwrite)


th c hi n vi c truy n d li u
c l y trong textBox1(tn l txttrans) t PC xu ng V K, Button2(btread)
dng l y d li u t V K ln PC hi n th textBox2(txtLog).
thu t ton th c hi n ch ng trnh chng ta ch h n ch 3 ch c n ng c b n
l c, vi t d li u v pht hi n thi t b gn vo hay tho ra (hai s ki n nh n
bi t thi t b u
c hi n th trn txtLog).
Ph n khai bo USING c a ch ng trnh chng ta c n m t s khai bo nh sau:
using
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Text;
System.Windows.Forms;
System.Runtime.InteropServices;
System.Runtime.CompilerServices;

using Jungo.wdapi_dotnet;
//s d ng th vi n wdapi_dotnet
using Jungo.project_usb_4550_lib; //s d ng th vi n project_usb_4550_lib
using wdu_err=Jungo.wdapi_dotnet.WD_ERROR_CODES;//s d ng vi c khai bo l i
using DWORD = System.UInt32;
using WORD = System.UInt16;
using UCHAR = System.Byte;

ph n khai bo cc bi n c a form chnh chng ta th c hi n m t s khai bo hng


bi n v t o cc i t ng sau:
private const string DEFAULT_LICENSE_STRING =
"6C3CC2CFE89E7AD04238DF2EF24449E848CDC187.NguyenNgocHung";
// TODO: If you have renamed the WinDriver kernel module (windrvr6.sys),
// change the driver name below accordingly
private const string DEFAULT_DRIVER_NAME = "windrvr6";
private const WORD DEFAULT_VENDOR_ID = 0x04D8;
private const WORD DEFAULT_PRODUCT_ID = 0x0101;
public const DWORD TIME_OUT = 30000;
private PROJECT_USB_4550_DeviceManager uDevManager; //khai bo kh i t o
vi c qu n l
i t ng USB
private PROJECT_USB_4550_Device usb_device; //khai bo
i t ng USB
private PROJECT_USB_4550_Pipe usb_pipe_trs; //khai bo
i t ng ng truy n
private PROJECT_USB_4550_Pipe usb_pipe_rev; //khai bo
i t ng ng nh n
private delegate void D_ATTACH_GUI_CALLBACK(PROJECT_USB_4550_Device pDev);
//khai bo y quy n thng bo thi t b g n vo
private delegate void D_DETACH_GUI_CALLBACK(PROJECT_USB_4550_Device pDev);
//khai bo y quy n thng bo thi t b tho ra
delegate void safeLogTextCallBack(string sMsg); //khai bo y quy n ph c v
hi n th

Chng ta c 1 i t ng qu n l USB, 1 i t ng thi t b USB, 2 i t ng


ng ng TRANSFER v RECEIVER, cc k t n i, khai bo driver
u khi n
v cc u quy n c n thi t. Ti p theo chng ta s xy d ng cc hm c a form
theo cc s ki n chnh. S ki n u tin chng ta c n quan tm l form load
v n x y ra u tin trong chu i s ki n v v y c th t n d ng kh i t o m t
bi n, i t ng cho ch ng trnh.
private void form_main_Load(object sender, EventArgs e)
{
//
ng k hai hm s ki n ATTACH_CALLBACK & DETACH_CALLBACK

-6-

Nguy n Ng c H ng L p TKTL 40 HVKTQS


D_USER_ATTACH_CALLBACK dDeviceAttachCb = new
D_USER_ATTACH_CALLBACK(UserDeviceAttach);
D_USER_DETACH_CALLBACK dDeviceDetachCb = new
D_USER_DETACH_CALLBACK(UserDeviceDetach);
//kh i t o
i t ng qu n l thi t b USB
uDevManager = new
PROJECT_USB_4550_DeviceManager(dDeviceAttachCb, dDeviceDetachCb,
DEFAULT_VENDOR_ID, DEFAULT_PRODUCT_ID, DEFAULT_DRIVER_NAME,
DEFAULT_LICENSE_STRING);
}

Hm 2 callback x l 2 s ki n Attacth v Detach theo c c u trung gian


c
i n 2 hm UserDeviceAttach & UserDeviceDetach
kh i t o cc i
ng AttachCb v DetachCb . Trong hm ny cn th c hi n vi c kh i t o thi t b
USB v hai
ng ng TRANSFER & RECEIVER.
private void UserDeviceAttach(PROJECT_USB_4550_Device pDev)
{
D_ATTACH_GUI_CALLBACK AttachCb = new
D_ATTACH_GUI_CALLBACK(DeviceAttachGuiCb);
// kh i t o thi t b USB
usb_device = pDev;
// kh i t o
ng ng nh n v truy n
usb_pipe_rev =
(PROJECT_USB_4550_Pipe)usb_device.GetpPipesList()[1];
usb_pipe_trs =
(PROJECT_USB_4550_Pipe)usb_device.GetpPipesList()[2];
Invoke(AttachCb, new object[] {pDev});
}

V:
private void UserDeviceDetach(PROJECT_USB_4550_Device pDev)
{
D_DETACH_GUI_CALLBACK DetachCb = new
D_DETACH_GUI_CALLBACK(DeviceDetachGuiCb);
Invoke(DetachCb, new object[] { pDev });
}

Cc hm DeviceAttachGuiCb & DeviceDetachGuiCb ch l cc hm hi n th tr ng


thi thi t b g n vo hay tho ra.
private void DeviceAttachGuiCb(PROJECT_USB_4550_Device pDev)
{
TraceMsg("Found new device\r\n");
TraceMsg("Your new device is installed and ready to use\r\n");
}
private void DeviceDetachGuiCb(PROJECT_USB_4550_Device pDev)
{
TraceMsg("Your device has detached\r\n");
}

thu n l i cho vi c hi n th tr ng thi ch ng trnh chng ta nn b xung m t


hm
u khi n vi c xu t thng bo v d 3 hm d i y:
private void SafeLogText(string sMsg)
{
// InvokeRequired compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (txtLog.InvokeRequired)
{

-7-

Nguy n Ng c H ng L p TKTL 40 HVKTQS


safeLogTextCallBack cb = new
safeLogTextCallBack(SafeLogText);
this.Invoke(cb, new object[] { sMsg });
}
else
{
txtLog.AppendText(sMsg);
}
}
public void TraceMsg(string sMsg)
{
SafeLogText(sMsg);
}

By gi ta b t tay vo vi c xy d ng hm dng truy n nh n d li u. Khi nh n


vo button write th th c hi n truy n m t byte xu ng V K:
private void btwrite_Click(object sender, EventArgs e)
{
SingleTransfer();
}

Hm SingleTransfer();
chuy n sang d ng byte

th c hi n vi t s l y 1 byte nh p vo txttrans v
trong buffer sau g i hm truy n khng ng b :

usb_pipe_trs.UsbPipeTransferAsync(false, 0, buffer,
dwBuffSize, TIME_OUT, new
D_USER_TRANSFER_COMPLETION(Transfer_trs_Completion));

Khi nh n vo button read th th c hi n nh n m t byte t V K ln PC v hi n


th ra txtLog.
private void btread_Click(object sender, EventArgs e)
{
SingleReceiver();
}

Hm SingleReceiver(); t ng t nh hm SingleTransfer();
nh n d li u vo b
m:

th c hi n vi c

usb_pipe_rev.UsbPipeTransferAsync(true, 0, buffer,
dwBuffSize, TIME_OUT, new
D_USER_TRANSFER_COMPLETION(Transfer_rev_Completion));

Cc hm Transfer_trs_Completion & Transfer_rev_Completion th c hi n vi c


thng bo hon thnh truy n ho c nh n. Hm DisplayHexBuffer
h tr vi c
hi n th gi tr thp l c phn.
Sau y l ton b m c a ch ng trnh:
using
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Text;
System.Windows.Forms;
System.Runtime.InteropServices;
System.Runtime.CompilerServices;

using Jungo.wdapi_dotnet;
using Jungo.project_usb_4550_lib;
using wdu_err = Jungo.wdapi_dotnet.WD_ERROR_CODES;
using DWORD = System.UInt32;

-8-

Nguy n Ng c H ng L p TKTL 40 HVKTQS


using WORD = System.UInt16;
using UCHAR = System.Byte;
namespace project_usb_4550
{
public partial class form_main : Form
{
private const string DEFAULT_LICENSE_STRING =
"6C3CC2CFE89E7AD04238DF2EF24449E848CDC187.NguyenNgocHung";
private const string DEFAULT_DRIVER_NAME = "windrvr6";
private const WORD DEFAULT_VENDOR_ID = 0x04D8;
private const WORD DEFAULT_PRODUCT_ID = 0x0101;
public const DWORD TIME_OUT = 30000;
private
private
private
private
private

PROJECT_USB_4550_DeviceManager uDevManager;
PROJECT_USB_4550_Device usb_device
PROJECT_USB_4550_Pipe usb_pipe_trs;
PROJECT_USB_4550_Pipe usb_pipe_rev;
delegate void D_ATTACH_GUI_CALLBACK(PROJECT_USB_4550_Device

pDev);
private delegate void D_DETACH_GUI_CALLBACK(PROJECT_USB_4550_Device
pDev);
delegate void safeLogTextCallBack(string sMsg);
public form_main()
{
InitializeComponent();
}
private void form_main_Load(object sender, EventArgs e)
{
D_USER_ATTACH_CALLBACK dDeviceAttachCb = new
D_USER_ATTACH_CALLBACK(UserDeviceAttach);
D_USER_DETACH_CALLBACK dDeviceDetachCb = new
D_USER_DETACH_CALLBACK(UserDeviceDetach);
uDevManager = new
PROJECT_USB_4550_DeviceManager(dDeviceAttachCb, dDeviceDetachCb,
DEFAULT_VENDOR_ID, DEFAULT_PRODUCT_ID, DEFAULT_DRIVER_NAME,
DEFAULT_LICENSE_STRING);
}
private void UserDeviceAttach(PROJECT_USB_4550_Device pDev)
{
D_ATTACH_GUI_CALLBACK AttachCb = new
D_ATTACH_GUI_CALLBACK(DeviceAttachGuiCb);
usb_device = pDev;
usb_pipe_rev =
(PROJECT_USB_4550_Pipe)usb_device.GetpPipesList()[1];
usb_pipe_trs =
(PROJECT_USB_4550_Pipe)usb_device.GetpPipesList()[2];
Invoke(AttachCb, new object[] {pDev});
}
private void DeviceAttachGuiCb(PROJECT_USB_4550_Device pDev)
{
TraceMsg("Found new device\r\n");
TraceMsg("Your new device is installed and ready to use\r\n");
}
private void UserDeviceDetach(PROJECT_USB_4550_Device pDev)
{
D_DETACH_GUI_CALLBACK DetachCb = new
D_DETACH_GUI_CALLBACK(DeviceDetachGuiCb);
Invoke(DetachCb, new object[] { pDev });
}

-9-

Nguy n Ng c H ng L p TKTL 40 HVKTQS


private void DeviceDetachGuiCb(PROJECT_USB_4550_Device pDev)
{
TraceMsg("Your device has detached\r\n");
}
private void SafeLogText(string sMsg)
{
// InvokeRequired compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (txtLog.InvokeRequired)
{
safeLogTextCallBack cb = new
safeLogTextCallBack(SafeLogText);
this.Invoke(cb, new object[] { sMsg });
}
else
{
txtLog.AppendText(sMsg);
}
}
public void TraceMsg(string sMsg)
{
SafeLogText(sMsg);
}
private void btwrite_Click(object sender, EventArgs e)
{
SingleTransfer();
}
private void SingleTransfer()
{
DWORD dwBuffSize = 1;
byte[] buffer = new byte[1];
string txt = txttrans.Text;
buffer[0] = Convert.ToByte(txt[0]);
usb_pipe_trs.UsbPipeTransferAsync(false, 0, buffer,
dwBuffSize, TIME_OUT, new
D_USER_TRANSFER_COMPLETION(Transfer_trs_Completion));
}
private void Transfer_trs_Completion(PROJECT_USB_4550_Pipe pipe)
{
if (pipe.GetTransferStatus() ==
(DWORD)wdu_err.WD_STATUS_SUCCESS)
{
TraceMsg("Transfer completed successfully!\r\n ");
}
else
{
TraceMsg("tranfer fail\r\n");
}
}
private void btread_Click(object sender, EventArgs e)
{
SingleReceiver();
}
private void SingleReceiver()
{
DWORD dwBuffSize = 1;
byte[] buffer = new byte[1];
usb_pipe_rev.UsbPipeTransferAsync(true, 0, buffer,

- 10 -

Nguy n Ng c H ng L p TKTL 40 HVKTQS


dwBuffSize, TIME_OUT, new
D_USER_TRANSFER_COMPLETION(Transfer_rev_Completion));
}
private void Transfer_rev_Completion(PROJECT_USB_4550_Pipe pipe)
{
if (pipe.GetTransferStatus() ==
(DWORD)wdu_err.WD_STATUS_SUCCESS)
{
TraceMsg(DisplayHexBuffer(pipe.GetBuffer(),1));
}
else
{
TraceMsg("receiver failure!\r\n");
}
}
private string DisplayHexBuffer(byte[] buff, DWORD dwBuffSize)
{
string display = "";
for (DWORD i = 0; i < dwBuffSize; i++)
display = string.Concat(display, buff[i].ToString("X")," ");
display = string.Concat(display, Environment.NewLine);
return display;
}
}
}

- 11 -

You might also like