BIDIRECTIONAL CONTROL TRANSFER WITH MICROCONTROLLER Mihir Kikani B.E., Saurashtra University, India, 2007

advertisement
BIDIRECTIONAL CONTROL TRANSFER WITH MICROCONTROLLER
Mihir Kikani
B.E., Saurashtra University, India, 2007
PROJECT
Submitted in partial satisfaction of
the requirements for the degree of
MASTER OF SCIENCE
in
ELECTRICAL AND ELECTRONIC ENGINEERING
at
CALIFORNIA STATE UNIVERSITY, SACRAMENTO
SPRING
2011
BIDIRECTIONAL CONTROL TRANSFER WITH MICROCONTROLLER
A Project
by
Mihir Kikani
Approved by:
__________________________________, Committee Chair
Jing Pang, Ph. D.
__________________________________, Second Reader
Fethi Belkhouche, Ph. D.
____________________________
Date
ii
Student: Mihir Kikani
I certify that this student has met the requirements for format contained in the University
format manual, and that this project is suitable for shelving in the Library and credit is to
be awarded for the project.
_________________________, Graduate Coordinator
Preetham Kumar, Ph.D.
Department of Electrical and Electronic Engineering
iii
________________
Date
Abstract
of
BIDIRECTIONAL CONTROL TRANSFER WITH MICROCONTROLLER
by
Mihir Kikani
The main goal of this project is to design and implement data communication
between personal
computer and PIC18F452 (Peripheral
Interface Controller)
microcontroller using USB (Universal Serial Bus) protocol. The major hardware
components of this project include PIC 18F452 microcontroller, LCD (Liquid Crystal
Display) display, personal computer, USB cable and Cana Kit programmer.
The initial design of the project was limited to one bit bidirectional transfer from
PC to PIC microcontroller using USB protocol which was in Visual Basic. PIC
programming software was written in C. The design did not use any LCD or display
device as it was single bit data transfer. LED (Liquid Crystal Display) was used as an
indication device.
USB based more than one bit bidirectional data transfer has been designed and
implemented in this project. LCD module has been used to display transferred data from
personal computer. Since this project is combination of hardware and software, the key
part of the project is debugging and troubleshooting of controller hardware. PIC
microcontroller has built in USB communication peripherals that are utilized in this
project.
_________________________________________________, Committee Chair
Jing Pang, Ph.D.
_________________________
Date
iv
ACKNOWLEDGMENTS
Before starting discussing this project I would like to appreciate all of the people
who helped me very much till the completion of the project. First of all I would like to
thank Prof. Dr. Jing Pang for her kind help, permission and suggestions for successful
completion of this project. It was really a great source of knowledge regarding USB
protocol and its implementation. Without her time and effort I would not have been able
to complete this project successfully. I would also like to thank her for reviewing my
project report very carefully.
I would also like to thank Dr. Fethi Belkhouche for being second reader to review
my report. He has spent his valuable time to review my project report. His suggestions
helped me a lot to abide all the rules and guidelines of university.
Finally I would like to thank my project partner Manthan Patel for giving me
motivation during the critical time of project progress.
Mihir Kikani
v
TABLE OF CONTENTS
Page
Acknowledgements..............................................................................................................v
List of Tables......................................................................................................................ix
List of Figures......................................................................................................................x
Chapter
1. INTRODUCTION...........................................................................................................1
2. TYPES OF DATA TRANSFER USED IN USB............................................................3
2.1 Introduction of USB Protocol....................................................................................3
2.2 Architectural Overview of USB Model...................................................................4
2.3 Types of Data Transfer Used in USB Protocol........................................................5
2.3.1 Control Transfer..............................................................................................5
2.3.2 Isochronous Transfer......................................................................................6
2.3.3 Interrupt Transfer ...........................................................................................6
2.3.4 Bulk Transfer..................................................................................................7
2.4 USB Data Flow Model.............................................................................................8
3. PIC SERIAL COMMUNICATION.............................................................................10
3.1 Configuring Oscillator Crystal Frequency...........................................................10
3.1.1Use of Internal Oscillator Block.................................................................10
3.2 Baud Rate Calculation...........................................................................................12
3.2.1 Calculating the Value Being Placed in the SPBRG Register.......................12
3.2.2 Calculating Baud Rate Error.........................................................................14
vi
3.2.3 Auto Baud Rate Detection Technique..........................................................14
3.3 Configuration of Enhanced Asynchronous Transmitter & Receiver....................16
3.3.1 EUSART Asynchronous Transmitter Functionality.....................................16
3.1.1.1 To Initialize an Asynchronous Transmission................................18
3.3.2 EUSART Asynchronous Receiver Functionality.........................................18
3.3.2.1 To Initialize an Asynchronous Reception......................................19
3.4 Configuring Program and Data Memory...............................................................20
3.4.1 Utilization of Data Memory..........................................................................21
3.4.2 Use of FLASH Program Memory.................................................................21
4. LCD INTERFACING MODULE.................................................................................22
4.1 Introduction............................................................................................................22
4.2 Description.............................................................................................................22
4.3 LCD PIC Driver Module ......................................................................................25
4.4 Schematic of Interfacing Module .........................................................................26
4.5 Software Used .......................................................................................................28
4.6 Source Code for LCD Module ..............................................................................28
5. BLOCK DIAGRAM AND OPERATION...................................................................32
5.1 Introduction............................................................................................................32
5.2 Block Diagram ......................................................................................................32
5.3 Design of Power Supply........................................................................................33
5.4 PL-2303 Serial Bridge Controller..........................................................................35
5.4.1 System Requirements for PL-2303 Bridge Controller..................................36
vii
5.5 Microcontroller Based Printed Circuit Board........................................................36
5.6 Software Implemented...........................................................................................38
5.6.1 Flow Chart....................................................................................................38
5.7 Simulation Results.................................................................................................43
6. CONCLUSION AND FUTURE WORK....................................................................48
Appendix Source Code ....................................................................................................49
References .......................................................................................................................55
viii
LIST OF TABLES
Page
1. Table 1 Selection of Capacitor Values for Crystal Oscillator..…..........................
10
2. Table 2 Oscillator Tuning Register ……………………………….......................
11
3. Table 3 Baud Rates for Asynchronous Mode ………………………………........ 14
4. Table 4 : LCD Pin Configuration...............................................................................24
24
ix
LIST OF FIGURES
Page
1. Figure 1. USB Physical Bus Topology………………………….........................
4
2. Figure 2. USB Implementation Areas ....……….…….........................................
8
3. Figure 3. Automatic Baud Rate Calculation.........................................................
15
4. Figure 4. EUSART Transmit Block Diagram………………………………......
17
5. Figure 5. EUSART Receive Block Diagram..........................................................
19
6. Figure 6. LCD Block Diagram…………………………………………………
23
7. Figure 7. Block Diagram of LCD-PIC Driver Module..........................................
25
8. Figure 8. LCD Interfacing Module with PIC18F452 Microcontroller..................
27
9. Figure 9. Block Diagram of Microcontroller Based Device..................................
32
10. Figure 10. Block Diagram of 5V DC Power Supply Design ……………….......
33
11. Figure 11. Transformer and Bridge Rectifier Circuit Diagram ………………...
34
12. Figure 12. Schematic of PL2303 Serial Bridge Controller ……………..............
35
13. Figure 13. PL 2303 Serial Adapter ….…………….............................................. 35
14. Figure 14. Microcontroller Based Printed Circuit Board ………………............
36
15. Figure 15. Flow Chart Design of Software Implemented...................................
39
16. Figure 16. Hello Dr. Pang Message on LCD........................................................
41
17. Figure 17. Snap Shot Showing USB Device Recognize by Personal Computer
41
18. Figure 18. Visual Studio Form to Enter Text Data..............................................
42
19. Figure 19. Simulation Result of MPLAB Tool Suite............................................ 43
x
20. Figure 20. Simulation Result of Pic Kit2 Tool Suite........................................44
21. Figure 21. Detecting of Virtual COM Port on Personal Computer...................45
22. Figure 22. Ball Movements on Personal Computer …………………………46
23. Figure 23. Simulation Result on Microcontroller Based LCD Interface .........47
24. Figure 24. Simulation Result on Personal Computer........................................47
xi
1
Chapter 1
INTRODUCTION
In the telecommunication and computer science, the concept of serial
communication is the process of sending a single bit at a time over some communication
channel or computer bus. In the parallel communication, several bits are being sent at a
time. Serial communication buses are becoming more and more popular day by day
because parallel communication system requires higher cable cost and has
synchronization issues. If we transfer data over serial bus, then we can have advantage of
good transmission speed and signal integrity. Universal Serial Bus is a serial
communication specification to establish data transfer between personal computer and
I/O devices such as mouse, keyboard, printer etc. Unlike other communication standards
such as RS 232 or parallel port, USB protocol also supply electric power therefore many
devices connected to USB do not need power source externally. The universal serial bus
offers single, standardize and easy way to connect up to 127 devices to a computer. This
project focuses on bidirectional data transfer between microcontroller and personal
computer using USB protocol standard. In this project, hardware and software co design
requires hardware of printed circuit board, LCD module, PIC microcontroller, USB cable
and software design of visual studio script in visual basic 6 and assembly code for
microcontroller.
2
Chapter 2 of the report includes basic understanding of USB protocol. This
chapter covers major features of the project. In chapter 2 architectural overview of the
protocol, types of data transfer and signals used in USB protocol and USB packet types.
Chapter 3 of the report describes features of EUSART (Enhanced Universal
Asynchronous Synchronous Receiver Transmitter) functionality. Especially, it gives
details of how to configure program and data memory.
Chapter 4 of the report includes features of LCD used in this project. This chapter
also covers interfacing of 16x2 LCD with PIC microcontroller.
Chapter 5 of the report shows block diagram and operation of the design. This
chapter starts with design of power supply and PL 2303 bridge controller. Then it covers
system requirements for the design and hardware implementation.
Chapter 6 of the report gives conclusion of this project and provides future
enhancement suggestions in the design.
3
Chapter 2
TYPES OF DATA TRANSFER USED IN USB
2.1
Introduction of USB Protocol
USB is a serial communication standard developed by seven companies in 1994.
The main goal of USB was to make data transfer between PC and peripheral devices
easier than what it was before. There are so many advantages of USB protocol over other
serial transfer protocols such as RS 232 such as lost cost solution for data, audio and
video, protocol flexibility in from of isochronous and asynchronous data transfers,
supports parallel connection between devices and many more. The recent motivation for
research in USB is because of increment in performance of personal computers day by
day and they are now capable of processing vast amount of data. Because of this high
processing speed of personal computers, we need a standard which can be effectively
communicate data between PCs and peripherals. User applications such as digital image
processing demands such kind of sophisticated standard. USB protocol comes with three
different speed standards such as low speed, full speed and high speed. Keyboard, mice
and other interactive devices works well on low speed devices. Phone, audio and
compressed video are used to communicate with full speed devices and video storage
imagining broad band are works well on high speed USB standard.
4
2.2
Architectural Overview of USB Model
The main USB system is divided in three parts such as USB interconnect USB
devices and USB host. There is only one host in any USB system at any time The host
controller is responsible of interface between USB interface and host computer. The host
controller is combination of hardware and software. The USB devices are connected in
star topology with USB host controller. The maximum numbers of tires that are allowed
in star topology is 7 and maximum devices that can be connected in 127 in any USB
protocol.
Figure 1: USB Physical Bus Topology [2]
Above figure shows the tired star topology by which devices such as host, root
hub and devices are connected to each other. Host always initiates the data transfer.
Devices do not speak unless spoken to. Hubs connects multiple devices called repeaters
and terminators. There are two kind of devices exists in USB protocol in terms of power.
One is self powered and another is bus powered. Self powered devices require external
5
power supply and bus powered devices consumes power from USB bus so no need to
connect with the power supply externally.
Data transfer takes place between host software and a particular endpoint on a
USB system. Such connection between host software and particular endpoint is called
pipes. More than one pipe can be there at any USB system any time. The USB
architecture consists of four basic types of data transfers.
2.3
Types of Data Transfer Used in USB Protocol
There are basically four types of data transfer modes supported by USB standard.
There four types are as follows.

Control Transfer

Bulk Data Transfer

Interrupt Driven Data Transfer

Isochronous Data Transfer
2.3.1 Control Transfer
With the use of control transfer different part of device can be accessed. Control
transfer can support configuration, command and status type of communication between
two devices. Every USB device must implement control transfer as a default transfer
mode. Pipe is implemented as a message pipe. Control transfer accommodates minimum
sets of command required by USB protocol. Bidirectional data flow can be supported
with control transfer mode in USB protocol. Transport mechanism is provided by control
6
transfer to access device descriptors. Only message pipes can carry control transfer
signals. An endpoint device and client software can not make request to access specific
bus for control transfer mode.
2.3.2 Isochronous Transfer
Isochronous transfer is useful for constant rate and error tolerance transfer. In
USB environment isochronous data transfer mode provide reliable access to USB
bandwidth but with bounded latency. Isochronous data transfer mode also provides
constant data rate throughout the transmission. Isochronous data transfer is always
unidirectional with compared to other transfer types. Two isochronous pipes must be
implemented if any device wants to follow bi directional data transfer using isochronous
mode. No error should be occurred during isochronous data transmission. If any error
occurs during isochronous data transmission it will not allow retransmission of data.
2.3.3 Interrupt Transfer
Any device that want to transmit or receive data infrequently but within bounded
service period can use interrupt data transfer mode. Interrupt transfer mode provide
guaranteed service period over pipe. Interrupt data transfer mode has a provision of
retransmission if any error occurs during transmission. Interrupt pipe is always
unidirectional. Interrupt data transfer mode can be used as low speed, high speed and full
speed devices. Handshaking signals should be used before transmitting data over
interrupt transfer mode.
7
2.3.4 Bulk Transfer
Bulk data transfer mode is generally used when any device want to transfer
relatively large amount of data. The bandwidth and time used in bulk data transfer mode
is highly variable with respect to time. Bulk data transfer mode provides facility of
retransmission of data in case of error signal. Bulk data transfer mode provides
guaranteed delivery of data but it can not provide guaranteed delivery of bandwidth or
latency. If any USB link has large amount of bandwidth than bulk transfer will happen
very quickly and if any USB link has relatively small amount of bandwidth, bulk transfer
will require relatively large amount of time. Only full speed and high speed USB devices
can use bulk data transfer mode.
8
2.4
USB Data Flow Model
Figure 2: USB Implementation Areas [7]
USB protocol establishes communication between host controller software and device
endpoints. Above figure shows the communication flow between two endpoints. From
the figure we can see that host initiates the data transfer with the help of client SW. The
simple communication between two endpoints involves number of layers each side.
Function layer, USB device layer and USB bus interface layer are main layers in the
communication system. The USB bus interface layer is sometime called as physical layer
provides physical/signaling/packet connectivity between the host and a device. The USB
9
device layer is responsible for how USB system software communicates with the USB
logical device. The USB device and function layer works together for effective
communication.
10
Chapter 3
PIC SERIAL COMMUNICATION
3.1
Configuring Oscillator Crystal Frequency
PIC18FXXXX devices can be operated in ten different oscillator modes. The
configuration bits FOSC<3:0> in configuration register 1H to select one of these ten
modes. In XP, LT, HS or HSLL modes crystal or ceramic resonator is connected between
OSC1 and OSC2 pins of the microcontroller. Parallel cut crystal design is required for the
oscillator design. Different capacitor values may be required to produce different
oscillator frequency. If we use the higher value of capacitor than it will increase the
stability of oscillator but at the same time it will also increase the start up time of design.
Sometime series resistor is required with the combination of crystal oscillator and two
capacitors. Below table shows the ideal capacitor selection for required frequency
generation. It is for example purpose only.
Crystal Frequency
Values of Capacitor
4MHz
C1 = 27pF
C2 = 27pF
8MHz
C1 = 22pF
C2 = 22pF
18MHz
C1 = 22pF
C2 = 22pF
20MHz
C1 = 15pF
C2 = 15pF
Table 1: Selection of Capacitor Values for Crystal Oscillator [1]
11
3.1.1
Use of Internal Oscillator Block
The microcontroller used in this project has internal oscillator block. If we use
this internal oscillator block than it will eliminate the need of external crystal resonator
along with capacitor and series resistor. The INTOSC output which is 8 MHz signal is
used as a main frequency source and it will drive the device clock. When a clock
frequency from 125 kHz to 8 MHz is selected, the INTOSC output is enabled.
Other clock source along with INTSOC is internal RC (INTRC) which is used to
provide 31kilohertz output. INTRC clock source is also enabled when any of these
signals are enabled such as power up timer, fail safe clock monitor, watchdog timer and
two speed startup. The IRCF bits of the OSCCON register will decide clock frequency by
selecting INTSOC or INTRC mode. Below figure shows the oscillator tuning register
and configuration bit settings.
R/W-0
R/W-o
INTSRC PLLEN
Bit 7
Bit 6
U-0
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
-
TUN 4 TUN 3 TUN 2 TUN 1 TUN 0
Bit 5 Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
Table 2: Oscillator Tuning Register [1]
Bit 7: INTSRC internal oscillator low frequency source select bit
1 = 31.25 kHz device clock derived from 8 MHz INTOSC source
0 = 31 kHz device clock derived directly from INTRC internal oscillator
Bit 6: PLLEN Frequency Multiplier PLL for INTOSC Enable bit
1 = PLL enabled for INTOSC (4 MHz and 8 MHz only)
0 = PLL disabled
12
Bit 4:0 TUN<4:0> Frequency Tuning bits
011111 = Maximum frequency
••
••
000001
000000 = Center frequency. Oscillator module is running at the calibrated
frequency.
111111
••
••
100000 = Minimum frequency
3.2
Baud Rate Calculation:
In transmit and status control register bit 2, high baud rate select bit (BRGH) is
used for the calculation of baud rate in design. Depending on bit value of BRGH field
crystal clock is divided by either 16 or 64.
So for a 4 Mhz crystal, BRGH = 1, to get 9600 baud;
BRG = 4000000/64/9600 = 6 and (6-1) = 5..................................................... (3.1)
And for 4 Mhz crystal, BRGH = 0, to get 9600 baud;
BRG = 4000000/16/9600 = 26 and (26-1) =25................................................ (3.2)
So these are the final values that we need to put into the BRG register field in order to get
desired baud rate.
3.2.1
Calculating the Value Being Placed in the SPBRG Register
If we want to transmit our data using 19200 bits per second of baud rate we have
to set the system clock on desired value. To get the desired result we need to write a
particular hexadecimal number to the SPBRG register. The value in the SPBRG register
13
will be responsible for setting up the clock cycle to the value that is required for the
desired baud rate.
The SPBRG register is 8 bit wide. As discussed previously in asynchronous
mode, the baud rate of transmission of information can be set to either on high speed or
on low speed. The rate selection, as already seen is made by BRGH bit in TXSTA
register. BRGH = 1 is high speed and BRGH = 0 is low speed. The equation below is
used to calculate each baud rate for the design.
SPBRG = (Fosc / (16 x Baud rate)) - 1, BRGH = 1 High Speed.................................. (3.4)
SPBRG = (Fosc / (64 x Baud rate)) - 1, BRGH = 0 Low Speed................................... (3.5)
Example: In our design if we want to get baud rate of 19200 bits per second we
will calculate the hex value that is going to be put in SPBRG resister. The calculation was
done for low speed baud rate.
The formula SPBRG = (Fosc / (64 x Baud rate)) - 1, BRGH = 0 (for low speed)
Thus SPBRG = (6.1 MHz/ (64 * 19200)) – 1 = 3.96, but it is not possible to load
non integer number inside SPBRG register so value has been rounded off to 4.00. Below
table shows different baud rates that are used in asynchronous mode of PIC18F
controllers.
14
Table 3: Baud Rates for Asynchronous Mode [1]
3.2.2
Calculating Baud Rate Error:
For a device with Fosc of 1.6 MHz, desired baud rate of 19200 bits per second,
asynchronous mode, 8 bit BRG,
Desired baud rate = FOSC/ (64([SPBRGH: SPBRG] +1)) and if we solve the
equation for SPBRGH: SPBRG than,
X = ((Fosc/desired baud rate)/64) – 1
X= ((1600000/9600)/64) – 1
X= 3.97 = 4.0 and now the calculated baud rate is
Calculated rate = (1600000/ (64(4+1))
= 19550................................................................................ (3.6)
3.2.3
Error
= (Calculated baud rate – Desired baud rate)/ Desired baud rate
Error
= (19550-19200)/ (19550)
Error
=5.5%................................................................................... (3.7)
Auto Baud Rate Detection Technique
The enhanced USART (Universal Synchronous Asynchronous Receiver
Transmitter) module inside the PIC18 series microcontroller supports the feature called
15
automatic baud rate detection and calibration. This feature works only in asynchronous
mode. This feature is enabled when WUE bit is set to 0 in BAUDCON register. Register
BAUDCON is associated with asynchronous transmission and reception with PIC
controller. In BRG mode the clock methodology is reversed. Usually BRG is used to
clock the Rx signal but in auto baud rate detection technique Rx signal is timing the
BRG. In ABD mode internal baud rate generator is used as a timer for incoming serial
byte stream. Below diagram shows the calculation of automatic baud rate in PIC18F
series controllers.
Figure 3: Automatic Baud Rate Calculation [1]
Once the ABDEN bit is set by user as shown in diagram, the FSM (Finite State
Machine) inside the controller will check clear BRG and will wait for a start bit on RX
16
pin. The ABD logic must receive signal with value of 55h (hex) to start baud rate
calculation. The calculation will take place on RX pin on both low and high value in
order to eliminate asymmetrical effect of incoming signal. After the proper start bit, the
SPBRG signal will start counting until fifth positive edge of incoming RX signal. After
the fifth rising edge the total value of BRG will be loaded into the SPBRG: SPBRGH
register pair. Once the fifth bit is seen which is followed by STOP bit the ABEDN
register will roll over and will start counting again. The BRG register are clocked at
1/8’th of the actual clock rate while measuring the baud rate. The ESURT FSM will held
idle while automatic baud rate detection technique takes place.
3.3
Configuration of Enhanced Asynchronous Transmitter & Receiver
ESURT feature of PIC microcontroller can be used in two ways. It can be used as
asynchronous transmitter as well as synchronous transmitter and receiver. Clearing the
SYNC bit will enable asynchronous mode of operation. Standard NRZ format is used by
asynchronous mode of operation. Eight bit is the most common data format used by this
mode of operation. The ESURT transmits and receives LSB first. Transmitter and
receiver of ESURT module are functionally independent but they are using the same data
format and baud rate. Hardware does not support parity bit but can be implemented using
software using additional ninth bit. EUSART asynchronous transmitter and receiver have
been individually covered in the report.
3.3.1
EUSART Asynchronous Transmitter Functionality
Figure shows EUSART transmitter block. Transmit (serial) shift register (TSR) is
a core part of transmitter design. This is a one kind of serial shift register. This shift
17
register is received data from TXREG register. TXREG is R/W buffer register. Device
driver software will load data into the TXREG register. The TSR register is loaded once
STOP bit is transmitted from the previous load. Once STOP bit is arrived the TSR
register is loaded for next transmit sequence.
Figure 4: EUSART Transmitter Block Diagram [11]
Once the data is sent to TSR register from TXREG register the TXIF flag is set
and TXREG register will be emptied. The interrupt enable bit (TXIE) is used to disable
or enable interrupt signal. The TSR register is not available to user because it is not
mapped to data memory.
18
3.1.1.1 To Initialize an Asynchronous Transmission

SPBRGH and SPBRG registers were initialized at appropriate baud rate. To
achieve desired baud rate BRGH and BRG16 bit has to be set or clear.

Asynchronous serial port was enabled by clearing SYNC bit and setting
SPEN.
3.3.2

Enable bit TXIE was enabled for interrupts. This is optional signal.

Transmit bit TX9 was enabled for address/data signal.

TXEN bit was set to enable transmission which in turn will initialize TXIF bit.

TXREG register was loaded with data and data than transmission will start.
EUSART Asynchronous Receiver Functionality
Below figure shows EUSART asynchronous receiver. RX pin received data from
transmitter and used to drive data recovery block. High speed shifter is used as data
recovery block. Data recovery block works as 16 times faster than actual baud rate. Main
receive signal operates at original Fosc frequency. This mode is typically used in RS232
based systems.
19
Figure 5: EUSART Receiver Block Diagram [11]
3.3.2.1 To Initialize an Asynchronous Reception

SPBRGH and SPBRG registers were initialized at appropriate baud rate. To
achieve desired baud rate BRGH and BRG16 bit has to be set or clear.

Asynchronous serial port was enabled by clearing SYNC bit and setting
SPEN.

Bit RCIE was enabled for interrupt facility.

Bit RX9 was not used as project was using 8 bit transmission.

Bit CERN was set to start reception.
20

RCIF, flag bit is set when reception is complete.

RCSTA bit was used to check if any error has occurred during reception

Read the RCREG bit to determine address of the device and clear the ADDEN
bit to interrupt CPU.
3.4
Configuring Program and Data Memory
Basically there are three types of memories provided in 18 series advanced
microcontroller devices. There are Program Memory, Data RAM (Random Access
Memory) and Data EEPROM (Electrical Erasable Programmable Read Only Memory).
As per the architectural specification separate buses are used by two separate buses. This
allows simultaneous access of both the memory types. EEPROM was used for data of
peripheral devices. EEPROM can be addressed and accessed through set of control
registers. PIC18 microcontroller has 21 bit program counter which is able to access 3MB
memory space. Controller which was used in the project has 32 KB of FLASH memory.
18F devices have two interrupt vectors. One is reset vector and another is interrupt
vector. Their addresses are 0000h and 0008h. Program counter specifies address of the
instruction. This instruction is used to fetch for next execution. Program counter has
width of 21 bits. Program counter has 3 8 bit registers. They are logically separated from
each other.
21
3.4.1
Utilization of Data Memory
Static RAM (Random Access Memory) is used as Data Memory in PIC18F
devices. Total 4096 byte of data memory has 12 bit addressed register. Whole memory
space is divided into 16 banks that contain 256 bytes each. There are two types of register
belongs to data memory. One is special function register, (SFR) and another is general
purpose register called (GPR). Special function register is used to control peripheral
functions and general purpose registers are used for data storage and other important
functions. There are three addressing modes by which the whole data memory can be
accessed called direct addressing, indirect or indexed addressing. Normally SFR and
GPR can be accessed in single instruction cycle. There is one more register called Bank
Select Register (BSR) in data memory SRAM (static ram) which is used to select desired
bank. The value in BSR will let used know the bank in data memory.
3.4.2
Use of FLASH Program Memory
Flash program memory can be read, write and erased during normal operation at
any time. Flash program memory can be read 1 byte at a time. Flash program me memory
can be written 32 bytes at a time. 64 blocks in program memory can be erased at a time.
During write and erase of program flash memory, flash memory will stop fetching new
instruction. Program cannot be executed during write or erase cycle of program FLASH
memory. There are two operations that will allow processor to move data between
program memory space and SRAM which is used for data memory. These two operations
are table read (TBLRD) and table write (TBLWT). Data RAM is 8 bits wide while the
program memory is almost 16 bits wide.
22
Chapter 4
LCD INTERFACING MODULE
4.1
Introduction
This chapter includes LCD interfacing module with PIC microcontroller used in
this project. The main objective of this chapter is to discuss about interfacing of
HD44780 based character LCD with 8 bit PIC microcontroller. A liquid crystal display is
thin crystal used for displaying purpose which works on light modulating principal.
LCDs are having very wide range of applications such as personal computer, cell phones,
PDAs, music players, television, and automobiles. LCDs are very energy efficient and
can work well on low DC voltage. LCDs can produce images in either in color or in
monochrome. LCD modules do not produce light by their own but they require external
light source. Two types of light source can be used to glow LCD modules. One is
fluorescent lamp that is situated behind the LCD panel and other is LED backlight LCD
display.
4.2
Description
HD44780 based 16x2 LCD module is very popular for interfacing with PIC
microcontroller. They are cheap compare to other modules and they can display
characters as well. Most of PIC controllers have built in library routines for HD44780
LCD modules. The whole interface requires 6 I/O lines along with 4 data lines and 2
control lines. Below figure shows the block diagram of standard 16x2 line LCD.
23
Figure 6: LCD Block Diagram [11]
The HD44780 based LCD module is connected through 14 pins. Below table
shows the pin configuration of LCD module used in this project.
NAME
FUNCTION
PIN NO
1
Vss
Ground
2
Vdd
Power Supply
3
Vee
Contrast
4
RS
Register Select
5
R/W
Read/Write
6
E
Enable
7
D0
Data Bit 0
8
D1
Data Bit 1
9
D2
Data Bit 2
10
D3
Data Bit 3
11
D4
Data Bit 4
12
D5
Data Bit 5
24
13
D6
Data Bit 6
14
D7
Data Bit 7
Table 4: LCD Pin Configuration [9]
There are total 8 data pins available called D0 to D7. RS, E and R/W are three
control pins in module. Vdd, Vee, Vss pins are available for power purpose. Some LCDs
have extra control pins called LED+ and LED- for illumination purpose. This feature
helps user to read LCD during low illumination conditions.
The control pins RS is responsible for data transaction between LCD module and
PIC microcontroller. This data transaction can be anything such as actual character data
or command/control signals. RS pin is pulled low when microcontroller needs to send
any command or control signals to LCD module. RS pin is pulled high in contrast when
microcontroller needs to send actual data to LCD module. The read and write operation is
controlled by pin R/W. If microcontroller wants to write some data on LCD module than
R/W pin is pulled high and when microcontroller wants to read something from LCD
module than this R/W pin is pulled low. The enable (E) pin is used for actual data
transfer. When writing to the LCD display, the data is transferred only on the high to low
transition of the E pin. [9]
This LCD module works well on constant 5V DC power supply. Some other LCD
module also works on +3.3 to +5.5 voltage range. For proper connection of power
supply, Vdd pin is always connected with positive +5V DC supply and Vss pin is always
25
connected to the ground. LCD brightness is controlled by Vee pin. Potentiometer is used
to control brightness of LCD.
Pin numbers 7 to 14 are called data pins. These pins are used to transfer data
between microcontroller and LCD module. Data transfer can be achieved from either 4
bit or 8 bit mode. For 8 bit mode all data lines are used to transfer data while in 4 bit
mode only 4 data lines are used for interfacing.
4.3
LCD PIC Driver Module
New series of PIC microcontroller has built in LCD driver module. PIC16F and
PIC18F series have this extra future. These new PIC controllers are flash based and LCD
enabled. They are built in facility of power management. These microcontroller can drive
LCD module even in sleep mode.
Figure 7: Block Diagram of LCD-PIC Driver Module [10]
26
These microchip’s new LCD enabled microcontrollers can support both type of
displays. They can support segmented and touch screen display for interfacing.
Segmented display includes both seven segments and 16 segments. Seven segment
display is used to create numbers and sixteen segment display is used to create custom
characters and icons.
The block diagram shown in figure includes clock source, timing control
mechanism and LCD data registers for interfacing. The first block of diagram is clock
source. This block is responsible for generating the waveforms. This waveforms are used
to drive LCD module. Timing control is the second block in diagram. Based on LCD
control register LCDCON, timing control block generate waveform. LCD phase register
and LCD segment enable register provides additional support to timing control block.
The third block of diagram describes LCD data registers which contains bits to support
individual pixel of LCD screen.
4.4
Schematic of Interfacing Module
This section discusses about basic interfacing of 8 bit PIC microcontroller and
LCD module. Below figure shows the schematic of LCD module interfacing with 8 bit
PIC microcontroller such as PIC18F452. This diagram shows the data transfer in 8 bit
mode. As we discussed earlier, microcontroller can support both 4 bit and 8 bit mode
depending on the requirements. Pin Vdd and Vee are grounded. +5V DC supply is
connected with the Vss pin. Data pins D0 to D7 are connected with pins RD0 to RD7 of
PIC microcontroller.
27
Figure 8: LCD Interfacing Module with PIC 18F452 Microcontroller [8]
Pin number 4 (RS) of LCD module is connected with pin number 33 (RB0/INT0)
of PIC controller. This pin is responsible for sending command or data to controller. Pin
number 5 (R/W) is connected with pin number 34 (RB1/INT1) of PIC controller. This pin
is used to select read or write logic. Pin 6 of LCD module called enable is connected
with pin number 35 of controller. This pin is used to enable the LCD module for any data
transfer and command application. This schematic shows the basic idea for LCD
interfacing. This is just for example purpose. Actual circuit used in this design is more
complicated depending on applications.
28
4.5 Software Used
Software used in this design is divided in two parts. One part is responsible for
personal computer user interface and another part is responsible for microcontroller
interfacing with other peripherals. The personal computer interface is designed in visual
basic professional version 6.0. The microcontroller interface is implemented in PIC
assemble language.
The LCD data and control lines are controlled through port C. Therefore port C is
defined as output port. Port A is responsible for data transfers therefore port A is defined
as digital port. Comparator function of PIC microcontroller is disabled. The programming
of HD44780 is little bit complex compare to other LCD modules. This programming
requires proper timing control and accurate control on command signals. [9]
4.6 Source Code for LCD Module
LCDINIT:
movlw 0x38
bcf
STATUS,C
rrcf
WREG
rrcf
WREG
movwf LATA
bsf
LCD_E
nop
bcf
LCD_E
call
delay1ms
29
bsf
LCD_E
nop
bcf
LCD_E
call
delay1ms
bsf
LCD_E
nop
bcf
LCD_E
call
delay1ms
movlw FUNC_SET
bcf
STATUS,C
rrcf
WREG
rrcf
WREG
movwf LATA
bsf
LCD_E
nop
bcf
LCD_E
call
delay1ms
movlw FUNC_SET
call
LCD_CMD
movlw DISP_ON
call
LCD_CMD
movlw DISP_CLR
30
call
LCD_CMD
movlw ENTRY_SET
call
LCD_CMD
clrf
LCD_OFST
;
movlw DISP_ON_B
;
call
LCD_CMD
return
LCD_CMD:
movwf LCD_TEMP
call
;Command to be sent is in W (0xMN)
delay1ms
movlw 0x00
movwf LCD_DATA
bcf
LCD_RS
call
LCD_Send
;Set LCD in command mode
return
LCD_CHAR:
movwf LCD_TEMP
call
;Command to be sent is in W (0xMN)
delay1ms
movlw 0x00
movwf LCD_DATA
bsf
LCD_RS
call
LCD_Send
;Set LCD in data mode
31
return
LCD_Send:
movf LCD_TEMP, W
bcf
;W = 0xMN
STATUS,C
movwf LATA
bsf
LCD_E
;LCD E-line High
LCD_E
;LCD E-line Low
nop
bcf
swapf LCD_TEMP, W
bcf
STATUS,C
rrcf
WREG
rrcf
WREG
;W = 0xNM
movwf LATA
end
bsf
LCD_E
;LCD E-line High
bcf
LCD_E
;LCD E-line Low
32
Chapter 5
BLOCK DIAGRAM AND OPERATION
5.1
Introduction
This Chapter discuss about block diagram of entire design. As shown in block
diagram this design includes constant 5V DC power supply, PL-2303 serial bridge
controller, microcontroller based printed circuit board (PCB) and LCD module
interfacing with PIC controller. Below figure shows the block diagram of entire design.
5.2
Block Diagram
Figure 9: Block Diagram of Microcontroller Based Device
33
5.3
Design of Power Supply
Power supply used in this project was to convert high voltage AC into low fixed
voltage DC. 5V DC power supply was used to run LCD module. USB based
microcontroller module was bus powered so not required for external power supply.
Design of power supply was broken down in series of steps such as transformer, rectifier,
filter circuit and selection of regulator IC. Transformer was used to convert high AC
voltage to low DC voltage that can drive LCD module with fix current ratings.
Transformer can only work with AC. In our project step down transformer was used.
There is little bit power loss from input to output.
Figure 10: Block Diagram of 5V DC Power Supply Design [5]
Rectifier is used to convert AC signal to pulsating DC signal. Diodes are main
part of design. Here in this project full wave bridge rectifier was used. It is called full
wave rectifier because it uses each positive and negative pulses of AC to convert into DC.
34
Figure 11: Transformer and Bridge Rectifier Circuit Diagram [5]
Filter circuit is used to smooth the pulsating DC output waveforms. Large value
of capacitor connected across power supply. It will block AC parameters and allow DC
parameters of electrical signal to pass through. Because of charging and discharging of
capacitor, output of filter circuit had ripple voltage. This ripple voltage was eliminated by
using series of capacitor and resistor pair.
IC7805 was used as +5V DC regulator. Transformer output was given to full
wave bridge rectifier. This full wave bridge rectifier will convert AC waveform into
pulsating DC signals. Output of bridge rectifier was given to regulator module made up
with IC7805. This module was used to produce fixed positive 5 volt DC supply.
35
5.4
PL-2303 Serial Bridge Controller
Figure 12: Schematic of PL2303 Serial Bridge Controller [6]
The PL2303 is universal serial bridge controller which is used to establish
communication between PIC18F series microcontroller and windows/Unix based
personal computer through USB protocol. It provides bridge connection. It has standard
DB9 pin male port at one end and standard type
Figure 13: PL 2303 Serial Adapter [6]
36
A USB connector at other end. It provides very simple way to adding serial
connection to your PC without having any physical serial port. This USB serial bridge
connector is very ideal for modems, cell phones, digital cameras, smart digital devices
which are using serial protocol for communication. PL-2303 can be used to provide up to
1Mbps transfer rate. It can be used with all windows operating system.
5.4.1
System Requirements for PL-2303 Bridge Controller

Windows 98, ME, XP, Vista and 7

USB 1.1 or higher port for interfacing

Intel or AMD processor which should be more than 133 MHz

PL-2303 Driver for related operating system. (Open Source)

USB to RS-232 serial cable adapter
5.5 Microcontroller Based Printed Circuit Board
Figure 14: Microcontroller Based Printed Circuit Board
37
The design used for this project is implemented on printed circuit board. As we
discussed earlier, microcontroller used for this design is PIC18F452. A 6.1 MHz of
external oscillator is used for this design. Crystal type of oscillator is used for this design.
PL 2303 serial bridge controller is used between microcontroller and personal computer.
9 key based keypad is used to transmit date from PCB to personal computer. 4K7 register
bank is used along with keypad. LCD module was implemented along with keypad and
microcontroller. 16x2 LCD was used for this design. Potentiometer was used to control
brightness of LCD. Pull up resistor 4K7 was used with pin RXD of controller. Pull up
resistor 4K7 was used with pin TED of controller. Capacitor C1, C2 and C3 used along
with the power supply. These capacitors are used for smoothing purpose. IC 7805 was
used to generate constant 5V DC voltage. Step down transformer was used to down the
supply voltage below specific level. 9V connector was used to attach power supply with
the design. This power supply used to drive LCD module. PIC microcontroller is self
powered microcontroller. PIC18F microcontroller used to draw current from USB bus.
Once the hardware outline has fixed, mounting of components started according
to the schematic of the design. Special care was taken during soldering of components.
Unwanted open or short of connections can happen if any mistake occurs during
soldering. Multimeter was used to check diode test of design. IC socket was used for
assembly of PIC controller on PCB. Direct soldering on controller could damage the
device due to high temperature of soldering device. Kana kit programmer was used to
program microcontroller. The tool used to interface with kana kit was MPLAB IDE. The
microcontroller was supported with both on chip, in circuit serial programming (ICSP)
38
and off chip programming facility. After all connections were done with soldering on
PCB, the device was connected with personal computer via USB cable.
5.6
Software Implemented
5.6.1
Flow Chart
The software that is designed in this project is divided in two main parts. One that
is designed to program the PIC controller and another is done in Visual Basic to send data
and command signals from host controller to PIC controller.
Initial part of flow chart discusses about welcome message displayed on LCD
screen. When fully connected PCB is connected with the power supply, it will display
welcome message called “HELLO DR. PANG” on LCD screen. The code for welcome
screen is written in an assembly language that supports PIC microcontroller.
Next block of flow chart discusses about virtual com port generation. When
device is connected with USB type A to A male connector to personal computer it
generates the random virtual com port number. The generated virtual com port number
can be checked in device manager properties under my computer icon on personal
computer. Now device is ready for bidirectional data transfer.
Next block of flow chart discuss about visual basic script which is used to enter
text string which is to be displayed on LCD screen. This same script is used to display
ball movement controlled by controller based device.
Last block of flow chart is all about disconnecting controller based device from
personal computer. Once the device is disconnected from personal computer, data
transfer stops automatically.
39
IDLE/START
When device is connected to power
supply
Welcome message called ‘Hello Dr.
Pang” displayed on the screen
When device is connected with
personal computer via USB cable
Virtual COM port number is generated
by personal computer
Device is ready for bidirectional data
transfer
When user types anything on visual
basic script on personal computer
Same text string is displayed on LCD
module
When user press any key on keypad
module
Virtual ball moves accordingly on
personal computer screen
When device is disconnected with
personal computer
USB link discontinuous and end of data
transfer
END/IDLE
Figure 15: Flow Chart Design of Software Implemented
40
Personal computer is used to send data and command to the controller over USB
cable with the use of control transfer mode. Hex file was an essential requirement to
program microcontroller. Microcontroller can only understand the hex file format.
MPLAB ID3 tool suite is used to convert assembly file into the hex file. Hex file is a type
of file which controller can understand. After conversion of hex file from assembly file
was done, Cana kit programmer was used to download the hex file into the controller.
Before downloading the code into the controller, blank check of IC was performed. After
blank check operation was done, hex file was imported from the source folder and
downloaded into the controller. Serial bridge controller (PL 2303) was used as a
communication medium between PIC controller and personal computer. Driver software
designed for PL 2303 was downloaded into the personal computer. Selection of the driver
software was done on basis of operating system running on the personal computer. After
everything was installed on both sides, the controller based device was connected with
personal computer with the help of USB cable. Type A to A male usb cable was used for
this communication.
When the microcontroller based device was connected with the PC, the PC
realized that a device has been connected via USB port. The device manager tab in my
computer path was used to check the status of connected USB device. COM and LPT
ports showed up in the device manager tab. Virtual COM port number was generated
every time the device attached with the personal computer and controller based device
used to show some welcome message on LCD screen.
41
Figure 16: “HELLO DR PANG” Message on LCD
Below figure shows form used to show up which is developed in visual studio
when device is connected with the PC.
Figure 17: Snap Shot Showing USB Device Recognize by Personal Computer
The required virtual COM port number was selected with the help of this visual
studio form. This from was also used to indicated the how many bits of data transfer will
be take place along with parity information and baud rate used for transfer. Figure shows
42
the form developed in visual basic 6.0 that was used to show up once the correct port
number has been selected.
Figure 18: Visual Studio Form to Enter Text Data
Appendix A includes the main assembly file for the microcontroller code. The
firmware was written in assembly code was able to communicate with most windows
based systems. Once the device has been connected to the personal computer and power
cable is plugged to device the message called Hello Dr. Pang was appeared on LCD. This
message was written in assembly code to check if the LCD module is working properly
or not. Once the correct port number selected by user, another visual studio form showed
up on the screen. This form was used to enter text based data that is going to be send to
43
controller device. Than the controller was used to send the text data to the LCD module.
This form was also used to display ball movement controlled by keypad on PCB board.
5.7
Simulation Results
The project successfully transferred bidirectional data transfer between
microcontroller and personal computer using USB protocol. The LCD module was used
to display data that was written in personal computer in visual basic form. The same
visual basic form was used to display ball movement that was controlled by key pad
implemented on PCB.
Initial task was to check if the LCD module is working properly or not. Assembly
code was developed to check LCD module and microcontroller interface. Another task
was to convert assembly code into hex code. Hex code is the only file format that
microcontroller can understand. MPLAB tool suite ID3 was used to develop hex file from
assembly code. Figure 14 shows the result of MPLAB tool suite.
Figure 19: Simulation Result of MPLAB Tool Suite
44
Converted hex file from assembly file was supposed to be downloaded into the
microcontroller to make controller work as required. PicKit2 tool suite was used make
this task successful. Cana Kit PIC programmer was used as hardware to download hex
file into PIC microcontroller. Figure 15 shows the result from PicKit2 tool suite.
Figure 20: Simulation Result of Pic Kit2 Tool Suite
45
PIC microcontroller was mounted on the IC socket residing on PCB to make
whole design work after downloading hex file into it. Well Come screen showed up on
LCD module mounted on PCB when connected to power supply.
After testing of LCD module was done the controller based device was connected
with the personal computer. The personal computer recognized the device and showed
the successful sign in task bar of personal computer. The device manager under my
computer properties was used to recognize what kind of device is connected with the
USB port of PC. The advance setting tab in profilic serial bridge adapter was used to
check the virtual COM port number of connected device. Figure 16 shows the virtual
COM port number of connected device.
Figure 21: Detecting of Virtual COM Port on Personal Computer
46
After setting everything the script developed in visual basic 6.0 was executed to
initiate data transfer. A form popped up in the screen of personal computer. Below figure
shows the visual basic form used to enter virtual COM port number of the device
connected. After entering the proper virtual COM port number and hitting OK button on
the first form of visual basic script, another form was popped up. This form was used to
enter text data that is to be displayed on LCD screen. Figure 17 shows the form of visual
basic script to enter desired text value along with LCD module on PCB. Successful data
transfer was done with USB protocol between personal computer and microcontroller
based device.
BALL
LEFT KEY
BALL
RIGHT KEY
BALL
BALL
LEFT KEY
BALL
DOWN KEY
RIGHT KEY
DOWN KEY
BALL
Figure 22: Ball Movements on Personal Computer
47
Figure 23: Simulation Result on Microcontroller Based LCD Interface
Figure 24: Simulation Result on Personal Computer
48
Chapter 6
CONCLUSION AND FUTURE WORK
The main focus of the project was to implement bidirectional USB
communication design between personal computer and PIC microcontroller based printed
circuit board. Hardware and Software co design technique was successfully implemented
in this project. Assembly language programming was used for PIC18F microcontroller
and visual basic script was written for personal computer to send data and command LCD
and microcontroller. PIC microcontroller based board implemented on printed circuit
board to establish communication with personal computer. LCD module along with 9 key
keypad was implemented on PCB to send and receive data with personal computer. This
project gives a very good experience in bidirectional USB communication and its
standards. This project can also be used as a reference for large amount of data transfer
between two devices.
Initial limitations can be improved by future enhancement in the project. With the
use of more powerful controller such as 16 bit or 32 bit we can communicate large
amount of data between two devices. With the use of different type of LCD, image files
can be transferred from personal computer to remote device using USB protocol.
External memory can be used to accommodate large amount of data along with 16 or 32
bit microcontroller. The speed at which the data transfer took place can be increase with
the use of microprocessor which is having high clock rate.
49
APPENDIX
Source Code
VERSION 5.00
Object = "{648A5603-2C6E-101B-82B6-000000000014}#1.1#0"; "MSCOMM32.OCX"
Begin VB.Form Form1
BorderStyle = 1 'Fixed Single
Caption
= "Form1"
ClientHeight = 7800
ClientLeft
= -15
ClientTop
= 375
ClientWidth = 12270
LinkTopic
= "Form1"
MaxButton
= 0 'False
MinButton
= 0 'False
ScaleHeight = 7800
ScaleWidth
= 12270
StartUpPosition = 3 'Windows Default
Begin VB.TextBox Text2
BeginProperty Font
Name
= "Calibri"
Size
= 21.75
Charset
= 0
Weight
= 400
Underline
= 0 'False
Italic
= 0 'False
Strikethrough = 0 'False
EndProperty
Height
= 660
Left
= 3240
TabIndex
= 0
Text
= "ABCDEFGHIJKLMNOPQRTSUVWXYZ"
Top
= 6600
Width
= 6375
End
Begin MSCommLib.MSComm MSComm1
Left
= 240
Top
= 0
_ExtentX
= 1005
_ExtentY
= 1005
_Version
= 393216
DTREnable
= -1 'True
50
End
Begin VB.Shape Shape1
Height
= 6015
Left
= 600
Top
= 360
Width
= 10575
End
Begin VB.Label Command1
BackStyle
= 0 'Transparent
Caption
= "Click To Send"
BeginProperty Font
Name
= "Tahoma"
Size
= 15.75
Charset
= 0
Weight
= 400
Underline
= 0 'False
Italic
= 0 'False
Strikethrough = 0 'False
EndProperty
ForeColor
= &H000000FF&
Height
= 495
Left
= 5520
TabIndex
= 1
Top
= 7200
Width
= 2055
End
Begin VB.Shape Shp_Move
BackStyle
= 1 'Opaque
FillColor
= &H000080FF&
FillStyle
= 0 'Solid
Height
= 495
Left
= 10440
Shape
= 3 'Circle
Top
= 360
Width
= 975
End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
'1 form with
51
'1 textbox : name=text1, multiline=true, scrollbars=3(both)
'1 textbox : name=text2
'1 command button
'1 mscomm control (Microsoft Comm Control 6.0)
Dim ComPortNo As Integer
Option Explicit
Private Sub Command1_Click()
With MSComm1
'make sure the serial port is open
If .PortOpen = False Then .PortOpen = True
'send the data (including a tailing carriage return as often needed)
.Output = Text2.Text & Chr$(&HAA)
End With 'MSComm1
With Text2
'place the focus back to the textbox
.SetFocus
'select the current text to be overwritten
.SelStart = 0
.SelLength = Len(.Text)
End With 'Text1
End Sub
Private Sub Form_Load()
Dialog.Show vbModal, Me
ComPortNo = Dialog.SelComPort
Unload Dialog
If (ComPortNo = 0) Then End
With MSComm1
'make sure the serial port is not open (by this program)
If .PortOpen Then .PortOpen = False
'set the active serial port
.CommPort = 14
'set the badurate,parity,databits,stopbits for the connection
.Settings = "19200,N,8,1"
'set the DRT and RTS flags
.DTREnable = True
.RTSEnable = True
'enable the oncomm event for every reveived character
.RThreshold = 1
'disable the oncomm event for send characters
.SThreshold = 0
52
'open the serial port
.PortOpen = True
End With 'MSComm1
' With Text1
' 'set the properties for the displaying textbox
' .BackColor = vbCyan
' .Locked = True
' .Text = ""
' End With 'Text1
' With Text2
' 'set the properties for the 'send' textbox
' .TabIndex = 0
' .Text = ""
' End With 'Text2
' With Command1
' 'set the properties for the 'send' command button
' .Caption = "&Send"
' .Default = True
' .TabIndex = 1
' End With 'Command1
End Sub
'Private Sub Form_Resize()
' Dim sngWidth As Single, sngHeight As Single
' Dim sngDisplayHeight As Single
' Dim sngTxtWidth As Single
' Dim sngCmdWidth As Single, sngCmdHeight As Single
' 'calculate the inner size of the form
' sngWidth = ScaleWidth
' sngHeight = ScaleHeight
' With Command1
' 'resize and reposition the command button
' sngCmdHeight = .Height
' sngCmdWidth = .Width
' sngDisplayHeight = sngHeight - sngCmdHeight
' sngTxtWidth = sngWidth - sngCmdWidth
' .Move sngTxtWidth, sngDisplayHeight, sngCmdWidth, sngCmdHeight
' End With 'Command1
' 'resize and reposition the label
' 'Text1.Move 0, 0, sngWidth, sngDisplayHeight
' 'resize and reposition the textbox
' 'Text2.Move 0, sngDisplayHeight, sngTxtWidth, sngCmdHeight
'End Sub
53
Private Sub MSComm1_OnComm()
Dim strInput As String, Data As Integer
With MSComm1
'test for incoming event
Select Case .CommEvent
Case comEvReceive
'display incoming event data to displaying textbox
strInput = .Input
'Text1.SelText = strInput
Data = Val(strInput)
Select Case Data
Case 1:
Shp_Move.Left = Shp_Move.Left - 100
If Shp_Move.Left < 360 Then Shp_Move.Left = 360
Case 2:
Shp_Move.Left = Shp_Move.Left - 100
If Shp_Move.Left < 360 Then Shp_Move.Left = 360
Shp_Move.Top = Shp_Move.Top + 100
If Shp_Move.Top > 5880 Then Shp_Move.Top = 5880
Case 8:
Shp_Move.Left = Shp_Move.Left + 100
If Shp_Move.Left > 10440 Then Shp_Move.Left = 10440
Shp_Move.Top = Shp_Move.Top + 100
If Shp_Move.Top > 5880 Then Shp_Move.Top = 5880
Case 5:
Shp_Move.Top = Shp_Move.Top + 100
If Shp_Move.Top > 5880 Then Shp_Move.Top = 5880
Case 7:
Shp_Move.Left = Shp_Move.Left + 100
If Shp_Move.Left > 10440 Then Shp_Move.Left = 10440
Case 4:
Shp_Move.Left = 5640
Shp_Move.Top = 3120
Case 3:
Shp_Move.Top = Shp_Move.Top - 100
If Shp_Move.Top < 360 Then Shp_Move.Top = 360
Case 6:
Shp_Move.Left = Shp_Move.Left + 100
If Shp_Move.Left > 10440 Then Shp_Move.Left = 10440
Shp_Move.Top = Shp_Move.Top - 100
If Shp_Move.Top < 360 Then Shp_Move.Top = 360
Case 9:
54
Shp_Move.Left = Shp_Move.Left - 100
If Shp_Move.Left < 360 Then Shp_Move.Left = 360
Shp_Move.Top = Shp_Move.Top - 100
If Shp_Move.Top < 360 Then Shp_Move.Top = 360
End Select
End Select
End With 'MSComm1
End Sub
55
REFERENCES
1. Microchip Technology, “PIC18FXX2 Data Sheet”, Document Number
DS39564C
[http://ww1.microchip.com/downloads/en/devicedoc/39564c.pdf]
2. Craig Peacock, “USB in a nutShell”, 3rd release, November 2002
[http://www.beyondlogic.org/usbnutshell/usb1.shtml]
3. Muhammad Ali Mazidi, Rolin McKinlay and Danny Causey, “PIC
Microcontroller and Embedded Systems”, The Islamic Uni of Gaza
4. Microcontroller Board Forun, “PIC Serial Communication Tutorial”
[http://www.microcontrollerboard.com/pic_serial_communication.html]
5. RSH Electronics, The Electronics Club Forum, “Power Supply Design Tutorial”
[http://www.kpsec.freeuk.com/powersup.htm]
6. Electronics Product Store, “PL 2303 USB to TTL Module”
[http://iteadstudio.com/store/index.php?main_page=product_info&products_id=2
83&zenid=vlr1b6ugciosnvgi95msu642k7]
7. Jeff Friesen, “Java and USB”. Today.java.net, 6 July, 2006
[http://today.java.net/pub/a/today/2006/07/06/java-and-usb.html]
8. TyFER, “Thread: PIC18F452, GPS and LCD”. edaboard.com, 3 July, 2008
[http://www.edaboard.com/thread119870.html]
9. R-B, “Lab 4: Interfacing a character LCD”. Embedded-lab.com, 7’th Nov, 2007
[http://embedded-lab.com/blog/?p=203]
10. Microchip Technology, “LCD PIC Microcontroller Solutions”, PIC
Microcontrollers with Integrated LCD driver Module
[http://ww1.microchip.com/downloads/en/devicedoc/39666b.pdf]
56
11. Milan Verle, “PIC Microcontrollers”, mikroElektronika, 1st edition (2008), ISBN:
978-86-84417-15-4
[http://www.mikroe.com/eng/chapters/view/7/chapter-6-serial-communicationmodules/]
Download