You are on page 1of 71

IMPLEMENTATION OF USB INTERFACE USING

MICROCONTROLLER
A project report submitted in partial fulfillment of the requirement for the award of degree of
MASTER OF ENGINEERING(ME)
IN
SYSTEMS & SIGNAL PROCESSING
BY
V. RAMA VARA PRASAD
(1005-10-749207)
Under the Guidance of
D. RAMA KRISHNA
Assistant Professor

CONTINUING ENGINEERING EDUCATION PROGRAMMES(CEEP)


UNIVERSITY COLLEGE OF ENGINEERING (Autonomous)
OSMANIA UNIVERSITY
HYDERABAD-500 007
2013

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


OSMANIA UNIVERSITY
HYDERABAD- 500 007

CERTIFICATE
This is to certify that the project report entitled "IMPLEMENTATION OF

USB INTERFACE USING MICROCONTROLLER" that is being


submitted by

Mr. V. Rama Vara Prasad, Roll no. 1005-10-749207 in partial

fulfillment for the award of degree of Master of Engineering in Systems and Signal
Processing at Osmania University Hyderabad is a record of bonafide work carried
out by him under my guidance and supervision the results are verified and found
satisfactory.
Certified further that to the best of my knowledge the work in this dissertation
has not been submitted to any other university or institute for the award of any
degree.

External guide

Internal Guide

Signature:

Signature:

Mr.Ajay kumar ,

D. Rama Krishna,

Assistant Manager R&D,

Assitant Professor,

Medha Servo Drives Pvt ltd,

Osmania University,

Hyderabad.

Hyderabad

ACKNOWLEDGEMENT
The Satisfaction that accompanies the successful completion of any task would be
incomplete without the mention of the people who made it possible and whose encouragement and
guidance has been a source of inspiration throughout the course of the project.
I am very much thankful to my external guide Mr. Ajay Kumar, Assistant Manager R&D,
Medha Servo Drives Pvt Ltd, Hyderabad, for his constant encouragement throughout this
project.
I express my deep sense of gratitude and profound thanks to my academic guide D.Rama
Krishna, Assistant professor, Osmania university, Hyderabad for the guidance provided in
completeing the project.
I am very much thankful to the Dr. P. Chandrashekar, Professor & Head of Electronics
and Communication Engineering Department, Osmania University, Hyderabad for constatnt
encouragement throughout this project.

Finally, I am thankful to my friends, who helped me in bringing out this project report as it
looks.

V. RAMA VARA PRASAD


(1005-10-749207)

ABSTRACT
The Universal Serial Bus(USB) had largely replaced the standard serial port to connect
devices to a PC because it is simpler, more foolproof and faster. But while USB makes connection
easier for the user, it adds more design challenges, many designers continue to use the
UART(Universal Asynchronous Receiver Transmitter) with the standard serial port, waiting for
products that make USB easier to implement.
The main objective is to develop the USB interface using Micro Controller which inturn able
to communicate with PC. The development will be in such a way that it will have the USB 2.0
specified things.
The required things to implement is to have an interface of Micro Controller with a USB
transceiver inbuilt. The Input section of transceiver will be interfaced with Micro Controller
internally and output section will be serial data(D+ and D-) of required voltage levels that support
USB2.0 physical layer.
In this work, Enumeration level will be Implemented in micro Controller so as to recognize
the USB device by PC.

CONTENTS
CERTIFICATE
ACKNOWLEGDEMENT
ABSTRACT
1 . INTRODUCTION
2. USB DESCRIPTION
3.HARDWARE DESRIPTION
4.USB DEVICE DEVELOPMENT
5.RESULTS
TOOLS & COMPONETS
BIBLIOGRAPHY

1.INTRODUCTION
1.1 PURPOSE
The purpose of this project is to design and develop a usb protocol interface for AC-AC
Traction systems which is being developed for Indian railways to interface AC-AC tration system
with PC/Laptop to download vaious system generated parameters like faults, event information etc.

1.2 SCOPE
The scope of this document is for engineers, students ans academicians who intend to know
and develop usb prorocol interface. Total USB Communication includes two steps, first one is
enemuration and second one is communication. Presently in this project upto first step is developed
i.e developed device shall be deteted by PC after completeion of enemuration. Enemuration is the
major task while developing a USB protocol interface. The Project can be further enhanced by
implementing second step, in second step custom software has to be written for the developed
custom device, they shall be agreed in commands and can be communicated.

1.3 PROJECT MOTIVATION


Recent motivation for a separate USB 2.0 protocol engine stems from the fact that
PCs have increasingly higher performance and are capable of processing vast amounts of
data. At the same time, PC peripherals have added more performance and functionality. User
applications such as multimedia applications demand a high performance connection between the PC
and these highly sophisticated peripherals.
The separate Protocol Engine addresses this need by working in parallel with the
Micro Controller hence releasing the microprocessor from the burden of dealing with basic
data transfer assignments such as token encoding and decoding, CRC check etc. This
architecture will increase the parallel work of the USB device and increase its overall speed.

1.4 ORGANISATION OF TEXT


The Text is organised in a manner as follows, chapter 2 gives an insight idea of USB,
Chapter 3 gives hard ware description , chapter 4 gives USB device development and firmware and
Chapter 5 gives Results.

2.USB DESCRIPTION
2.1 Introduction
The Universal Serial Bus (USB) is a specification developed by Compaq, Intel,
Microsoft and NEC, joined later by Hewlett-Packard, Lucent and Philips. These companies
formed the USB Implementers Forum, incorporated as a non-profit corporation to publish the
specifications and organize further development in USB. The USB is specified to be an
industry-standard extension to the PC architecture with a focus on PC peripherals that enable
consumer and business applications. Main goal of the USB protocol was to replace the over
growing number of different ports of PC connectivity. For example, parallel, ps/2 ports and serial
could now be replaced by one simple connection. The USB will do the same role of all the replaced
ports and suitable for all applications and peripherals.
USB 2.0 is an Industry-wide, host oriented protocol, employing serial bus,
supporting up to 127 devices and hot insertion. Several criteria were applied in defining the
architecture for the USB: Ease-of-use for PC peripheral expansion. USB 2.0 represents a
great advance in speed while keeping a low-cost solution that supports transfer rates of up to 480
Mbps. With full support for real-time data, voice, audio, and video it is the chosen protocol for most
PC peripherals today. Comprehension of various PC configurations and form factors make the
USB a multifunctional protocol capable of servicing various solutions.
The USB is a generic protocol making its interface capable of quick diffusion into
product. Augment the PCs capability by enabling new classes of devices giving the USB a
capability to be implemented in new developed devices, advancing with technology. Fully
backward compatibility of USB 2.0 for devices built to previous versions of the USB
specification.
2.2 Robustness
The key advantage of the USB protocol is its robustness. The USB has signal
integrity which enables it to use differential drivers, receivers, and shielding. CRC protection
over control and data fields. Detection of attach and detach and system-level configuration of
resources. Self-recovery in protocol, using timeouts for lost or corrupted packets. Flow control
for streaming data to ensure isochrony and hardware buffer management. Data and control
pipe constructs for ensuring independence from adverse interactions between Functions.
2.3 Error Detection

The core bit error rate of the USB medium is expected to be close to that of a
backplane and any glitches will very likely be transient in nature. To provide protection
against such transients, each packet includes error protection fields. When data integrity is
required, such as with lossless data devices, an error recovery procedure may be invoked in
hardware or software. The protocol includes separate CRCs for control and data fields of
each packet. A failed CRC is considered to indicate a corrupted packet. The CRC gives
100% coverage on single- and double-bit errors.
2.4 Error Handling
The protocol allows for error handling in hardware or software. Hardware error
handling includes reporting and retry of failed transfers. A USB Host Controller will try

transmission that encounters errors up to three times before informing the client software of
the failure. The client software can recover in an implementation-specific way.
2.5 Data Speeds
The USB specification defines three data speeds:
Low Speed
This was intended for cheap, low data rate devices like mice. The low speed captive cable is
thinner and more flexible than that required for full and high speed.
Full Speed
This was originally specified for all other devices.
High Speed
The high speed additions to the specification were introduced in USB 2.0 as a
response to the high speed of Firewire.

Table 2.1 USB data speeds


2.6 Devices Endpoints
An endpoint is a uniquely identifiable portion of a USB device that is the final stop of a
communication flow between the host and device. Each USB logical device is composed of
up to 30 independent endpoints and a control endpoint. To reach an endpoint the host must
send a packet to the correct device address assigned by the system at device attachment time, and
the correct endpoint number given at the design time. Each endpoint has a device-determined
direction of data flow, up to 15 IN and 15 OUT endpoints are available and an additional control
endpoint which is always referred to as endpoint zero. The combination of the device address,
endpoint number, and direction allows each endpoint to be uniquely referenced.

Figure 2.1 Each endpoint supports data flow in one direction:either input(from device to host) or
output(from host to device)

2.7 Descriptor Tables


USB devices report their attributes using descriptors. A descriptor is a data structure
with a defined format. Each descriptor begins with a byte-wide field that contains the total
number of bytes in the descriptor followed by a byte-wide field that identifies the descriptor
type. Using

descriptors

allows

concise

storage

of

the

attributes

of

individual

configurations because each configuration may reuse descriptors or portions of descriptors


from other configurations that have the same characteristics. In this manner, the descriptors
resemble individual data records in a relational database.
2.7.1 Device Descriptor Table
A device descriptor describes general information about a USB device. It includes
information that applies globally to the device and all of the devices configurations. A USB device
has only one device descriptor.
All USB devices have a Default Control Pipe. The maximum packet size of a devices
Default Control Pipe is described in the device descriptor. Endpoints specific to a
configuration

and

its

interface(s)

are

described

in

the

configuration

descriptor. A

configuration and its interface(s) do not include an endpoint descriptor for the Default
Control Pipe. Other than the maximum packet size, the characteristics of the Default Control Pipe
are defined by this specification and are the same for all USB devices. Table 2.2 shows the
Standard Device Descriptor Table.

Table 2.2 Standard Device Descriptor Table


2.7.2 Configuration Descriptor Table
The configuration descriptor

describes

information

about

specific

device

configuration. The descriptor contains a bConfigurationValue field with a value that, when used as
a parameter to the SetConfiguration() request, causes the device to assume the described

configuration. The descriptor bNumInterfaces field describes the number of interfaces provided by
the configuration. Each interface may operate independently. For example, an ISDN device
might be configured with two interfaces, each providing 64 Kb/s bi-directional channels
that have separate data sources or sinks on the host. Another configuration might present the ISDN
device as a single interface, bonding the two channels into one 128 Kb/s bi-directional
channel. When the host requests the configuration descriptor, all related interface and
endpoint descriptors are returned. A USB device has one or more configuration descriptors. Each
configuration has one or more interfaces and each interface has zero or more endpoints. An
endpoint is not shared among interfaces within a single configuration unless the endpoint is
used by alternate settings of the same interface. Endpoints may be shared among interfaces
that are part of different configurations without this restriction. Table 2.3 shows the Configuration
Descriptor Table.

Table 2.3 Configuration Descriptor Table


2.7.3 Interface Descriptor Table
The interface descriptor describes a specific interface within a configuration. A
configuration provides up to four interfaces, each with zero or more endpoint descriptors
describing a unique set of endpoints within the configuration. When a configuration supports
more than one interface, the endpoint descriptors for a particular interface follow the
interface descriptor in the data returned by the GetConfiguration() request. The descriptor
contains a bInterfaceNumber field that specifies the number of the interface.
An interface descriptor is always returned as part of a configuration descriptor. Interface
descriptors cannot be directly accessed with a GetDescriptor() or SetDescriptor() request.
Table 2.4 shows the Interface Descriptor Table.

Table 2.4 Interface Descriptor Table


2.7.4 Endpoint Descriptor Table
Each endpoint used for an interface has its own descriptor. This descriptor contains the
information required by the host to determine the bandwidth requirements of each endpoint.
The descriptor contains a bEndpointAddress field that specifies the direction and endpoint
number. bmAttributes field is used to determine the endpoint type (i.e Bulk, Isochronous,
Control or Interrupt). wMaxPacketSize field contains the value of the Maximum packet size this
endpoint is capable of sending or receiving. For isochronous endpoints, this value is used to
reserve the bus time in the schedule, required for the per-microframe data payloads. An
endpoint descriptor is always returned as part of the configuration information returned by a
GetDescriptor(Configuration) request. There is never an endpoint descriptor for endpoint zero.
Table 2.5 shows the Endpoint Descriptor Table.

Table 2.5 Endpoint Descriptor Table.

2.8 Token Packets

Table 2.6 Token packet bit distribution


A token packet consists of a PID, ADDR and ENDP fields. Table 2.6 shows the
field formats and their respective number of bits. Packet ID specifies either IN, OUT or
SETUP packet type. PID codes table is available in Table 2.7. For OUT and SETUP
transactions, the address and endpoint fields uniquely identify the endpoint that will receive the
subsequent Data packet. For IN transactions, these fields uniquely identify which endpoint
from a unique addressed device should transmit a Data packet. Only the host can issue
token packets. An IN PID defines a data transaction from a function to the host. OUT and
SETUP PIDs define data transactions from the host to a function. The tokens correctness is
assured by the combination of two mechanisms. The 4 bits representing the PID field are
duplicated and negated to become 8 bits long. The ADDR and ENPD fields are protected by the
CRC5 field.

Table 2.7 PID Codes Table


2.9 Data Packets

Table 2.8 Data packet bit distribution


A data packet consists of a PID, data field containing zero or more bytes of data, and a

CRC16 as shown in Table 2.8. There are four types of data packets, identified by different
PIDs: DATA0, DATA1, DATA2 and MDATA. DATA0 and DATA1 are defined to support data
toggle synchronization in bulk, setup and interrupt transactions. All four data PIDs are used in
data PID sequencing for high bandwidth high-speed isochronous endpoints. Data must always
be sent in integral even number of bytes. Similar to the token packet, the data CRC16 is computed
over only the data field in the packet and does not include the PID, which has its own check field.
2.10 Handshake Packets

Table 2.9 Data packet distribution


Handshake packets, as shown Table 2.9, consist of only a PID. Handshake packets are
used to report the status of a data transaction.
Assuming successful token decode, a device, upon receiving a data packet, may return any
one of the handshake types:

If the data packet was corrupted, the function returns no handshake.

If the data packet was received error-free and the functions receiving endpoint is
halted,the function returns STALL.

If the transaction is maintaining sequence bit synchronization and a mismatch is


detected, then the function returns ACK and discards the data.

If the function can accept the data and has received the data error-free, it returns
ACK.

If the function cannot accept the data packet due to flow control reasons like out of space, it
returns NAK.
Upon receiving a SETUP token, a device must accept the data. A device may not

respond to a SETUP token with either STALL or NAK, and the receiving device must accept the
data packet that follows the SETUP token. If a non-control endpoint receives a SETUP token,
it must ignore the transaction and return no response. Isochronous transactions have a token and
data phase, but no handshake phase. The host issues an OUT token followed by the data phase
in which the host transmits data. Isochronous transactions do not support a handshake
phase or retry capability.
2.11 Setup Packet
Every USB device must respond to requests from the host on the devices endpoint zero.
The setup packets are used for detection and configuration of the device and carry out common
functions such as setting the USB devices address, requesting a device descriptor or checking the
status of an endpoint. These requests are made using control transfers. The request and the

requests parameters are sent to the device in the Setup packet. Every Setup packet has eight bytes
with the following fields: bmRequestType One byte field which identifies the characteristics of
the specific request. In particular, this field identifies the direction of data transfer in the second
phase of the control transfer. The state of the Direction bit is ignored if the wLength field is zero,
signifying there is no Data stage. The bitmap of bmRequestType field is specified in the table
below.

Table 2.10 bmRequest bitmap


bRequest This 8 bit field specifies the particular request based on the Table 2.11 bRequest
codes below.

Table 2.11 bRequest Codes


wValue Two byte field with variable content according to the request. It is used to pass a
parameter to the device, specific to the request.
wIndex Two byte field with variable content according to the request. It is used to pass a
parameter to the device, specific to the request. The wIndex field is often used in requests to specify
an endpoint or an interface.

wLength - Two byte field which specifies the length of the data transferred during the second
phase of the control transfer. The direction of data transfer (host-to- device or device-tohost) is indicated by the Direction bit of the bmRequestType field. If this field is zero, there is
no data transfer phase.

Table 2.12 Format of setup data


2.12 Enumeration Process
After a device is powered on it must follow the enumeration process to receive an address
from the host and configuration. When in powered state it must not respond to any bus transactions
until it has received a reset from the bus. After receiving a reset, the device is then addressable at
the default address. The device then waits for a setup token which precedes the setup packet
for the SET_ADDRESS request. After the setup token has been received correctly, the host
will send a setup packet to endpoint zero, with address zero and with packet ID DATA0.
The setup packet contains the SET_ADDRESS request which contains the device new
address assigned by the host. The new address is saved in the wValue field of the setup
packet (see Table 2.12 for wValue description). After the device changes its address it enters the
Addressed state. The device will enter its final state called Configured State which starts
once the device receives the SET_CONFIGURATION request with a non-zero wValue field.
2.13 USB Communications Flow
All communications on the USB bus are initiated by the host. This means, for
example, that there can be no communication directly between USB devices. A device
cannot initiate a transfer, but must wait to be asked to transfer data by the host. In any

Figure 2.2 The logical connection of a USB

USB system there is only one host and up to 127 peripherals. The attached peripherals
share USB bandwidth through a host scheduled, token-based protocol.
The USB is a polled bus. Each transaction begins when the host controller, on a scheduled
basis, sends a USB packet describing the type and direction of transaction, the USB device address,
and the endpoint number. This packet is referred to as the token packet. The USB device that is
addressed selects itself by decoding the appropriate address fields from the token packet. In a given
transaction, data is transferred either from the host to the device or from the device to the host. The
source of the transaction then sends a data packet. If transfer was successful the destination,
excluding isochronous type of transactions, responds with a handshake packet indicating the
transfer was successful.

Figure 2.3 Atypical USB transaction involves a token followed by a data packet and ends with a
handshake packet
2.14 Transaction Types
The USB architecture comprehends four basic types of data transfers:
1. Control Transfers - Control data is used by the USB System Software to configure devices
when they are first attached. Mandatory using Endpoint 0 OUT and Endpoint 0 IN.
2. Bulk Transfers - Bulk data typically consists of larger amounts of data, such as that
used for printers or scanners. Bulk data is sequential. Reliable exchange of data is ensured.
Bulk transfers are designed to transfer large amounts of data with error-free delivery,
but with no guarantee of bandwidth. The host will schedule bulk transfers after the
other transfer types have been allocated.
3. Interrupt Transfers - A limited-latency transfer to or from a device is referred to as interrupt
data. Such data may be presented for transfer by a device at any time and is
delivered by the USB at a rate no slower than is specified by the device
4.

Isochronous

Transfers

Isochronous

data

is

continuous

and

real-time

in

creation, delivery, and consumption. Timing-related information is implied by the

steady rate at which isochronous data is received and transferred. Isochronous


data must be delivered at the rate received to maintain its timing. A typical example of
isochronous data is voice. The timely delivery of isochronous data is ensured at the
expense of potential transient losses in the data stream, where it is important to
maintain the data flow, but not so important if some data gets missed or corrupted.
In

other

words,

any

error

in

electrical transmission is not corrected by hardware

mechanisms such as retries.


2.15 Data Toggle Synchronization
The USB provides a mechanism to guarantee data sequence synchronization between
data

transmitter

and

receiver

across

multiple

transactions.

This mechanism provides a

means of guaranteeing that the handshake phase of a transaction was interpreted correctly
by both the transmitter and receiver. Synchronization is achieved via use of the DATA0
and DATA1 PIDs and separate data toggle sequence bits for the data transmitter and
receiver. Receiver sequence bits toggle only when the receiver is able to accept data and receives
an error-free data packet with the correct data PID. Transmitter sequence bits toggle only when the
data transmitter receives a valid ACK handshake. The data transmitter and receiver must
have their sequence bits synchronized at the start of a transaction. The synchronization
mechanism used varies with the transaction type. Data toggle synchronization is not supported for
isochronous transfers.

3.HARDWARE DESCRIPTION
The USB Interface Module kit Primarly consists of a microcontroller, JTAG connector, Led
Indications and associated hardware and sofware.The microcontroller is the MC9S08JM16 motorola
family controller having a 256 bytes of USB RAM. The block diagram view is given in figure 3.2.
The description if each of these is given in this chapter.
3.1 MICROCONTROLLER
The MC9S08JM16 was chosen as controller. The features which makes this controller more
preferable to this project and it is having 16kb flash to store code and 1kb RAM and 256 bytes of
USB RAM. MC9S08JM16 series MCUs are members of the low-cost, high-performance HCS08
family of 8-bit microcontroller units (MCUs). All MCUs in the family use the enhanced HCS08 core
and are available with a variety of modules, memory sizes, memory types, and package types.
On-chip memory in the MC9S08JM16 series of MCUs consists of RAM, flash program memory for
nonvolatile data storage, plus I/O and control/status registers. The registers are divided into three
groups:

Figure 3.1 Memory Map of MC9S08JM16

Direct-page registers (0x0000 through 0x00AF)

High-page registers (0x1800 through 0x185F)

Nonvolatile registers (0xFFB0 through 0xFFBF)

3.2 Block Diagram of MC9S08JM16 :

Figure 3.2 Block diagram of MC9S08JM16


The 8-bit MC9S08JM16 device further extends Freescales entry-level 8-bit embedded USB
controller family with up to 16 KB of flash memory, a full-speed USB 2.0 device controller and an
eight-channel, 12-bit

analog-to-digital converter. The S08 JM family also has several system

protection features, such as low voltage detection and a computer operating properly (COP) module.
The MC9S08JM16 device is well suited

for a variety of industrial control and

consumer

applications. Such applications include PC peripherals, industrial printers and touch panels.
Features

Benefits

8-bit HCS08 Central Processing Unit (CPU)


Up to 24 MHz internal bus (48 MHz HCS08
core) frequency offering 2.7 to 5.5V across
temperature range of -40C to +85C

Offers strong performance throughout the


entire
voltage range

Support for up to 32 peripheral interrupt/


request resources

Allows for exceptional software flexibility and


optimization for real-time applications

On-Chip Memory
Up to 16K flash read/program/erase over full
operating voltage and temperature

Allows user to take full advantage of inapplication,


re-programmability benefits

Up to 1K RAM

Security circuitry to help prevent unauthorized


access to RAM

Flash contents help to reduce system power


consumption
256 Byte USB RAM

Improve data transfer speed by providing


data buffering

Power-Saving Modes
Wait plus two stop modes

Allows continuation of sampling application


in a reduced
power state which reduces system power
consumption

Multi-purpose clock generator (MCG)

Frequency-locked loop (FLL): Internal or


external
reference can be used to control the FLL
Phase-locked loop (PLL): Voltage controlled
oscillator (VCO). Modulo VCO frequency
divider.
Lock detector with interrupt capability
Internal reference clock: Can be selected as
the
clock source for the MCU
External reference clock: Provides control for
a separate crystal oscillator. Clock monitor with
reset capability. Can be selected as the clock
source for the MCU.
Reference divider provided
Clock source can be divided by 1, 2, 4 or 8

Peripherals
USB device module

Full-speed USB 2.0 (12 Mbps) module with


dedicated on-chip 3.3V regulator
Supports control, interrupt, isochronous and
bulk transfers

Analog comparators (ACMP)Analog


comparator with option to compare to
internal reference

Requires only single pin for input signal,


freeing up
other pin for other use
Allows other system components to see
comparator result with minimal delay
Can be used for single slope ADC and RC
time
constant measurements

Analog-to-digital converter (ADC)Eightchannel, 12-bit resolution

Output formatted in 12-, 10- or 8-bit


right-justified format
Single or continuous conversion
Operation in low-power modes for lower
noise operation
Asynchronous clock source for lower
noise operation

Two serial communications interface


(SCI) modules offering asynchronous
communications

Provides standard UART communications


peripheral
Allows full-duplex, asynchronous, NRZ serial

communication between MCU and remote


devices
I 2 C with up to 100 kbps with maximum bus
loading; multi-master operation; programmable
slave address; interrupt driven byte-by-byte
data transfer; supports broadcast mode and
10-bit addressing

Ability to add an additional I 2 C device

SPITwo serial peripheral interfaces with


full-duplex or single-wire bidirectional; doublebuffered transmit and receive; master or slave
mode; MSB-first or LSB-first shifting

Having two SPI allows two separate dedicated


devices, for example, one SPI dedicated to a
ZigBee transceiver, and the other to MCUs or
peripherals

Timer pulse width modulation (TPM)Up to Each channel may be input capture, output
six channels
compare or edge-aligned PWM
Input capture trigger on either rising or falling
edge
Selectable polarity on PWM outputs
Timer clock source selectable as prescaled bus
clock, fixed system clock or an external clock
pin
Input/Output
Up to seven Keyboard Interrupt (KBI) pins
with
selectable polarity

Each KBI pin is programmable as falling edge


only,
rising edge only, falling edge and low level, or
rising
edge and high level interrupt sensitivity

37 general purpose input/output (GPIO)s

Results in a large number of flexible I/O pins


that
allow vendors to easily interface the device into
their own designs

System Protection
Watchdog computer operating properly (COP) Allows the device to recognize run-away code
reset with option to run from dedicated 1 kHz
(infinite loops) and resets the processor to help
internal clock source or bus clock
avoid lock-up states
Low-voltage detection with reset or interrupt; Alerts the developer to voltage drops outside
selectable trip points
of the
typical operating range
Illegal op code detection with reset

Allows the device to recognize erroneous code


and
resets the processor to help avoid lock-up states

Flash block protection

Prevents unauthorized access to flash RAM


which
greatly reduces the chance of losing vital system
code for vendor applications

Hardware Development Support


Single-wire background debug interface

This allows developers to use the same


interface
for multiple platforms

Breakpoint capability

Allows single breakpoint setting during incircuit


debugging (plus two more breakpoints in onchip
debug module)

On-chip in-circuit emulator (ICE) debug


module (containing three comparators and
nine trigger modes). Eight deep FIFO for
storing change-of-flow addresses and
event-only data, debug module supports
both tag and force breakpoints.

Grants full access to built-in chip emulation


without
the added expense of traditional emulator
hardware

Table 3.1 Features and Benefits of MC9S08JM16


3.3 Understanding of MC9S08JM60 USB Module:
3.3.1MC9S08JM60 USB Module Introduction
Figure 3.3 shows the block diagram of the USB module for MC9S08JM60 MCU.

Figure 3.3 Block diagram of the USB module for MC9S08JM60 MCU.
It includes:

On-chip 3.3 V regulator (VREG)

USB transceiver (XCVR)

Serial interface engine (SIE)

USB RAM

Figure 3.4 shows the layers of a typical USB device.

Figure 3.4 USB Protocol Layer


The physical layer involves data signaling, such as J and K signals, start of packet (SOP), and
resume signals. The USB PHY of MC9S08JM60 corresponds to the physical layer.
The protocol layer lies above the physical layer. Transactions of different transfer type are
managed by this layer. The packet (handshake, etc.), in the USB low-level protocol are processed in
this layer. In the MC9S08JM60 USB module, they are finished by SIE.
The command processor and data report handler layer lies between the protocol and
application layers. The USB enumeration and configuration, the standard class request, or the
customized protocol are all to be processed by this layer.
The top layer is the application layer. It it is based on the USB communication provided in the
low layers. The program in this layer focuses on the customized application.
3.3.2 USB Endpoint
One important concept needs to be discussed before explaining the USB module - the
endpoint. Each USB logical device consists of a collection of independent endpoints. An endpoint is a
uniquely identifiable portion of a USB device that is the terminus of a communication flow between
the host and device. USB pipe is an association between an endpoint on a device and software on the
host.

The MC9S08JM60 device has seven endpoints that can be used to build seven communication
pipes between the USB host and device. Endpoint 0 is bidirectional (in and out); its mainly used for
control transfer. Endpoint 0 is required for all USB devices. Endpoint 16 are directional: they can be
configured to do only in or out direction communication at a time. Endpoint 5 and 6 are double
buffering, that is also be called ping-pong buffer. Each of these has two buffers. One buffer can be
operated by the CPU, when the other communicates with the host (controlled by SIE). These two
buffers exchange their roles after the current transaction is over. The CPU has the control of one of the
double buffers in turn. With this feature, the communication efficiency improves because the CPU
waiting time is shortened.
Each endpoint can be enabled or disabled by the EPCTLn register. The direction and
handshake for all endpoints are also controlled by the EPCTLn register.
The control transfer, bulk transfer, isochronous transfer, and interrupt transfer are all supported
by each endpoint of MC9S08JM60 series MCU. That matches all kinds of USB data transfer
requirements.
3.3.3 VREG
On-chip regulator (VREG) provides a stable power source to the USB internal transceiver and
internal (or external) pullup resistor. It requires a voltage supply input in the range of 3.9 V to 5.5 V,
and its output voltage range is from 3.0 V to 3.6 V. The VREG shares the same power supply with the
MCU, but the MCU can work with the power voltage from 2.7 V to 5.5 V. The corresponding pin to
regulator output voltage is VUSB3.3 , that can be used to supply the power for the external pullup
resistor. The on-chip regulator can be enabled or disabled by USBVREN bit of the USBCTL0 register.
If it isdisabled, an external 3.3 V voltage must be provided to USB module via VUSB3.3 pin.
NOTE
Damage to the part may occur if the external 3.3 V power supply is provided while the internal
regulator is enabled.
3.3.4 USB Transceiver
USB transceiver belongs to the physical layer of the USB standard protocol. It provides a
differential signal for USB communication. The USBDP and USBDN pins are analog input/output
lines for full-speed data communication.
3.3.5 USB SIE
The USB serial interface engine (SIE) is mainly used to implement transferring and receiving

of logic. For the SIE transferring logic, the firmware immediately needs to configure three BD
registers and fills the data into endpoint buffer; then hands over the control to SIE. The SIE will send
the data to the host automatically after the host issues an IN operation. All work required in the USB
specification, such as coding (NRZI), bit stuffing, CRC, SYNC, etc., are implemented by SIE without
firmwares intervention. The SIE hands over the control to the CPU after the transfer is finished.
As for the receiving logic, the SIE can receive data packets automatically. The receiving logic
process includes decoding, synchronizing, detection, bit stuff removal, EOP detection, CRC
validation, PID check, etc.
The data packet is filled into the endpoint buffer, and the BD registers are updated. Then the
SIE gives the control to the CPU for reading data out. Some status and flag bits in the USB registers
(INSTAT, STAT, ERRSTAT, and EPCTLn) for this transaction are refreshed. The SIE owns the
control of the BD and endpoint buffer before the data ends to receive.
The SIE sends the acknowledge (ACK) or non-acknowledge (NAK) handshake to the host. It
also stalls the current transfer (STALL). The handshake is enabled or disabled by the EPHSHK bit in
the EPCTLn register. If it is enabled, ACK is transferred to the host when the transaction is correctly
received. The NAK is sent out by SIE if the OWN bit in BD status and control register is 0. The
STALL is issued by setting the EPSTALL bit in the EPCTL register or the BDTSTALL bit in the BD
status and control register.
With the SIE transferring and receiving logic, the work of the firmware is greatly reduced
resulting in more CPU time being saved.
3.3.6 USB RAM
MC9S08JM60 MCU provides 256 bytes RAM space for the USB module, in which the USB
BD registers and endpoint buffer are located. The USB RAM can also be allocated by the system as
general purpose RAM when the USB module is disabled or it still has free space.
The USB RAM runs at 48 MHz, which is twice the speed of the bus clock. It can be accessed
by the CPU system and SIE. This is an area to exchange data and information between the CPU and
SIE.
All the USB control and the status registers (BD registers) and USB data buffer must be
allocated in the USB RAM. It is illegal to allocate them in other space.The USB RAM occupies a
separate space instead of a part of the MCU RAM. From the memory map of MC9S08JM60 in Figure
3, the USB RAM address range is from 0x1860 to 0x195F, but the 4K bytes of MCU RAM starts
from 0x00B0, ends at 0x10AF.

Figure 3.5 USB RAM


Figure 3.5 shows the USB RAM location of MC9S08JM60 in the memory map.
3.3.7 Buffer Descriptor Table (BDT)
Buffer descriptor table (BDT) is used to manage USB endpoint communication efficiently. It
provides the status and control for each endpoint.

Figure 3.6 Buffer Descriptor


These registers for each endpoint are called buffer descriptor (BD). Each BD comprises three
bytes, in which the endpoint data buffers location, length, control logic, and status are kept.
The BDT locates at the beginning of USB RAM. The BDs for seven endpoints are organized and
placed one by one from EP0 in to EP6 out. There are 10 BDs in total and 30 bytes are allocated from

0x1860 to 0x187D (offset: 0x000x1D in USB RAM space).


Figure 3.6 shows the BDs for seven endpoints and three BD registers for endpoint 0 (in
direction). For endpoint 0 (bidirectional), 5 and 6 (double buffer), each has two BDs. Endpoint of 14
owns only one BD.
The first byte of the BD is the status and control register (see Figure 3.7). It includes four bits
that the CPU reads or writes for controlling the USB communication. They are OWN (bit 7),
DATA0/1(bit 6), DTS (bit 3), and BDTSTALL (bit 2).

Figure 3.7 Status and Control Register of BD

BDTSTALL can be set by the CPU to stall the next transaction. A STALL handshake is issued on

its associated endpoint if the BDTSTALL bit is set.


The DTS bit is used to enable or disable the data toggle synchronization.
DATA0/1 bit defines a DATA0 or DATA1 packet to be transmitted or received.

OWN bit is implemented as the semaphore mechanism. Its value determines whether the BD and

endpoint buffer is controlled by the CPU or SIE. When it is set to logic 0, the CPU has the control of
the BD and endpoint buffer, the CPU can modify the contents of the BD registers and the data in the
endpoint buffer. If it is set to logic 1, the SIE has the control of BD and endpoint buffer.
The bit[5:2] are updated by SIE after a new token packet is received. The token packet PID is kept
in these four bits.
The firmware designer must rewrite all bits in the status and control the register in terms of the
configuration for the next transaction. Otherwise all the data packets may not be received or
transferred. The wrong setting for DATA0/1 results in the data being discarded by the SIE or the host.
The DTS and BDTSTALL bits can also result in the data packet not being received or being stalled.
The values for these two bits are replaced by bit 0 and bit 1 of the new packets PID. They must be
updated before the next packet is allocated.
The second byte (BC[7:0]) is the length of the data packet to be transferred or the packet that
has been received. It can be set to zero for some packets (e.g, the transaction in the status stage of
control transfer). The maximum length is 64 for the MC9S08JM60 MCU. The BC register must be set
to the actual packet size to be transferred for the in direction endpoint, but it must be initialized to be

greater than or equal to the packet size that is received for out direction endpoint.
The third byte (EPADD[9:2]) keeps the start address of the endpoint buffer. It must be filled
with the bit 92 of the relative address in USB RAM. It can be calculated by shifting two bits of the
relative address to right so the endpoint buffer address is four bytes alignment.
Figure 3.8 shows an example for calculating the value of the EPADD register. Provided that the
endpoint buffer locates 0x1880 (absolute address), the address relative to the start address of USB
RAM is 0x20.
Thus the value of EPADD for the endpoint can be calculated by shifting the value 0x20 two bits to
right and the result is 0x08.

Figure 3.8 Example for calculating the value of EPADD Register


Setting these registers correctly is the basic requirement for successful endpoint
communication. Figure 3.9 is an example of BDT configuration. It shows the content in the BD
registers of the endpoint 0 and 1. In this example, the buffer length is eight bytes for endpoint 0 (in
and out) and four bytes for endpoint 1. The endpoint buffers are allocated continually from 0x1880
(relative address 0x20).

Figure 3.9 BDT Configuration Example


Endpoint 0 in direction:
If the content of the status and control register is 0x00, the CPU still has the control of BD. If
the BC[7:0] register is filled with 0x08, it means that the packet size transmitted by EP0 in is eight
bytes. This value takes effect when the SIE controls this endpoint.
The maximum packet size for the endpoint is transferred to the host in the USB device
enumeration process. The value for the BC registers can be less than the maximum value the data
that exceeds the maximum length must be divided into several packets. The actual number to be
transferred to the host must be set to the BC register before the OWN bit of the status and control
register is set (hand over the control of BD to SIE).
The value of EPADD[9:2] is 0x08. It can be calculated by the start address allocated for
endpoint 0 in direction. Its absolute address is 0x1880. The calculation method is illustrated in Figure
3.8.

Endpoint 0 out direction:


The BD for endpoint 0 out direction is set to receive a DATA0 packet. The content of the
status and control register is 0x88, which means the control for BD and data buffer has handed over to
SIE (OWN = 1), endpoint 0 will receive DATA0 (DATA0/1 = 0) packet, and the data toggle has been
enabled (DTS = 1), the correct data packet is received (STALL = 0).
The SIE changes the OWN bit to 0 for handing over the control to the CPU. When one packet
is finished receiving, the exact data length is updated and written to BC register.
Endpoint 1 in direction:
The endpoint 1 is used for the in direction (transmitting data to the host). It is configured to
transfer only four bytes.
NOTE
When developing firmware, the programmer must avoid the address overlap for different
endpoint buffers. In addition, the maximum size of the endpoint buffer must be the same as the length
in the USB configuration descriptor.The start address of the endpoint buffer must be sixteen bytes
aligned in USB RAM. As for the space in USB RAM that is not assigned, the firmware can use them
for another purpose.
The flowchart in Figure 3.10 shows the operation of BD registers used for in and out direction. In out
direction, after the data packet is received from the host, the TOKDNEF bit is set, and the CPU
becomes the control of the BD and endpoint buffer (OWN = 0). Firmware can deal with this in an
interrupt service routine or in a polling routine. The program reads the length of the received data
from the BC register and then reads out the data from the endpoint buffer and processes it if necessary.
After that, firmware updates the BD register and hands over the control to SIE for next transaction.
Before the first packet is received, the firmware initializes the associated BD registers and hands over
the control to SIE. Then the USB module is ready to receive data from the host.
In in direction of control transfer, the USB device receives one data packet that includes one
request or command, then the device begins to prepare the data to be delivered to the host according
to some protocols. The firmware writes the data length to the BC register, writes the data to the
endpoint data buffer, then updates the status and control the register (DATA0/1, OWN, etc.). After
that, the USB module begins to wait for the host to read data (in operation).

Figure 3.10 BDT Opearation Example


The TOKDNEF bit is set after the host finishes reading out the data in the endpoint
(the transaction has finished). The USB interrupt is triggered if it is enabled. The new data for the next
transaction can be prepared in an interrupt service routine or in a polling routine.

4 USB Device Development


4.1 Hardware Design
Hardware design for USB device with MC9S08JM60 is simple and flexible. The designer can
choose to use the on-chip regulator or external power supply and to use the internal pullup or external
pullup resistor. You can use the internal pullup or external pullup resistor. The MCU provides many
interfaces such as SPI, SCI, IIC, ADC, KBI, etc. The designers thus have more selections in design.
The hardware design of the USB interface is discussed in the following sections.
4.1.1 Clocking Generation
USB module requires two clock sources. They are the 24 MHz bus clock and 48 MHz
reference clock. According to the MCG features, the MCG must work in PEE mode (PLL engaged
external) and an external clock source is essential for matching this requirement. An oscillator or
crystal is used as the external clock source.
4.1.2 USB Device Power

Figure 4.1 USB Connection


The dedicated on-chip regulator powers the USB transceiver. It shares the same power supply
with MCU. The on-chip regulator is enabled or disabled by the USBVREN bit in the USBCTL0
register. When the on-chip regulator is disabled (USBVREN = 0), one external 3.3 V power is
connected to V USB 3.3 pin to provide the power for USB transceiver and pullup resistor.

The nominal input range of this regulator is from 3.9 V to 5.5 V, but the MCU works at lower
voltage (2.7 V 5.5 V). When the power supply for MCU is below 3.9 V, an external power supply
must be provided for the USB module and the internal regulator must be disabled.
In addition, it is highly recommended that two capacitors are connected to the V USB 3.3 pin
to decrease the ripple on the output of the regulator. Their recommended values are 0.47 F, and 4.7
F. (refer to Figure 10), and they must be placed to the V USB 3.3 pin as near as possible.
USB devices have two power modes self-powered and the bus-powered. Refer to the USB
specification for detailed information. The design for two different power modes differ.
Bus-Powered
Bus-powered USB devices are powered from the USB bus. The maximum current drawn from
the host is 500 mA. The USB device is powered when it is attached to USB bus and the connection is
valid, then the host will find it attached.
Self-Powered
The self-powered USB device uses an individual power supply to provide the current for all
components, so that its power consumption is limited by the capability of external power supply. The
USB device whose current consumption is more than 500 mA must adopt self-powered mode.
In self-powered applications, the MCU works without the USB connection. The firmware has
the capability to know the status of USB connection (attached or not) for switching its state machine
correctly. One GPIO pin or KBI pin is recommended to help detect the USB power; then the firmware
determines the connection status.
In addition, connect the ferrite bead in series between the power (or ground) of the host and
USB device to help to absorb the high frequency noise coupled in the power system (decrease
electromagnetic interference). The ferrite bead is similar to a high permeability inductance wherein
the high frequency impedance attenuates the high-frequency current, and the DC current passes freely.
4.1.3 Pullup Resistor
USB host uses the pullup resistor to detect the connection of the USB device and identifies the
devices speed (low, full, high). The USB module of MC9S08JM60 choose the use of an internal or
external pullup resistor. The internal pullup resistor is enabled by the USBPU bit of the USBCTL0
register.When the internal pullup resistor is disabled, one 1.5 k pullup resistor can be connected
between the V USB 3.3 pin and the USBDP pin.

NOTE
The USB device can use internal pullup resistor or external pullup resistor, but only one pullup
resistor is allowed to be connected.
Table 4.1 lists all the combinations USB regulator and pullup resistor. The designers can select
one of the combinations according to actual requirement.

Table 4.1 USB regulaor and pullup resistor configuration


4.2
4.2.1

USB Firmware Design


USB Communication Model
On the high layer of the USB data flow model, the USB pipe is built for communication

between the USB device and the host. A USB pipe is an association between an endpoint on a device
and software on the host. Pipes represent the ability to move data between software on the host via a
memory buffer and an endpoint on a device.
USB devices must build at least one control pipe to the host. The control pipe (also called
default control pipe) is essential for all USB devices. It is based on endpoint 0, uses control transfer
type, and supports bidirectional data communication. The other pipes can be designed in terms of the
applications requirements. There are seven pipes available (seven endpoints) for MC9S08JM60 to
support control, bulk, interrupt, or isochronous transfer.
The default control pipe is used by the USB system software to determine device identification
and configuration requirements and to configure the device. The default control pipe can also be used
by device-specific software after the device is configured. The USB enumeration and configuration is
the first step to design the firmware of a USB device.
The USB communication consists of transfers. The USB transfer comprises one or more
transactions, and each transaction includes several packets. For MC9S08JM60 USB devices, the
firmware immediately needs to do little work. One transaction is completed by the USB module
automatically. The programer can ignore work related to low level USB protocol, such as CRC
calculation, building packet and handshake. The programer can spend more effort on high-level

protocol and data process.


The firmware design of USB device with MC9S08JM60 is discussed in the following
sections.Detailed information about enumeration and configuration has also been covered.
4.2.2

Main Firmware Structure

Figure 4.2 Example of the Main Function and USB Module Initilialization
Figure 4.2 shows two flow charts of a USB firmware example designed with MC9S08JM60
device. One is the main routine, and the other is the USB module initialization. After the MCU is
powered on the firmware performs system initialization. All modules used in application are
initialized one by one.
The firmware can complete the USB module initialization by following the steps in Figure 11.
It initializes the USB BDT according to the USB RAM assignment, then initializes the USB registers,
and sets the USB state to ATTACHED at last.
To set the USB registers, it configures the USB module (pullup resistor, USB regulator in
terms of the hardware design) first, then enables the EP0 and the USB interrupt. For self-powered
devices, the USB module can be enabled when MCU detects the USB bus power, and the USB device
initial state is POWERED.
NOTE
The EPCTL0 must be set to 0x0D for control transfer on endpoint 0 before the enumeration
starts.In the main loop of firmware, the program checks the USB status changes, e.g., attached or
detached to USB bus. The other customize tasks are also located in main loop. The firmware can use
the polling or interrupt method to deal with USB events. With the polling method, all USB status bits
in the INTSTAT register are checked, the program will jump to associated service routine if the flag
bits are set. The USB interrupt must be enabled before entering suspend mode if the MCU needs to
work in stop3 mode.

If the polling method is not adopted, the interrupt method is a good choice. All events involved
in the USB communication can be processed in real-time by the USB interrupt service routine, and all
unnecessary polling for the status flag bits when no USB events occurred are avoided.
Figure 4.3 is an example of USB interrupt service routine (ISR). The USB interrupt flags in
the INTSTAT register are checked one by one. When one USB event occurs, the associated interrupt
flag is set, then the program will process these events in ISR if this interrupt is enabled. The program
will check the next interrupt flag.

Figure 4.3 Example of USB interrupt service routine


When the USB device is in suspend mode, the resume interrupt flag and the resume interrupt
processing differ according to the work mode of MCU (stop3 or user mode). The LPRESF bit in the

USBCTL0 register is set for resuming from stop3 mode, and the RESUMEF bit in the INTSTAT
register is set for resuming from the user mode. The processing is listed in Figure 4.3. The designer
can select from these two ways. This is the reason why the processing for RESUMEF is marked with
dotted line. The RESET bit is set when the host sends a reset signal to the device. The program for
processing a RESET must stop all USB involved processes immediately, reset the USB registers (e.g,
ADDR=0), and return to the state before enumeration begins. The TOKDNEF bit is set when one
transaction is complete. The processing of TOKDNEF is the main entry for all transactions.The
interrupt flag must be cleared after it is serviced. Otherwise the interrupt is executed again and again,
without stopping.
4.2.3

USB State Machine

USB device has the following states:


Powered: USB device is not attached to the USB bus, but the MCU has been powered on.
Attached: USB device is attached to the USB bus, but enumeration has not started
Default: USB device is reset by the host
ADDR_PENDING: USB device receives the Set_Address command from the host

Figure 4.4 USB Device State Transfer


Addressed: The Set-Address command has executed successfully.

Configured: The USB device receives and executes the Set_Configuration command successfully.
Suspend: The USB device enters suspend mode.
Figure 4.4 shows the switches of the USB state machine. The suspend and reset mode can be
entered from all states except the powered state.
The bus-powered USB device sets its state to attached directly after it is attached to the USB
bus.The state of ADDR_PENDING is set when USB device receives the Set_Address setup token. It
is changed to ADDRESSED when the Set_Address transfer has finished. After the USB device is
attached to the USB bus, the host starts the enumeration process, the USB device state changes to
configured from attached if the enumeration process succeeds.
4.2.4 USB Device Enumeration Process
In the enumeration process, the host performs the identification and configuration for the USB
device. The following process is an example for enumeration between a USB device and computer
with Windows XP operating system installed.
1. The host detects the connection of a new device via the devices pullup resistors on the data
pair. The host waits for at least 100 ms, allowing for the plug to be inserted fully and for power
to be stable on the device.
2. Host issues a reset to make the device in default state.
3. The MS Windows host asks for the first 64 bytes of the device descriptor.
4. After receiving the first eight bytes of the device descriptor, host immediately issues another
bus reset.
5. The host now issues a Set_Address command to place the device in the addressed state.
6. The host asks for the entire 18 bytes of the device descriptor.
7. The host then asks for nine bytes of the configuration descriptor to determine the overall size.
8. The host asks for 256 bytes of the configuration descriptor.
9. Host asks for any string descriptors specified.
10. Windows will ask for a driver for device. It may request all the descriptors again before it
issues a Set configuration request.
11. Host sets the configuration of device. The USB device state changes to configured.

The enumeration process is similar for all USB devices. The host fetches a lot of descriptors
from the device, such as the devices descriptor, configuration descriptor, interfaces descriptors,
endpoint descriptors, and string descriptors. According to the information in these descriptors, the
operating system finds the driver for the USB device, and the driver sets the configuration of device at
last.
The enumeration process is carried on the endpoint 0, which the default control pipe is built in.
The control transfers constitute the enumeration process, so the program about control transfer is the
most important part for USB stack.
The implementation for control transfer on endpoint 0 has been described in the sections that
follow. The setting for the BD registers and the endpoint buffer is also involved.

4.3 USB Firamware


/*******************************************************************************
* Project name : Implementaion of USB Interface using Micro Controller
*
* Created by : V. Rama Vara Prasad
*
* Compiler
: CodeWarrior V6.1 for HC(S)08
*
*******************************************************************************/
void main(void)
{
/* System Initalization */
Init_Sys();
/* Enable Interrupts Macro */
EnableInterrupts;
for(;;)
{
Check_USBBus_Status();
}
}
/*******************************************************************************
* Function : Init_Sys
*
* Description : Initialize the system
*
*******************************************************************************/
void Init_Sys(void)
{
Mcu_Init();
/* MCU general Initialization */
MCG_Init();

/* Initialize the MCG module to generate 24MHz bus clock */

Initialize_USBModule(); /* Initialize USB Module */


}
/*****************************************************************************
* Function : MCU_Init
*
* Description : Initialization of the MCU.
*
****************************************************************************/
void Mcu_Init()
{
SOPT1= SOPT1_STOPE_MASK;
SPMSC1=SPMSC1_LVWACK_MASK;
}

/*****************************************************************************
* Function
: MCG_Init
*
* Description : Initialization of the MCG.
*
*
****************************************************************************/
void MCG_Init()
{
/* The MCG is default set to FEI mode, it should be change to FBE mode*/
MCGC2=MCGC2_RANGE_MASK|MCGC2_HGO_MASK|
MCGC2_EREFS_MASK|MCGC2_ERCLKEN_MASK;
while(!MCGSC_OSCINIT);
MCGC1= MCGC1_CLKS1_MASK | MCGC1_RDIV1_MASK |
MCGC1_RDIV0_MASK | MCGC1_IRCLKEN_MASK |
MCGC1_IREFSTEN_MASK;
while((MCGSC & 0x1C ) != 0x08); /* check the external reference clock is selected or
not*/
/* Switch to PBE mode from FBE */
MCGC3=MCGC3_PLLS_MASK | MCGC3_VDIV3_MASK;
while ((MCGSC & 0x48) != 0x48);

// wait for the PLL is locked

/* Switch to PEE mode from PBE mode */


MCGC1&= MCGC1_RDIV2_MASK | MCGC1_RDIV1_MASK |
MCGC1_RDIV0_MASK | MCGC1_IREFS_MASK |
MCGC1_IRCLKEN_MASK | MCGC1_IREFSTEN_MASK;
while((MCGSC & 0x6C) != 0x6C);
}
/******************************************************************************
* Function : void Initialize_USBModule(void)
* Description: Initialize the USB module enable regulator, PHY, pull-up resistor, BDT
*

initialization

*****************************************************************************/
void Initialize_USBModule()
{
Usb_Device_State = POWERED_STATE;
#ifdef SELF_POWER
Usb_Stat._byte = 0x01;

/*SelfPower*/

#else
Usb_Stat._byte = 0x00;

/*Notice: Bus powered*/

#endif
Usb_Active_Cfg = 0x00;
USBCTL0 = USB_RST;
while(USBCTL0_USBRESET) {

};

/*Below is initialization the BDT*/


Bdtmap.ep0Bo.Stat._byte = _SIE|_DATA0|_DTS; /* endpoint 0 OUT initialization*/
Bdtmap.ep0Bo.Cnt = EP0_BUFF_SIZE;
Bdtmap.ep0Bo.Addr = 0x0C; //((byte)(((byte*) &Setup_Pkt)-0x1860) )>> 2; //can
calculate this value
Bdtmap.ep0Bi.Stat._byte = _CPU; /* endpoint 0 IN buffer initialization*/
Bdtmap.ep0Bi.Cnt = 0x00;
Bdtmap.ep0Bi.Addr = 0x08;
USBCTL0 = 0x00;
EPCTL0 = 0x0D;

/*enable endpoint 0*/

INTENB = 0x01;
}
/******************************************************************************
* Function :
void Check_USBBus_Status(void)
*
* Overview :
This function can be used to detect if the USB bus has attached on USB
bus, we can use a GPIO.
*****************************************************************************/
void Check_USBBus_Status(void)
{
#ifdef SELF_POWER
if(PTGD_PTGD0 == USB_BUS_ATTACHED)

/* Is JM60 attached on USB bus? */

{
#endif
if(CTL_USBEN == 0)

/* JM60 module off ? */

{
EPCTL0 = 0x0D;
INTSTAT = 0xBF;
CTL = 0x00;
INTENB = 0x00;

/* disable USB interrupt*/

CTL_USBEN = 0x01;

/* enable module */

USBCTL0 = UCFG_VAL;

/* attach JM60 to USB bus*/

Usb_Device_State = ATTACHED_STATE;

}
#ifdef SELF_POEWER
}
else
{
if(CTL_USBEN == 1)

/* JM60 USB on ?*/

{
CTL = 0x00;

/* disable module */

INTENB = 0x00;

/* mask USB interrupt*/

Usb_Device_State = POWERED_STATE;
}
}
#endif
if(Usb_Device_State == ATTACHED_STATE)
{
INTSTAT = 0xBF;

/*clear USB interrupts*/

INTENB = 0xBF;
}
if(Usb_Device_State == USB_ENTER_SUSPEND)
{
USB_Suspend();
}
}
/******************************************************************************
* Function :
void USB_Soft_Detach(void)
*
* Overview :
USB_Soft_Detach disconnects the device from USB bus.
*

This is done by stop supplying Vusb voltage to pull-up resistor. The pulldown resistors on the host side will pull both differential signal lines low
and the host registers the event as a disconnect.
Since the USB cable is not physically disconnected, the power supply
through the cable can still be sensed by the device. The next time
Check_USBBus_Status() function is called, it will reconnect the device back
to the bus.

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

void USB_Soft_Detach(void)
{
CTL = 0x00;
/* disable module */
INTENB = 0x00;
/* mask USB interrupt*/
Usb_Device_State = POWERED_STATE;
return;
}
/******************************************************************************
* Function
:
void USB_Suspend(void)
*
* Overview
:
After 3ms of USB bus idle status, the SLEEPF will be set,The firmware
should enable the resume function in 7ms before the USB enters into
suspend state.
*****************************************************************************/
void USB_Suspend(void)
{
unsigned char Result;
//INTENB_RESUME = 1;
USBCTL0_USBRESMEN = 1;
INTSTAT_SLEEPF = 1;
//RTC_DISBALE();
Usb_Device_State = USB_SUSPEND;
do
{
Result = USB_WakeUp() ;
}while(!Result);
USBCTL0_USBRESMEN = 0;
if(Result == 2)
USB_Remote_Wakeup();
return;
}
/******************************************************************************
* Function :
void USB_WakeFrom_Suspend(void)
* Input

None

* Output

None

*****************************************************************************/
void USB_WakeFrom_Suspend(void)
{
INTSTAT_RESUMEF = 1; /*write 1 to clear*/
INTENB_RESUME = 0;
CTL_TSUSPEND = 0;
/*enable the transmit or receive of packet */
}

/******************************************************************************
* Function
:
void USB_Remote_Wakeup(void)
* Overview

This function is used to send wake-up signal from device to host or hub

* Note

According to USB 2.0 specification section 7.1.7.7, "The remote wakeup


device must hold the resume signaling for at lest 1 ms but for no more
than 15 ms."

*****************************************************************************/
void USB_Remote_Wakeup(void)
{
static word delay_count;
USB_WakeFrom_Suspend();
CTL_CRESUME = 1;
delay_count = 8000;
do
{

/* Start RESUME signaling*/


/* Set RESUME line for 1-15 ms*/

delay_count--;
__RESET_WATCHDOG();
}while(delay_count);
CTL_CRESUME = 0;
}
/******************************************************************************
* Function :
void USB_SOF_Handler(void)
* Overview

The USB host sends out a SOF packet to full-speed devices every 1 ms.
This interrupt may be useful for isochronous pipes.

*****************************************************************************/
void USB_SOF_Handler(void)
{
/*can add some code if isochronous transfer*/
INTSTAT_SOFTOKF = 1; /*clear the interrupt flag*/
}

/******************************************************************************
* Function :
void USB_Stall_Handler(void)
* Overview

The STALLIF is set anytime the SIE sends out a STALL packet regardless
of which endpoint causes it. A Setup transaction overrides the STALL
function. A stalled endpoint stops stalling once it receives a setup packet.
There are a few reasons for an endpoint to be stalled.
1. When a non-supported USB request is received.
Example: GET_DESCRIPTOR(DEVICE_QUALIFIER)
2. When an endpoint is currently halted.
3. When the device class specifies that an endpoint must stall in response to
a specific event.

*****************************************************************************/
void USB_Stall_Handler(void)
{
if((STAT & 0xF0)== 0x00)
{
if(EPCTL0_EPSTALL == 1)
EPCTL0_EPSTALL = 0;
/*Notice if is generated by BDTSTALL, the firmware should notice the IN or OUT DIR*/
/*we only set it for OUT direction in this demo*/
USB_Prepare_Next_Trf();
}
/*
else
{
//Add the process for STALL generated by other endpoints (even or odd)
}
*/
INTSTAT_STALLF = 1;
}
/******************************************************************************
* Function
:
void USB_Error_Handler(void)
* Overview

You can check error register to see which error occured

*****************************************************************************/
void USB_Error_Handler(void)
{
INTSTAT_ERRORF = 1;
/*add code to check the error source */
if((ERRSTAT_BUFERRF) && ((STAT & 0xF0)==0)) /*Bdt buffer overflow*/
{
USB_Prepare_Next_Trf();
}

/*check the other error at here */


ERRSTAT = 0xBF; /*clear all errors*/
return;
}
/******************************************************************************
* Function:
void USB_Bus_Reset_Handler(void)
*
* Overview: Once a USB bus reset is received from the host, this function should be
called. It resets the device address to zero, disables all non-EP0 endpoints,
initializes EP0 to be ready for default communication, clears all USB interrupt
flags, unmasks applicable USB interrupts, and reinitializes internal statemachine.
*****************************************************************************/
void USB_Bus_Reset_Handler(void)
{
ERRSTAT = 0xFF;
/* clear USB error flag*/
INTSTAT = 0xBF;

/* clear USB interrupt*/

ERRENB = 0xBF;

/* disable all USB error interrupt sources*/

INTENB = 0x9F;

/* enable all interrupts except RESUME*/

ADDR = 0x00;

/* reset to default address*/

Clear_Mem((byte*)&EPCTL1,6); /* disable all endpoints */


EPCTL0 = EP_CTRL|HSHK_EN; /* enable endpoint 0*/
while(INTSTAT_TOKDNEF )

/* Flush any pending transactions because 4 status buffer*/

INTSTAT = 0xBF;
USB_Prepare_Next_Trf();

/*prepare to receive the setup packet*/

Usb_Stat.BitCtl.RemoteWakeup = 0;

/* default status flag to disable*/

Usb_Active_Cfg = 0;
Usb_Device_State = DEFAULT_STATE;
}
/******************************************************************************
* Function
:
void USB_Buf_Rdy(buffer_dsc)
*
* PreCondition :
IN endpoint: Buffer is control by MCU.OUT endpoint: Buffer is
conrolled by SIE.
* Input

byte buffer_dsc: one buffer descriptor in Bdtmap

* Overview

This function turns the buffer ownership to SIE,and toggles the DTS
bit for synchronization.

* Note

This function should not be called by Endpoint 5 or 6 because they are


pingpong buffer, DATA0/1 do not need to be switched

*****************************************************************************/
void USB_Buf_Rdy(BUFF_DSC *buffer_dsc)
{
buffer_dsc->Stat._byte &= _DATA1;
buffer_dsc->Stat.McuCtlBit.DATA = ~ buffer_dsc->Stat.McuCtlBit.DATA; /* Toggle DTS
bit*/
buffer_dsc->Stat._byte |= _SIE|_DTS;

/*give the ownership to SIE*/

}
/******************************************************************************
* Function
:
void Clear_Mem(byte* startAdr,byte count)
*****************************************************************************/
void Clear_Mem(byte* startAdr,byte count)
{
byte i;
for(i=0; i < count; i++)
{
*(startAdr + i) = 0x00;
}
return;
}
/******************************************************************************
* Function
:
void interrupt USB_ISR()
* Overview

The USB stat interrupt service routine

*****************************************************************************/
void interrupt 7 USB_ISR()
{
if((USBCTL0_LPRESF) && (Usb_Device_State == USB_SUSPEND))
{
USBCTL0_USBRESMEN = 0;
}
if(INTSTAT_RESUMEF && INTENB_RESUME)
USB_WakeFrom_Suspend();
if(INTSTAT_USBRSTF && INTENB_USBRST)
{
USB_Bus_Reset_Handler();
}

if(INTSTAT_SOFTOKF && INTENB_SOFTOK)


{
USB_SOF_Handler();
}
if(INTSTAT_STALLF && INTENB_STALL )
USB_Stall_Handler();
if(INTSTAT_ERRORF && INTENB_ERROR)
USB_Error_Handler();
if((INTSTAT_SLEEPF && INTENB_SLEEP)&&(Usb_Device_State >=
CONFIGURED_STATE))
{
Usb_Device_State = USB_ENTER_SUSPEND; /*do not hope enter into suspend */
INTSTAT_SLEEPF = 1;
}
if(INTSTAT_TOKDNEF && INTENB_TOKDNE)
{
USB_Transaction_Handler();
INTSTAT_TOKDNEF = 1;

/*write 1 to clear*/

}
return;
}
/******************************************************************************
* Function :
void interrupt IRQ_ISR()
* Overview

The IRQ is used to wakup the USB and MCU.

*****************************************************************************/
void interrupt 2 IRQ_ISR()
{
IRQSC_IRQACK = 1;
return;
}
/******************************************************************************
* Function
:
unsigned char USB_WakeUp()
* Output

0: noise, re-entern into sleep

1: Bus wake-up

2: remote wake up

* Overview

The USB sleep and wake up

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

unsigned char USB_WakeUp(void )


{
int delay_count;
asm STOP;

/*MCU enter into stop3*/

Usb_Device_State = CONFIGURED_STATE;
if((! USBCTL0_LPRESF) /*&& (Kbi_Stat)*/) /*Is the KBI interrupt bring the MCU out of
STOP3*/
{
if(Usb_Stat.BitCtl.RemoteWakeup == 1) /*Is remote wakeup supported*/
return 2;

/*will enable remote wakeup*/

else
return 0;
}
else
{
delay_count = 50;
do
{
delay_count--;

/*tell MCU it should enter STOP3 again*/


/*add delay to filter the noise */

__RESET_WATCHDOG();
}while(delay_count);
if(INTSTAT_RESUMEF)

/*The resume signal has engouh time to set


RESUMEF bit*/

{
return 1;
}
else
return 0;

/*USB resume*/

/*resume is caused by noise*/

}
}
/********************************************************************
* Function
:
void USB_CtrlEP_Handler(void)
* Overview
:
process the transaction from different endpoint
********************************************************************/
void USB_Transaction_Handler(void)
{
unsigned char stat = STAT;
if((stat & 0xF0 ) == 0x00)
{
stat &= 0xF8;

if(stat == EP00_OUT)
{
if(Bdtmap.ep0Bo.Stat.RecPid.PID == SETUP_TOKEN)
USB_CtrlTrf_SetupStage_Processing();
else
USB_CtrlTrf_Out_Handler();
}
else
{
if(stat == EP00_IN)
USB_CtrlTrf_In_Handler();
}
}
else
{
if(stat & 0x08)
asm(nop);
else

// OUT handler

EndPoint_OUT((stat & 0xF0)>>4);


}
}
/********************************************************************
* Function
:
void USB_CtrlTrf_Out_Handler(void)
* Overview
*

This function handles an OUT transaction according to


which control transfer state is currently active.

********************************************************************/
void USB_CtrlTrf_Out_Handler(void)
{
if(Ctrl_Trf_State == CTL_TRF_DATA_RX)
USB_CtrlTrf_RxData();

/*Data stage*/

else
USB_Prepare_Next_Trf();
return;
}

/*Current transfer completes*/

/********************************************************************
* Function
:
void USB_CtrlTrf_RxData(void)
********************************************************************/
void USB_CtrlTrf_RxData(void)
{
int Byte_Num;
Byte_Num = (int)Bdtmap.ep0Bo.Cnt;
Transfer_Cnt = Transfer_Cnt + Byte_Num;
pSrc = (byte*)&CtrlTrf_Data;
while(Byte_Num)
{
*pObj = *pSrc; /*Please init the pObj when receiving data in enumeration process*/
pObj++;
pSrc++;
Byte_Num--;
}
if(Bdtmap.ep0Bo.Stat.McuCtlBit.DTS == 0)
Bdtmap.ep0Bo.Stat._byte = _SIE|_DATA1|_DTS;
else
Bdtmap.ep0Bo.Stat._byte = _SIE|_DATA0|_DTS;
return;
}
/********************************************************************
* Function
:
void USB_CtrlTrf_In_Handler(void)
* Overview

This function handles an IN transaction according to which


controls transfer state is currently active. It will check if it is the
set-address transaction

********************************************************************/
void USB_CtrlTrf_In_Handler(void)
{
if(Usb_Device_State == ADDR_PENDING_STATE)
{
ADDR = Setup_Pkt.CtlAdd.bDevADR._byte;
if(ADDR > 0x00)
Usb_Device_State = ADDRESS_STATE;
else
Usb_Device_State = DEFAULT_STATE;
}
if(Ctrl_Trf_State == CTL_TRF_DATA_TX)

USB_CtrlTrf_TxData();
else
USB_Prepare_Next_Trf();
return;
}
/********************************************************************
* Function
:
void USB_CtrlTrf_TxData(void)
********************************************************************/
void USB_CtrlTrf_TxData(void)
{
int Byte_To_Send;
if(Transfer_Cnt < EP0_BUFF_SIZE)
Byte_To_Send = Transfer_Cnt;
else
Byte_To_Send = EP0_BUFF_SIZE;
Bdtmap.ep0Bi.Cnt = (byte)(Byte_To_Send);
Transfer_Cnt = Transfer_Cnt - Byte_To_Send;
pObj = (byte*)&CtrlTrf_Data;
while(Byte_To_Send)
{
*pObj = *pSrc;
pObj++;
pSrc++;
Byte_To_Send--;
}
if(Ctrl_Trf_State == CTL_TRF_DATA_TX)
{
if(Bdtmap.ep0Bi.Stat.McuCtlBit.DATA == 0)
Bdtmap.ep0Bi.Stat._byte = _SIE|_DATA1|_DTS;
else
Bdtmap.ep0Bi.Stat._byte = _SIE|_DATA0|_DTS;
}
return;
}

/********************************************************************
* Function
:
void USB_CtrlTrf_SetupStage_Processing(void)
*
* Overview
:
This function has 3 steps
*

1. init the control transfer state machine.

2. calls on each of the module that may know how to

service the Setup Request from the host.

3. once each of the modules has a chance to check if

it is responsible for servicing the request then checks direction of


the transfer to determine how to prepare EP0 for control transfer.

********************************************************************/
void USB_CtrlTrf_SetupStage_Processing(void)
{
Transfer_Cnt = 0;
Ctrl_Trf_State = WAIT_SETUP_TOKEN;
Ctrl_Trf_Session_Owner = CLASS_NULL;
USB_StdReq_Handler();
/*if(Ctrl_Trf_Session_Owner == CLASS_NULL)*/
/*USB_ClassReq_Handler();*/

/*if it is not USB standard request*/


/*verify if it is class request*/

USB_CtrlEP_SetupStage_Complete();
return;
}
/********************************************************************
* Function
:
void USB_CtrlEP_SetupStage_Complete(void)
* Overview

This function wrap up the ramaining tasks in servicing

a Setup Request. Its main task is to set the endpoint

controls appropriately for a given situation.

********************************************************************/
void USB_CtrlEP_SetupStage_Complete(void)
{
int Tmp;
if(Ctrl_Trf_Session_Owner == CLASS_NULL)
{
Bdtmap.ep0Bo.Cnt = EP0_BUFF_SIZE;
Bdtmap.ep0Bo.Addr = 0x0C; /*can calculate the address according the offset in
Bdtmap*/

/*We can set the EPSTALL bit in EPCTL or the STALL bit in BDT register*/
/*EPCTL0_EPSTALL = 1;*/
Bdtmap.ep0Bo.Stat._byte = _SIE|_BDTSTALL;
Bdtmap.ep0Bi.Stat._byte = _SIE|_BDTSTALL;
}
else
{
if(Setup_Pkt.CtlReqT.DataDir == DEV_TO_HOST)
{
Tmp = ((LSB(Setup_Pkt.CtlPara.W_Length)<<8) |
(MSB(Setup_Pkt.CtlPara.W_Length))); //adjust endian
if(Tmp < Transfer_Cnt)
Transfer_Cnt = Tmp;
USB_CtrlTrf_TxData();
Ctrl_Trf_State = CTL_TRF_DATA_TX;
Bdtmap.ep0Bo.Cnt = EP0_BUFF_SIZE;
Bdtmap.ep0Bo.Addr = 0x0C;

/*can calculate the addree according the offset in

Bdtmap*/
Bdtmap.ep0Bo.Stat._byte = _SIE;
Bdtmap.ep0Bi.Addr = 0x08;

/*can calculate the addree according the offset in

Bdtmap*/
Bdtmap.ep0Bi.Stat._byte = _SIE|_DATA1|_DTS;
}
else
{
Ctrl_Trf_State = CTL_TRF_DATA_RX;
Bdtmap.ep0Bi.Cnt = 0;
Bdtmap.ep0Bi.Addr = 0x08;

/*can calculate the addree according the offset in

Bdtmap*/
Bdtmap.ep0Bi.Stat._byte = _SIE|_DATA1|_DTS;
Bdtmap.ep0Bo.Cnt = EP0_BUFF_SIZE;

Bdtmap.ep0Bo.Addr = 0x0C;

/*can calculate the addree according the offset in

Bdtmap*/
Bdtmap.ep0Bo.Stat._byte = _SIE|_DATA1|_DTS;
}
}
CTL_TSUSPEND = 0;
return;
}
/********************************************************************
* Function
:
void USB_Prepare_Next_Trf(void)
* Overview

The routine forces endpoint 0 OUT to be ready for a new


Setup transaction, and forces endpoint0 IN to be owned by
MCU

********************************************************************/
void USB_Prepare_Next_Trf(void)
{
Bdtmap.ep0Bo.Cnt = EP0_BUFF_SIZE;
Bdtmap.ep0Bo.Addr = 0x0C;

//((byte)(((byte*) &Setup_Pkt)-0x1880) >> 2 ); //

Bdtmap.ep0Bo.Stat._byte = _SIE|_DATA0|_DTS;
Bdtmap.ep0Bi.Stat._byte = _CPU;
CTL_TSUSPEND = 0;
Ctrl_Trf_State = WAIT_SETUP_TOKEN;
return;
}
/********************************************************************
* Function

void USB_StdReq_Handler(void)

* Overview

This function checks the setup data packet to see if it

knows how to handle it

********************************************************************/
void USB_StdReq_Handler(void)
{
if(Setup_Pkt.CtlReqT.RequestType != STANDARD)
return;
switch(Setup_Pkt.StdCtl.bRequest)
{
case GET_DSC:
USB_StdGetDsc_Handler();

break;
case SET_CFG:
USB_StdSetCfg_Handler();
break;
case SET_ADR:
Usb_Device_State = ADDR_PENDING_STATE;
Ctrl_Trf_Session_Owner = STANDARD_CLASS_ID;
break;
case GET_CFG:
pSrc = (byte*)&Usb_Active_Cfg;
Transfer_Cnt = 1;
Ctrl_Trf_Session_Owner = STANDARD_CLASS_ID;
break;
case GET_STATUS:
USB_StdGetStatus_Handler();
break;
case CLR_FEATURE:
case SET_FEATURE:
USB_StdFeatureReq_Handler();
break;
case GET_INTF:

/*Notice when the Setup_Pkt.bIntfId > 1*/

if(Setup_Pkt.CtlIntf.bIntfID < MAX_NUM_INTF)


{
pSrc = (byte*)&Usb_Alt_Intf + Setup_Pkt.CtlIntf.bIntfID;
Transfer_Cnt = 1;
Ctrl_Trf_Session_Owner = STANDARD_CLASS_ID;
}
/*
else
{
//add code for more than 1 interface, notice the value of MAX_NUM_INTF

}
*/
break;
case SET_INTF:
Usb_Alt_Intf[Setup_Pkt.CtlIntf.bIntfID] = Setup_Pkt.CtlIntf.bAltID;
Ctrl_Trf_Session_Owner = STANDARD_CLASS_ID;
break;
case SET_DSC:
case SYNCH_FRAME:
default:
break;
}
return;
}
/********************************************************************
* Function
:
void USB_ClassReq_Handler(void)
* Overview
*

The routine will be called when the request in setup packet


an not be parsed. It will call the routines in
Std_Class_Req_Handler,

The new routine for new class can be added to this array
when new standard class is required. The user can also add
its owner processing for customize protocol.

********************************************************************/
void USB_ClassReq_Handler(void)
{
byte i;
for(i=0;i < (sizeof(Class_Req_Handler)/sizeof(pFunc)); i++)
{
if(Ctrl_Trf_Session_Owner != CLASS_NULL) //if the request has been parsed, return
return;
if(Class_Req_Handler[i])
Class_Req_Handler[i]();
}
return;
}

//if the routine is valid, then call

/********************************************************************
* Function
:
void USB_StdGetDsc_Handler(void)
* Overview

This function handles the standard GET_DESCRIPTOR


request.

*******************************************************************/
void USB_StdGetDsc_Handler(void)
{
if(Setup_Pkt.StdCtl.bmRequestType == 0x80)
{
switch(Setup_Pkt.ReqWval.bDscType)
{
case DSC_DEV:
Transfer_Cnt = sizeof(Device_Dsc);
pSrc = (byte*)&Device_Dsc;
Ctrl_Trf_Session_Owner = STANDARD_CLASS_ID;
break;
case DSC_CFG:
Transfer_Cnt = sizeof(USB_CFG);
pSrc = Cfg_Des[Setup_Pkt.ReqWval.bDscIndex];
Ctrl_Trf_Session_Owner = STANDARD_CLASS_ID;
break;
case DSC_STR:
Transfer_Cnt = *pSrc;
pSrc = Str_Des[Setup_Pkt.ReqWval.bDscIndex];
Ctrl_Trf_Session_Owner = STANDARD_CLASS_ID;
break;
default:
break;
}
}
return;
}
/********************************************************************
* Function
:
void USB_StdSetCfg_Handler(void)
* Overview
*

This function disables all endpoints except 0 by clearing


EPCTL registers, then initializes these endpoints

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

void USB_StdSetCfg_Handler(void)
{
Clear_Mem((byte*)&EPCTL1,6);
Clear_Mem((byte*)&Usb_Alt_Intf,MAX_NUM_INTF);
Usb_Active_Cfg = Setup_Pkt.CtrCfg.bCfgValue;
Ctrl_Trf_Session_Owner = STANDARD_CLASS_ID;
if(Setup_Pkt.CtrCfg.bCfgValue == 0)
Usb_Device_State = ADDRESS_STATE;
else
{
Usb_Device_State = CONFIGURED_STATE;
Endpoint_Init();
}
return;
}
/********************************************************************
* Function
:
void USB_StdGetStatus_Handler(void)
* Overview
:
This function handles the standard GET_STATUS request
********************************************************************/
void USB_StdGetStatus_Handler(void)
{
CtrlTrf_Data.EachByte._byte0 = 0;
CtrlTrf_Data.EachByte._byte1 = 0;
switch(Setup_Pkt.CtlReqT.Recipient)
{
case RCPT_DEV:
/* _byte0: bit0: Self-Powered Status [0] Bus-Powered [1] Self-Powered */
/*

bit1: RemoteWakeup

[0] Disabled

[1] Enabled

if(Usb_Stat.BitCtl.Self_Power)
CtrlTrf_Data.EachByte._byte0|=0b000000001;
if(Usb_Stat.BitCtl.RemoteWakeup == 1)
CtrlTrf_Data.EachByte._byte0|=0b00000010;

*/

Ctrl_Trf_Session_Owner = STANDARD_CLASS_ID;
break;
case RCPT_INTF:
Ctrl_Trf_Session_Owner = STANDARD_CLASS_ID;
break;
case RCPT_EP:
if((Setup_Pkt.EpND.EPNum == 0b0001 ) && (Setup_Pkt.EpND.EPDir))
{
if(Bdtmap.ep1Bio.Stat.McuCtlBit.BDTSTALL)
CtrlTrf_Data.EachByte._byte0 |= 0x01;
Ctrl_Trf_Session_Owner = STANDARD_CLASS_ID;
}
break;
default:
break;
}
if(Ctrl_Trf_Session_Owner == STANDARD_CLASS_ID)
{
Transfer_Cnt = 2;
pSrc = (byte*)&CtrlTrf_Data;
}
return;
}
/********************************************************************
* Function
:
void USB_StdFeatureReq_Handler(void)
* Overview

This function dealt with the standard SET & CLEAR

FEATURES requests
********************************************************************/
void USB_StdFeatureReq_Handler(void)
{
if((Setup_Pkt.CtlReqT.bFeature == DEVICE_REMOTE_WAKEUP)&&
(Setup_Pkt.CtlReqT.Recipient == RCPT_DEV))
{
if(Setup_Pkt.StdCtl.bRequest == SET_FEATURE)
Usb_Stat.BitCtl.RemoteWakeup = 1;

else
Usb_Stat.BitCtl.RemoteWakeup = 0;
Ctrl_Trf_Session_Owner = STANDARD_CLASS_ID;
}
if((Setup_Pkt.CtlReqT.bFeature == ENDPOINT_HALT)&&
(Setup_Pkt.CtlReqT.Recipient == RCPT_EP)&&
(Setup_Pkt.EpND.EPNum != 0))
{
if(Setup_Pkt.EpND.EPNum == 0b0001)
{
if(Setup_Pkt.StdCtl.bRequest == SET_FEATURE)
{
if(Setup_Pkt.EpND.EPDir)
{
Bdtmap.ep1Bio.Stat.McuCtlBit.BDTSTALL = 1;
}
}
else
{
if(Setup_Pkt.EpND.EPDir)
{
Bdtmap.ep1Bio.Stat.McuCtlBit.BDTSTALL = 0;
}
}
Ctrl_Trf_Session_Owner = STANDARD_CLASS_ID;
}
}
return;
}

5.RESULTS
5.1 USB Device Real Hardware

USB
Connector

9S08
micro
controller

5.2 USB Device Power up through Bus Power

USB
Device
Power up
through
Bus Power
Indication

5.3 USB Device Detection by PC


Enemuration
and device
driver
installation
sucess
indication

TOOLS & COMPONETS


Tools:
CodeWarrior for Microcontrollers V6.1
Dev C++
Components:
9s08 Micro Controller
USB connector
USB cable

BIBLIOGRAPHY
Universal Serial Bus Specification revision 2.0 April 2000.
USB Complete: Everything You Need to Develop USB Peripherals, Third
Edition by Jan Axelson.
MC9S08JM16 Data Sheet.
Basics of SCSI(Small Computer System Interface).

You might also like