Sie sind auf Seite 1von 62

Chapter 1: Introduction to PSoC

• Introduction
• 1.1 System Overview
• 1.2 CPU
• 1.3 Frequency generator
• 1.4 Microcontroller power consumption
• 1.5 Reset
• 1.6 Digital inputs and outputs
• 1.7 Analog inputs and outputs
• 1.8 Accessing programmable digital blocks
• 1.9 Global input lines

• 1.10 Digital programmable blocks


• 1.11 Analog programmable blocks
• 1.12 Referent voltage generators
• 1.13 Switch mode pump
• 1.14 MAC
• 1.15 Decimator
• 1.16 I2C controller
• 1.17 Interrupt controller
• 1.18 Address space

Introduction
When developing more complex projects, there is often a need for additional
peripheral units, such as operational and instrument amplifiers, filters, timers, digital
logic circuits, AD and DA convertors, etc. As a general rule, implementation of the
extra peripherals brings in additional difficulties: new components take space, require
additional attention during production of a printed circuit board, increase power
consumption... All of these factors can significantly affect the price and development
cycle of the project.

The introduction of PSoC microcontrollers has made many engineers’ dream come
true of having all their project needs covered in one chip.

PSoC: Programmable System on Chip

PSoC (Programmable System on Chip) represents a whole new concept in


microcontroller development. In addition to all the standard elements of 8-bit
microcontrollers, PSoC chips feature digital and analog programmable blocks, which
themselves allow implementation of large number of peripherals.

Digital blocks consist of smaller programmable blocks that can be configured to allow
different development options. Analog blocks are used for development of analog

1
elements, such as analog filters, comparators, intrumentational (non–)inverting
amplifiers, as well as AD and DA convertors.

There’s a number of different PSoC families you can base your project upon,
depending on the project requirements. Basic difference between PSoC families is the
number of available programmable blocks and the number of input/output pins.

Number of components that can be devised is primarily a function of the available


programmable blocks. Depending on the microcontroller family, PSoC chips have 4–
16 digital blocks, and 3–12 analog programmable blocks.

Characteristics of PSoC microcontrollers

Some of the most prominent features of PSoC microcontrollers are:

• MAC unit, hardware 8x8 multiplication, with result stored in 32-bit


accumulator,
• Changeable working voltage, 3.3V or 5V,
• Possibility of small voltage supply, to 1V,
• Programmable frequency choice.

Programmable blocks allow you to devise:

• 16K bytes of programmable memory,


• 256 bytes of RAM,
• AD convertors with maximum resolution af 14 bits,
• DA convertors with maximum resolution of 9 bits,
• Programmable voltage amplifier,
• Programmable filters and comparators,
• Timers and counters of 8, 16, and 32 bits,
• Pseudorandom sequences and CRC code generators,
• Two Full-Duplex UART’s,
• Multiple SPI devices,
• Option for connection on all output pins,
• Option for block combining,
• Option for programming only the specified memory regions and write
protection,
• For every pin there is an option of Pull up, Pull down, High Z, Strong, or
Open pin state,
• Possibility of interrupt generation during change of state on any input/output
pin,
• I²C Slave or Master and Multi-Master up to speed of 400KHz,
• Integrated Supervisory Circuit,
• Built-in precise voltage reference.

Is PSoC good enough for my project?

Perhaps the best way to recognize the true value of PSoC microcontrollers is through
comparison with other options.

Major advantages of PSoC microcontroller include the following:

2
• There is no other microcontroller that has programmable voltage,
instrumentational, inverting, and non-inverting amplifiers;
• Hardware generators of pseudorandom and CRC code, as well as analog
modulators, are unique to PSoC families;
• MAC (Multiply-accumulate) is an essential part of digital signal processors,
which allows implementation of digital signal processing algorithms. It’s
worth noting that hardware accumulator multiplication is not a common
feature of 8-bit microcontrollers;
• Having the advantage of changeable working voltage doesn’t really need a
comment. This feature is particularly important for development of new
devices as it eliminates the need for redesigning the PCB and implementing
the level translator;
• Option for low voltage supply (~1V) is a tremendous advantage in battery
operated systems;
• Timers, counters, and PWM units are more flexible than the usual
implementation;
• Automatic code writing for accessing all the peripherals in use;
• In case you need a larger array of components, there is an option for dynamic
reconfiguration, allowing you to change peripherals during run-time. In this
way, it’s possible to minimize the processor workload at an time, leaving the
largest part of the job to the specialized hardware.

On the other hand, there are certain limitations of PSoC that could influence the
choice of microcontroller for your design.

• In systems which require highly precise or fast measurement, problems may


occur with analog device characteristics. In this case, you should analyze if
speed of AD convertors and offset/noise of analog amplifiers are able to
satisfy the project demands.
• Analog components do not have the ability to work with usual negative supply
voltage. For example, zero voltage for inverting amplifiers is taken to be the
analog ground AGND (usually 2.5V). All voltages above AGND are taken as
positive, while voltages below AGND are taken as negative.
• Most PSoC microcontrollers have 256 bytes of RAM, which could prove to be
insuficient for some projects.

1.1 System overview


PSoC microcontrollers are based on 8-bit CISC architecture. Their general structure
with basic blocks is presented in the following image:

3
CPU unit is the main part of a microcontroller whose purpose is to execute program
instructions and control workflow of other blocks.

Frequency generator facilitates signals necessary for CPU to work, as well as an


array of frequencies that are used by programmable blocks. These signals could be
based on internal or external referent oscillator.

Reset controller enables microcontroller start action and brings a microcontroller to


regular state in the case of irregular events.

Watch Dog timer is used to detect software dead-loops.

Sleep timer can periodically wake up microcontroller from power saving modes. It
could be also used as a regular timer.

Input-Output pins enable communication between the CPU unit, digital and analog
programmable blocks and outside world.

Digital programmable blocks are used to configure digital programmable


components which are selected by user.

Analog programmable blocks are used to configure analog components, like AD


and DA converters, filters, DTMF receivers, programmable, instrumental, inverting,
non-inverting and operational amplifiers. Interrupt controller handles necessary
operations in the case of interrupts.

I2C controller Enables hardware realization of an I2C communication.


4
Voltage reference is vital for the work of analog components that reside inside of
analog programmable blocks.

MAC unit is used for operations of hardware signed multiplication of 8-bit numbers.

SMP is a system which can be used as a part of a voltage regulator. For example, it is
possible to supply power to a PSoC microcontroller from a single 1.5V battery.

1.2 CPU
During the programming, instructions are stored in program (FLASH) memory in a
way which is familiar to microcontroller. CPU fetches one instruction at a time from
program memory, decodes it and executes appropriate operations. CPU unit has
internal registers PC, SP, A, X and F, as well as ALU unit and instruction decoding
unit, that are associated to instruction execution process.

Internal Registers of CPU

Program counter (PC) is used as a pointer to the next program instruction that
should be executed. With each new instruction value of program counter is being set
to point on the next instruction in program memory, which is going to be decoded and
executed.

Stack pointer (SP) points to the address of SRAM memory where data is written to
or read from in case of PUSH and POP instructions respectively. When these
instructions occur value stored in SP is internally incremented or decremented.

Accumulator register (A) is the main register which handles all arithmetical, logical
or data transfer operations.

Index register (X) could behave as register A in large number of instructions. Also,
register X is used in the case of index addressing.

Flag register (F) contains bits which describe result of a previously executed
instruction. It also has a role during selection of a RAM memory page in case when
PSoC microcontroller has more than 256 bytes of RAM. Bit Flag Zero (Z) marks that
accumulator stores a zero, while Carry (C) marks that there has been carrying during
arithmetic or logic operations.

5
Arithmetic logic unit (ALU) is a standard part of a CPU, which is used for
arithmetic operations like addition, subtracting and shifting (left or right), as well as
logic operations. Data handled by instructions could be stored in internal registers A
and X, or in RAM data memory

1.3 Frequency generator


Frequency generator is vital to CPU unit functioning, as well as programmable
blocks. Each of programmable components has certain demands regarding speed.
PSoC microcontrollers have a system for generation of different frequency signals,
which is done by graphically selecting appropriate parameters. Picture shows two
independent systems for generating signals SYSCLK and CLK 32k.

SYSCLK is the main internal clock signal with a speed of 24MHz. It is used as a
reference clock for most of other signals.

SYSCLKx2 is a clock signal with double frequency (48MHz) of SYSCLK signal.

24V1 is a signal derived by dividing frequency SYSCLK with parameter N1, which
varies in range from 1 to 16. 24V1 frequency equals SYSCLK/N1, with a frequency
from 1.5MHz (N1=16) to 24MHz (N1=1).

24V2 is a signal derived by dividing 24MHz frequency with parameter N1, which
varies in range between 1 and 16. 24V2 signal frequency equals SYSCLK/N1N2.,
which means that possible frequency ranges from 93.75kHz (N1,N2=16) to 24MHz
(N1,N2=1).

24V3 signal is derived by dividing frequency of one of the signals 24V2, 24V1,
SYSCLK or SYSCLKx2, with number N, in the range from 1 to 256.

6
CPU_CLK is used as a CPU unit frequency which has a direct impact on instruction
execution speed. CPU_CLK can have any of eight frequencies that are in range from
93.75MHz to 24MHz.

Frequency 24V1, 24V2, 24V3 and CPUCLK selection is done easily, by setting
appropriate parameters in Device Editor or during program runtime by selecting three
lower bits of OSCCR0 register.

CLK32K is a slow signal with a frequency of 32kHz. It can be used as a


programmable component input. It can also be used for Sleep timer wake-up
operation in the case when other SYSCLK derived signals are inactive.

Signal SYSCLK can be acquired using internal main oscillator (IMO), while
CLK32K signal is acquired through internal local oscillator (ILO).

Fault tolerance of 2.5% in the case of internal frequency generation, is the limit factor
in a precise timing applications. In such case external SYSCLK clock reference
should be used. External frequency ranges from 1 to 24MHz. It connects to PSoC
through pin P1[4].

Similar situation is in the case of CLK32K, which also can be generated by internal
local oscillator (ILO), as said before, or more precise external 32kHz oscillator. In the
both cases microcontroller starts with internal frequency generators, after which is
necessary to satisfy appropriate procedure.

1.4 Microcontroller power consumption


Processor signal frequency CPUCLK is directly connected with the instruction
execution speed of the microcontroller. Doubling the frequency, program executes
approximately twice faster. On the other hand, higher frequency doesn’t necessary
always mean better overall performances. Main disadvantage in rising the frequency
is it’s unwanted effect on microcontroller power consumption, which is one of the
main problems it the case of battery supply. Other disadvantage of higher frequency is
more intensive generation of electromagnetic interference, which may affect on
surrounding devices. Because of these problems general rule should be applied, which
says that lowest possible satisfactory frequency should be used. Default value of
PSoC microcontroller signal frequency is 3MHz, which is a compromise between
speed and consumption.

To maintain the longest possible uninterrupted work time, it is an imperative to bring


power consumption to its lowest satisfactory functional level in battery operated
devices. Most of microcontrollers operate only periodically, while being in the idle
state for the most of their time. Major power saving can be achieved by bringing
microcontroller to sleep mode while microcontroller does no important role. Saving is
achieved because of all the frequencies, except CPU32K and SLEEP become inactive,
while processor stops instruction execution. Microcontroller could be woken up from
sleep mode only by reset or a interrupt.

Interrupt could be generated by a sleep timer or some digital block which use
CPU_32k frequency. Also GPIO pin or analog column interrupts can be used for CPU
waking-up. Sleep timer represents a special counter whose main role is to generate
7
periodic interrupts which enable waking microcontroller from power saving mode.
Sleep timer frequency interrupt ranges from 1 to 512Hz. After waking microcontroller
does all needed operations after which it’s being switched back to sleep mode and
waits for another sleep timer interrupt. There is a appropriate type of interrupt needed
to wake the microcontroller from sleep mode. Because of possibility for various
irregularities to occurs during the work of microcontroller there is a need to reset it in
those cases, or in other words, brought to beginning state. Begin state means all
internal registers are initialized and program continues its execution from beginning.

1.5 Reset
POR

During the work of microcontroller, supply voltage variations occurs. It is very


dangerous if voltage drops beneath certain limit, because microcontroller can make
some unpredictable actions. In the case of such voltage drop detection,
microcontroller is switched into Power on Reset mode in which it remains until
voltage stabilizes above critical limit which is defined by Trip Voltage parameter.

XRES

External reset allows user to bring microcontroller to start state by switching a button.
Reset is achieved when XRES pin reads logic ONE. Simplest reset circuit can be
made with pull-down resistor and one switch.

WDR

Watch dog reset (WDR) is used for avoiding software dead-loops or other
irregularities, bringing the system in the start state. Using WDR, it is watch dog timer
(WDT) is periodically restarted inside of a main program, after which appropriate
subprograms are executed. In normal mode after certain time WDT is being restarted
once again and subprogram cycle continues. But, if program blocks in one of the
subprograms WDT is not reset, and WDR occurs.

8
1.6 Digital Inputs and Outputs
Connection between a PSoC microcontroller with an outside world is achieved over
input-output pins. Eight pin group which could be accessed simultaneously are parts
of one port. Although port number differs from the type of the microcontroller, write
and read operations are done in the same way in any case. Port access registers are
stored inside of register address space noted as PRT0DR, PRT1DR, PRT2DR,
PRT3DR, PRT4DR or PRT5DR.

Writing to port

Writing value to PRTxDR initializes register which through init circuit drives the state
of pins. Init circuit can pass the signal from PRTxDR register directly (strong), over
pull-up or pull-down resistors or through open drain output. Beside that, there is a
possibility to isolate value of register from pin state (Hi-Z).

Reading port

Reading value from address PRTxDR digital state of voltage on pins is stored to
register A. In case that voltage is dictated by some external device, read value could
differ from voltage on PRTxDR register.

Drive Mode

Selection of the way in which init register PRTxDR is connected to pins can be set
inside of Device Editor or during runtime initializing registers PRTxDM2, PRTxDM1
and PRTxDM0. There is eight methods to initialize pins in total, which enables
connection to different types of devices, with considerate smaller amount of external

9
components. Pin work modes are defined according to the following table depending
on contents of appropriate bit from registers DM2, DM1 and DM0.

DM2 bit DM1 bit DM0 bit Mode Data = 0 Data = 1


0 0 0 Resistive Pull Down Resistive Strong
0 0 1 Strong Drive Strong Strong
0 1 0 High Impedance Hi-Z Hi-Z
0 1 1 Resistive Pull Up Strong Resistive
1 0 0 Open Drain, Drives High Hi-Z Strong (Slow)
1 0 1 Slow Strong Drive Strong (Slow) Strong (Slow)
1 1 0 High Impedance Analog Hi-Z Hi-Z
1 1 1 Open Drain, Drives Low Strong (Slow) Hi-Z

Strong mode is used when it is needed to connect the state on PRTxDR register
directly to pins. This way of connection is applied when pin is used as an input.

Analog Hi-Z mode is used when connecting analog signals, like AD converter input.
In this case, all internal connections between PRTxDR register and pin are
disconnected, so not to interfere with value of brought voltage.

Pull-up or pull-down resistors are used when connecting with buttons or some other
devices which demand this type of components. These resistors are defining the state
on input when button is not pushed.

Open drain mode is used when it is needed to bring several devices to the same line,
when it is needed to add one external pull-up or pull-down resistor. This mode is
convenient for realization of a line which signals if there has been a mistake to one of
the microcontrollers. For example, when used pull-up resistor version when zero
(error) occurs on any of output pins state of this line will be zero. Pins on PSoC

10
microcontroller allow user to generate interrupt on any pin, when signal changes, or
on signal rising or falling edge.

1.7 Analog inputs and outputs


Some of input-output pins, beside their standard use can perform analog input or
output operation. Any pin of port P0 as well as lower four pins of port P2 can be used
as analog input. Inputs of port P0 are connected to analog blocks over analog
multiplexers, while in case of port P2 they are connected directly to programmable SC
blocks. Pins P2[4] and P2[6] can serve as external referent voltage inputs. Outputs
from analog blocks can be connected to 4 output buffers, which are connected to
P0[2],P0[3],P0[4] and P0[5] pins.

1.8 Accessing programmable digital blocks


Digital components, which are stored inside of programmable blocks, aren’t
connected directly to input or output pins. It is done in a way shown on following
picture, which depicts group of four digital programmable blocks. As it could be seen,
pin connection is established using global connection lines, multiplexer and lines of
programmable blocks. PSoC microcontrollers can have one, two or four digital
programmable block groups like this one depending on their family.

11
1.9 Global input lines
Global input lines establishes connection between the pins and input multiplexers.
Global input lines are divided in two groups, depending on weather they can connect
to ports with odd (GIO) or even (GIE) index. Rule of connection is that it is possible
to connect only between a line and a pin which have the same index. For example,
line GIO_0 can connect only to zero pin of some of the odd index ports
(P1[0],P3[0],P5[0]).

Input multiplexers of block lines

Input multiplexer selects one of global lines and connects it to signal carrying line
which leads to programmable blocks. Picture shows that input block lines can be
connected to GIO or GIE lines with same index, or with index with offset four.

12
1.10 Digital programmable blocks
Inside of digital programmable blocks user can configure components like timers,
counters, PWM, PRS, CRC generators and devices for SPI, IrDA and UART
communication, which enables custom hardware adjustment of the system for specific
uses. The process of setting and connecting using PSoC Designer is very simple to
understand, but at first is necessary to understand the way those components function.
Most components, like counters, PRS and CRC generators can be stored inside of any
free block. On the other side, communication components like Rx, Tx, UART and SPI
can be set on the right side of the programmable blocks.

The number of necessary blocks which are used for component configuration shown
in the table:

Number of blocks Components


1 Counter8, Timer8, PWM8, PRS8, RX8/TX8, SPIM/SPIS

13
Number of blocks Components
Counter16, Timer16, PWM16, PRS16, PWMDB8, CRC16, UART,
2
IrDARx/IrDATx
3 Counter24, Timer24, PWMDB16
4 Counter32, Timer32

Frequency signal (CLK)

Frequency signal is needed for digital components to work. Depending on wanted


speed there is a range of several built-in frequencies to choose from:

• internal signal frequency VC1, VC2, VC3, SYSCLKx2, CPU_32


• output from adjacent blocks
• common Broadcast line (BC)
• input (RI) or output (RO) block lines

Most common internal signals are VC1, VC2 and VC3, because when used with
different prescalers, they offer broad range of possible frequencies. In case that
signals VC1,VC2 and VC3 could not offer specified frequency, outputs from Counter,
Timer or PWM, which can be used like like additional prescalers. Picture above
shows in dotted line direct way to connect output of previous block with the input of
the next block. In case that signal needs to be routed across several blocks, connection
is done over common frequency line BC.

Component input signal

Most of the components, beside frequency signal, has one or two digital inputs. For
example, in the case of a counter and PWM generator input is used for enabling
counting. There are different possibilities in selection of the component input signal:

• block input lines (RI), which is a case of external signal


• block output lines (RO), in the case of component cascading
• analog block comparator lines
• signal of logic one(high)
• signal of logic zero (low)

Component output signals

Digital outputs of the component are used for connecting programmable blocks with
output lines RO. Signal could be routed from output lines further toward output of the
microcontroller or input of some other component. Output multiplexers are used for
connecting lines of programmable blocks with global output lines.

14
Multiplexer

Depending on the state of multiplexer, output (RO) or input (RI) line of


programmable block could be connected.

Logic circuit

Selected signal can be brought to the output of logic circuit. As other input could be
used some of adjacent lines of programmable blocks (RO). Logic circuit can:

• pass one of two signals


• invert input signals
• do logic operations AND, OR or XOR over input signals which could be
inverted previously.

Output drivers

Logic circuit output can be routed to four output drivers, which can make connection
to one, or more, global output lines. Line of programmable blocks with some index
can be connected to GOO or GOE lines with same or by four higher index. Global
output lines makes connection between drivers and pins. They are separated in two
groups, depending on where they can be connected to ports with odd (FGIO) or even
(GIE) index. Rule of connection says that only lines and pins with the same index can
be interconnected. Beside that there is a possibility to establish a connection between
input and output lines, which enables additional processing of the input signal.

15
1.11 Analog programmable blocks
Analog programmable blocks are grouped in columns of three programmable blocks.
Depending on family of microcontroller, there could be 1, 2 or 4 analog columns.
Each column has input multiplexer, one frequency line, output analog and a
comparator line.

Analog multiplexers of port P0

Signals from port 0 are connected to analog ACB blocks over appropriate input
multiplexers. Multiplexers can select even (Port0_even) or odd (Port0_Odd) pins,
while two middle columns have the ability to choose either pins of port P0.

Analog inputs of port P2

Beside port P0, as analog inputs could be used four lower pins of port P2. This pins
can be connected directly to analog programmable blocks.

Analog columns

One column of analog blocks is made of three types of blocks: ACB, ASC i ASD.
Outputs of these blocks can be routed to some of adjacent blocks, output analog line
or comparator line.

16
ACB blocks are used to store amplifiers with rail-to-rail inputs and outputs, digital
controlled resistors and internal multiplexers. Depending on interconnections made
inside of ACB blocks, it is possible to implement inverting, noninverting, instrument
amplifier or comparator. As input to ACB blocks can be used analog multiplexer or
output signal of some of adjacent blocks.

ASC and ASD blocks are of switched capacitor (SC) type. They contains amplifiers
with rail-to-rail input and outputs, condensators and internal multiplexers. AD, DA
and analog filters could be implemented depending on configuration inside of these
blocks. As inputs to SC blocks, input from some adjacent block could be used. It
should be noted, that signals from analog multiplexers couldn’t be brought directly to
SC blocks, but over ACB blocks.

Analog outputs

For every analog column is common to have an AnalogOutBus line. Analog output
lines can be are connected, through a buffer, to four middle pins of port A.

Comparator outputs

Every analog column has one comparator line, to which could be connected digital
output from one of analog blocks. Comparator output could be connected to digital
blocks (most common way of doing it is as counter signal, or timer). Before
connecting, there is a possibility to modify or combine comparator output of some
column (A) with next comparator line (B), using some logic operation.

Frequency signal

Many components, such as AD, DA convertors and filters, need to have a frequency
signal in the specific range, which affects the component’s speed. Frequency signal
selection done over appropriate multiplexers. For each of the columns it is possible to
select:

• internal frequency VC1

17
• internal frequency VC2
• output over some of the digital blocks, most commonly counter timer and
PWM generator, which is selected through the multiplexer.

1.12 Referent voltage generators


There are three stable voltage generators in PSoC microcontroller:

• AGND
• RefH
• RefLo

AGND is ground voltage for analog components. Voltage values higher than AGND
are considered as positive, while less are negative. PSoC microcontrollers have one-
side power supply, so value of analog ground is somewhere in between GND and
VDD. AGND value is selected by user.

RefHi and RefLo represent referent higher and lower voltage, for AD and DA
components. PSoC microcontrollers have a system that can generate several referent
signal values AGND, RefHi and RefLo. This enables simple adjustment to different
types of voltage sensors. Referent voltages are made from internal temperature
stabilized bandgap voltage reference Vbg = 1.3V, supply voltage VDD or external
signal as shown in the following table. PSoC microcontrollers are well adjusted to
work with battery supply.

18
Ref Mux AGND [V] RefLo [V] RefHi [V]
Vdd/2 ± Vbg 2.5/1.65 1.2/0.35 3.8/2.95
Vdd/2 ± Vdd/2 2.5/1.65 0 5.0/3.3
Vbg ± Vbg 1.3 0 2.6
1.6Vbg ± 1.6Vbg 2.08 0 4.16
2Vbg ± Vbg 2.6 1.3 3.9
2Vbg ± P2[6] 2.6 1.6 3.6
P2[4] ± Vbg 2.2 0.9 3.5
P2[4] ± P2[6] 2.2 1.2 3.2

1.13 Switch Mode Pump


In the case of battery suply Switch Mode Pump (SMP) system can be used. Its
operation is based on principle of BOOSTDC/DC convertor. This type of convertor
gives voltage supply value higher than battery voltage, which makes possible power
suplly with 1.5V battery. For SMP to function properly, it is necessary to connect,
beside battery, a diode, inductivity and a capacitive.

1.14 MAC

19
MAC unit is a device that implements operation of hardware multiplication of 8-bit
signed numbers, as well as sum of product. For execution of these operations there is
no special instruction, but all of the work is done by writing to and reading from
certain registers.

Hardware multiplication

Multiplication operation is done by writing 8-bit inputs X and Y into registers


MUL_X and MUL_Y, and reading output from 16-bit result from registers MUL_DH
and MUL_DL.

;file: main.asm
;project: MAC

mov reg[MUL_X],0x64 ;Initialize X = 100


mov reg[MUL_Y],0x0C ;Initialize Y = 12
mov A,reg[MUL_DH] ;Read high byte of result (0x04)
mov A,reg[MUL_DL] ;Read low byte of result (0xB0)

mov reg[MUL_X],0xFE ;Initialize X = -2


mov reg[MUL_Y],0x03 ;Initialize Y = 3
mov A,reg[MUL_DH] ;Read high byte of result (0xFF)
mov A,reg[MUL_DL] ;Read low byte of result (0xFA)

Sum of products

During multiplication, result can be added to previously stored value inside of 32-bit
accumulator. In that way is made sum product operation, which represents most
important operation of digital signal processing for correlations, convolutions and
filtering. Beside that MAC unit allows simple implementation of multibyte
multiplication.

20
Summing products is done when data X and Y are initialized by writing into registers
MAC_X or MAC_Y. Input data X and Y could also be initialized by writing into
registers MUL_X and MUL_Y, in which case operation of product summing does not
take place. Result of product summing operation is stored inside of registers
ACC_DR3, ACC_DR2, ACC_DR1 i ACC_DR0. Starting value of accumulator is set
to zero by writing any value to register MAC_CL1 or MAC_CL0. In the next
example shows method of initializing input data, as well as operation of summing
products.

1.15 Decimator
Decimator component is component that is used for digital data processing during
sigma delta, as well as some types of incremental AD conversion.

;file: main.asm
;project: MAC

mov reg[MAC_CL0],0 ;Clear Accumulator


;(Acc = 0)

mov reg[MUL_X],5 ;Initialize X


mov reg[MAC_Y],4 ;Initialize Y and execute MAC
;(Acc = 0 + 5 * 4 = 20)

mov reg[MUL_X],6 ;Initialize X


mov reg[MAC_Y],5 ;Initialize Y and execute MAC
;(Acc = 20 + 6 * 5 = 50)

mov reg[MUL_X],3 ;Initialize X


mov reg[MAC_Y],2 ;Initialize Y and execute MAC
;(Acc = 50 + 3 * 2 = 56)

mov reg[MAC_Y],2 ;Initialize Y and execute MAC


;(Acc = 56 + 3 * 2 = 62)

mov reg[MAC_X],4 ;Initialize X and execute MAC


;(Acc = 62 + 4 * 2 = 70)

mov A,reg[Acc_DR0] ;Read low byte of result


;(0x46 = 70dec)

1.16 I2C Controller


I2C controller implements hardware serial I2C communication, and in that way
minimizes usage of CPU units resources. Most important operations of I2C controller
are:

• Master or Slave, sending or receiving data


• Byte level data processing
• Connected to CPU over interrupts or polling mode.
• Transfer speed: 50K, 100K and 400K
• Frequency synching in case of larger number of masters
• 7or 10-bit addressing of I2C unit

1.17 Interrupt Controller


21
Interrupts are mechanisms inside of a microcontroller that allow responding to some
event immediately after its detection. Events could be internal (timer overrun, end of
AD conversion) or external (character receiving over serial connection, pin state
change). When interrupt occurs program execution is interrupted (hence the name) by
jumping to part of the program that is called interrupt routine. Upon ending of that
routine program continues from place in program where interruption took place.
Interrupt controller makes hardware interrupt detection, program flow interruption by
jumping to interrupt routine, as well as returning to interruption point from the
routine. These operations are executed in several steps:

1. When event that triggers interruption takes place, interrupt controller stores
interrupt type.
2. End of current instruction is awaited.
3. If interrupt is allowed and if global interrupt permit is set to 0ne (GIE = 1),
interrupt processing begins. For later continuing of instructions execution,
stack holds values of PCH, PCL and F registers.
4. New interrupt occurrence is disabled by setting values of register F to zero
(GIE = 0).
5. Program counter is set to address of interrupt routine, which is same as
interrupt type, after which execution jumps to interrupt routine address.
6. Program executes interrupt routine instructions.
7. When it gets to instruction reti, which marks return from main program, values
of F register are restored from stack, and program counter is reset to old value
before interrupt occurred.

Register PRTxIF is used as indication of GPIO interrupt on certain port, while


PRTxIC1and PRTxIC0 are appropriate control registers. Every interrupt type can be
masked or deleted, which is done with help of INT_MSK and INT_CLR registers,
which will be discussed in more detail in examples part.

1.18 Address space


PSoC microcontrollers have three address spaces:

• ROM
• RAM
• registers

As in all Harvard architecture processors access to ROM memory is done with special
lines, so microcontroller is able to acquire instructions and access data at the same
time.

22
Program memory

Program memory is the part of ROM, which is used for storing program code, which
is written in this part of memory written by programming hardware. Program memory
is implemented in FLASH technology, which allows simple development time change
of the program inside of microcontroller. Program memory size depends on the family
of PSoC microcontrollers and is 2, 4, 8, 16 and 32 kB.

Supervisory ROM

Supervisory ROM is part of ROM which is used during start of PSoC microcontroller,
as well as for calibration of components. With special instruction SSC, it is possible
access this part of memory.

RAM

RAM enables storing of variables and stack which are used during work of
microcontroller. Size of RAM, in most PSoC microcontrollers, is 256 bytes. When
microcontrollers have more than 256 bytes of RAM (series CY8C29xx and
CY8C21x34), memory is organized in 256 byte pages, with stack residing on the last
page. To access some variable, user apart from 8-bit address must state appropriate
page.

Register

Register address space contains registers used for peripheral's global parameters and
programmable blocks of a PSoC microcontroller. PSoC microcontrollers have 512
registers, which are grouped in two 256 bytes banks. To access some register, beside
stating its name, what is needed is to also state the name of the bank in which resides
wanted register. Access to certain bank is done by using macros M8C_SetBank0 and
M8C_SetBank1, which delete or set bit XIO in CPU_F register.

------------------------***************************-------------------------------------

23
Chapter 2: PSoC Designer
• Introduction
• 2.1 Programmable Component Selection
• 2.2 Interconnection View
• 2.2 Application Editor

Introduction
PSoC Designer is program package that leads user through all stages of developing
project. Version discussed here will be 4.2, but this book will still remain competent
in case of newer versions, because differences are shown only in addition of new
programmable components and some minor improvements. The most important for
user is is to get familiar with two main parts of PSoC Designer:

• Device Editor
• Application Editor

Beside these two, there is also a debugger part, but during the course of this book it is
only mentioned as an option, because it demands additional hardware. Device editor
consists of two windows. First one is for selection and is called User Module selection
View. Other, is called Interconnection View. It is used for setting and connecting
components and parameter adjustment. Transfering from one to the other part of the
PSoC Designer is done easily by clicking appropriate icon. To open Interconnection
View or User Module Select windows, Device Editor icon must be selected first.
Lower image shows look of the programmable component choice window.

2.1 Programmable Component Selection


Most important part of the programmable component selection window is placed on
the left side. Components sorted in several groups, like AD converters, amplifiers,
analog communications, counters, etc. After group selection, necessary component for
project should be selected with double-click, or right-click on select. In the case of
successful selection, appropriate graphical symbol would be shown in selected
components slot.

24
The rest of the window offers some other useful information. Resource Meter shows
how much space is left for new programmable blocks. For example, 16-bit counter
takes two programmable blocks, so it is possible to place 4 counters like this one
altogether. During selection of each of the components, in lower side of the window is
opened detailed instruction, which gives information about block characteristics,
usage and code example. User does not have to know by heart all details about the
component he uses, because this part holds all necessary information.

2.2 Interconnection View


Previously selected components are still unusable, until they are placed in digital or
analog programmable blocks, and until appropriate parameters are set. This important
part of work can be done in Interconnection View window. Central part of this
window is graphical representation of programmable blocks and connection lines. In
the case of microcontroller of CY8C27xxx series, eight digital and twelve analog
programmable blocks can be used. In the place between blocks there are internal lines
for interconnection, and global purpose input/output lines. Although this scheme
looks complicated at first sight, you can be sure that it isn’t hard to master the way it
is all connected. In some way it resembles PCB routing, but really much simpler.

25
Global Parameters

On the upper left side can be found Global Resources window. It is used for general
parameters selection.This method of setting is similar to configuration words on other
microcontrollers, but with more versatility. Click on any of the parameters opens pull-
down menu with given options.

All global parameters have default values, which means that even without setting
microcontroller will be able to work. For example supply voltage can be 5V or 3,3V,
depending on selection in parameter Supply Voltage. If user does not make selection,
Supply Voltage parameter would be set on it's default value of 5V. When higher

26
frequency precision is necessary it is possible to add external oscillator on lower two
pins of port 1, and choose external as option in mentioned parameter. Most important
parameters for our examples are internal frequency prescaler values of V1, V2 and
V3. Signals V1, V2 and V3 are used by various analog and digital programmable
blocks. V1 signal frequency value can be derived by dividing system frequency of
24MHz with prescaler N1. V2 signal frequency value is aquired by dividng signal V1
with N2. Acquiring signal V3 is done in similar fashion, by dividing some signal with
value in N3, with possibility to choose from several different signals the one that will
be divided. CPU_Clock represents frequency value, based on who are processed
instructions of microcontroller.

Component Parameters

Central window on the left side is designated as User Module Parameters. Peripherals
in PSoC microcontroller are very flexible, so it is required to set the way of their
operation. Typically this is done by selecting frequency of the signal, connecting it
with some other blocks and internal connection lines. Also, component specific
parameters can be set. Such parameters are component specific, and it will be more
discussed in chapter 5. In the picture below example for setting up component
PWM16 is represented. In this case frequency signal is VC2. Time interval of impulse
and pause is 32000 and 16000, respectively, of chosen frequency signal. Obligatory
part of parameter are signals that are entering, and exiting programmable components.
This operation can also be done in graphical mode, clicking inputs and outputs on set
component. Picture holds example of adjusting signal frequency on component
PWM16. Click on black triangle, which represents signal input, enables selection of
possible clock signals. Specific parameters like impulse and pause interval, enable
and similar are not obligatory to be set in this window, but is however desired. At a
later point, while writing program in Application Editor, there is possibility for
changing these values by calling specific procedures.

Pin Parameters

Lower left side holds pin parameter options. In order to protect external devices from
unexpected signals, default pin state of PSoC microcontrollers is Analog Hi-Z, in
which microcontroller cannot change pin states. Pin drive mode selection can be done
graphically by selecting appropriate parameters in column Drive or software by
setting appropriate registers.

Option select is used for choosing the way pins are driven. If selected option is
StdCPU, then pin have standard input/output function, and is disconnected from

27
programmable blocks. If pin is supposed to be connected to appropriate global lines
over which is established connection with peripherals it is expected to be done by
user. Easiest way to do it is graphical, as it will be explained in next section of the
book.

Column Drive is used for pin drive mode settings. Options pull-up or pull-down
activate internal resistors, which set default logic state of pin to ONE, or ZERO,
respectively. This is of importance while working with devices like push-button
switches, because they allow direct connection to PSoC microcontroller without need
for external resistors. Pull-up or pull-down resistors must not be used on analog
inputs, like input of AD convertor because they can have impact on input voltage
level. In such case state of high impedance, marked with Hi-Z Analog, should be
chosen.

Third column is used when in the case of pin interrupts. It is possible to to select
interrupt on rising edge, falling edge or state change depending on previous readout.
For example, one of efficient ways to measure signal interval could be allowing
interrupt on rising edge of signal. In interrupt routine is then started a timer, and
following that, is allowed interrupt on falling edge, where timer is stopped in interrupt
routine.

Placement

Free locations for setting programmable blocks are represented by grey rectangles.
Clicking some of selected components, marks placement space in graphical part. In
case that communication from selected block, and intended pin could not be
established, next available location could be selected, using icon Next Allowed
Placement. Component placement is done by selecting component, and then right-
clicking on Place, or shorter, using icon Place. During the placement of analog and
digital components, general rule applies, that components that are to be connected
should be placed in adjacent blocks. Components of upper four digital blocks are
more easily connected among themselves, than with components from lower four
blocks. Similarly, it is easier to connect analog components that are placed inside of
one column.

28
Digital Components Interconnection

For start, the most important thing is to get to know the basic elements of
programmable blocks. Digital blocks are grouped in two entireties of four blocks, as
shown on picture.

On the upper side of each row there are four input lines to digital blocks, marked in
red, and from the lower side of each block are four output lines marked in blue.
Digital blocks aren’t connected directly to output pins, but over multiplexer and
global input or output lines. Global lines are marked in green. Second letter in name
tells about direction of the line I - input, O - output. Last letter in name gives
information if lines could be connected only to E - even or O - odd ports. For
example, GIE represents global input line that can only be connected to ports with
even index (i.e. Port 0, Port 2...).

Global input lines are placed on the left side, while global output lines are placed at
the right side. Procedure of connection global lines to pins is very simple. When

29
certain line is clicked on, a external pin name, or interconnecting input and output
global lines, is shown. Selecting option Pin, pins of ports with according index will be
offered. For example, global line GIO4 can be connected only with fourth pin of odd
number ports. Global lines are connected with digital lines from programmable
components over the multiplexer.

Multiplexer has a function to choose one input signal that will be connected with his
output. Graphically, it is represented with a small square. There are input and output
multiplexers, depending on connecting input or output lines. Clicking on some of
input lines of digital programmable blocks, opens window with possible choice of
connection. Connectiong on global output lines is a little bit more complicated than in
previous case. The selected output line is taken, which is routed to output buffers. On
upper left side is positioned multiplexer, which can select optionally connecting
shown input line. Connection to global lines is established by clicking on appropriate
buffer, which is represented in shape of triangle.

If this step is done correctly, buffer will be painted blue as well as line that goes out
from it. As additional element there appears a possibility for implementing logic
functions with adjacent lines. Selection of logical functions is done by clicking on
small square, and by choosing one of the options, after which is shown appropriate
symbol. All digital components have input for frequency. Frequency signal is marked
with black triangle. With left-click menu with possible selection of signal frequencies
is shown. Some of possibilities are 48MHz, 32kHz, V1, V2, V3, as well as signals
from some of global lines, BC lines or adjacent blocks. There are two groups of
common lines marked as BC1 and BC0. Beside frequency input, other input/output
lines could be found, depending on component type.

30
Analog Components Interconnection

Analog blocks are placed on lower side of the graphic part of the window. Four
analog columns and several multiplexers can be noticed. In every of columns, upper
block ACB is used for analog amplifiers realization, while lower two are used for AD
and DA convertors. Routing is done graphically, by connecting frequency signal, and
input signal to the same analog column. Pins with analog input/output of ports 0 and 2
are shown on the left side, which could serve as analog inputs or outputs. Columns on
far left or right side could be connected only to odd or even pins of port 0,
respectively. With help of two additional multiplexers there could be connected two
middle analog columns to any pin of port 0. Each of analog columns can have one
output that leads to one of four pins of port 0. Connection is established by using
buffer that resides on bottom of every column.

2.3 Application Editor


31
Application Editor is used for writing programs, which can be done using assembly or
C. Application Editor itself, bears much resemblance to IDE-s of other standard 8-bit
microcontrollers. Left side window holds list of files that are contained in current
project. Most important file for users is called main.

This is the place of user code start. Include files are generated automatically based on
selected programmable blocks in Device Editor, clicking on icon Generate
Application. For example, if set programmable blocks are adcinc12, pga, and lcd,
PSoC Designer automatically generates files with data and subprograms for their
usage. So in the case of AD conversion, programming is done as simply as calling
subprogram with start instruction call ADCINC12_Start and result readout with call
ADCINC12_GetSamples. File Boot.asm is should not be changed because it is
automatically rewritten during each new configuration. Names of available
subprograms in part Library Source are in file with according name. When process of
programming is done, compiling is started by clicking icon Build. In case of succesful
compiling there will be shown message in lower window 0 Errors. At the same time,
in folder output of the current project, .hex file will be shown which can be
programmed into microcontroller.

32
------------------------------*****************************------------------------------

Chapter 3: Quick Start


From the free online book “Architecture and Programming of PSoC
Microcontrollers”

• Introduction
• 3.1 Creating a Project

Introduction
Every beginning is the hardest part of every job. Because of that, it is very important
to write complete project that works, as soon as possible. What else could be in a
microcontroller world than LED blinking? Basic idea is that we implement LED
blinking by using PWM16 component, with the same signal/pause ratio. It is done in a
very simple way, by selecting frequency of 32kHz with period set to 32000, and
impulse to 16000, for base frequency of PWM16. User just should connect output of
PWM component to output pin Port_1_0 to where is LED connected, and write
simple code to start PWM component. All the steps are similar in more complex
projects.

3.1 Creating a Project


33
Click on the New Project icon opens a New project Wizard, where user should
specify name, and location of the project.

Left side of the window is used to choose the way that new project will be formed.
Most common choice is to start new project by click on Create New Project icon. If
there was a need to modify already existing project, or change of microcontroller type
of some previous design, one of lower two choices should be selected.

Click on the Next, new window with assembler or C selection is opened. Option
Assembler is available to all users, while for C one needs license. For this example,
microcontroller CY8C27643 and Assembler should be selected.

Button Finish opens Device Editor window where user can select programmable
components. Component PWM16 can be found in PWMs section. Importing it to the
project is done simply, by marking its icon, and right-click selection. As a result of

34
this operation, graphical simbol of PWM16 block will appear in selected components
slot, automatically named as PWM16_1. This name can be changed by user.

Note that resource window shows that component PWM16 takes two digital blocks,
which means that it is possible to place a maximum of three blocks like this. After
component selection, we go to interconnection window by click on the icon
Interconnect View.

Component placement in a marked free locations is simply done by right click on the
component.

Next step is to adjust parameters of PWM16 component. Period and width of PWM
impulse is set in window User Module Parameters. Parameter value of 32000 with
input frequency CPU_32_KHz results in one second period. For equal length of signal
and pause, Pulse Width is set to half of period, e.g. 16000. Final view of the User
Module Parameter window is illustrated in the figure below.

35
PWM16 output signal CompareOut is connected to output pin P1[0] in three steps. As
a first, since LED has been connected to pin Port_1_0, PWM16 output CompareOut
should be connected to digital output line with index 0, in this case Row_0_Output_0.
Click on this line opens output digital multiplexer settings, where should be done
connection to a global output line by enabling appropriate buffer.

Since LED is placed on odd Port_1_0, it is necessary to make connection trough Odd
buffer line GOO_0 as it was illustrated in a figure above.

Final link with output pin is accomplished by click on Global_OUTOdd_0 linije and
selecting pin Port_1_0.

36
When component is placed, and connected to output pin user can start to write code.
Before that, Generate Application icon should be clicked, which starts automatic
generation of files for PWM16 component.

Application editor selection is done by appropriate icon click, which is shown in the
figure below.

On the left side of Application Editor, list of all automatic generated files can be
found. Click on file main.asm from Source Files section, opens the main program
window. For PWM16 to start working, all necessary is to call Start procedure
PWM16_1_Start. List of all other subprograms that could be used for given
component is found by opening .asm file with the same name as the component in
Library Source section, or in appropriate component manual. Click on pwm16_1.asm
opens a window with all subprograms. All available subprograms from this file are
declared with directive extern.

After code is written, compiling should be started by clicking on icon Build. In case
when code does not contain any mistakes, compiling will be succesfully, and
blink.hex file will be generated in the folder output.

37
---------------------------------------**********************-------------------------------

Chapter 4: Assembly Language


• Introduction
• 4.1 Instruction types
• 4.2 Operators
• 4.3 Constants
• 4.4 Instruction set
• 4.5 Directives
• 4.6 Addressing modes

Introduction
Complete set of 37 basic instructions, which makes with their sub-variants total
number of 136 instructions, are explained in this chapter. Reason for such large
number of instructions lies in the fact that this is a CISC architecture microcontroller,
whose instructions allow pretty much conform programming. One disadvantages is
that instructions are not optimized for speed, because their execution takes several
instruction cycles.

4.1 Instruction types


Data transfer

Data transfer is done by instructions MOV, MVI and SWAP. MOV represents basic
transfer instruction, which offers large number of arguments. First argument is
destination location, while second source location. There are 21 types of MOV
instruction in total, in dependence of data types. Shortest execution time is in the case
when data is transferred trough internal registers A and X, while it is the longest when
transferring contents of two variables. Instruction MVI is optimized for data transfer
between accumulator A and array of sequential data locations. Aside from transferring
data, at the same time initialization, which is needed for acquiring next element, takes
place. One of the arguments is register A, and other is the value of variable that has a
role of pointer to array, i.e. which holds address of the first array element. Instruction
SWAP is used for direct exchange between registers A,X and a value of some
variable Beside that, there’s also a possibility of exchange of values in registers A and
SP.

Arithmetic and logic

PSoC as well as other microcontrollers has built-in support for arithmetic operations,
like addition or subtraction. Instructions ADD and SUB are two basic operations.
Value of the first argument is added or subtracted with other argument, and result is
stored in the first value Beside basic operations of adding and subtracting, there are

38
also existing their modifications. There are instructions INC and DEC, which
implements increment (add 1) or decrement (subtract 1) operations. ADC and SBB
makes addition or subtraction operation, while Carry Flag is added to the result,
which allows simple multi-byte operations. MAC unit allows operation of hardware
multiplication. There are no special instructions for this operation, since all the work
is done in special multiplication registers. Values that are multiplying are transferred
to registers MUL_X and MUL_Y with MOV instruction, and then high end, and low
end bytes are read from registers MUL_DH and MUL_DL.

Logic unit of PSoC microcontroller has ability to handle standard logical operations
AND, OR, XOR, negation (CPL), shifting (ASL, ASR) and rotation (RLC, RRC). For
operations that have two arguments holds rule that operation is executing on
according bits of both arguments, and the result is stored in first argument. In case of
CPL instruction content of accumulator is completed bit by bit, so that every zero is
replaced by one, and opposite. Instructions of shifting and rotation moves bits one
space to the left (toward bit 7) or one space to the right (toward bit 0), while the bit
that exits register is written into Carry Flag of F register. There are differences in the
way how are set bit 0 or bit 7. ASL and ASR instructions are used for signed
multiplication and dividing by number 2. In the case of ASL zero bit is set to 0, and in
the case of ASR, bit seven is not changed. Rotation instructions RLC and RRC are
writing bit exiting register Carry Flag into which is later written to bit on opposite
side of register.

Comparation instructions

Because of need to compare arguments, there are two instructions CMP and TST.
These instructions have two comparing arguments that don't change their value.
Result of these instructions represents state of Z and C flags in F register.

Instruction CMP is used to compare two values. If both arguments are equal, Z flag
will be set to one. If first argument is lower than the other C flag will be set to one, in
every opposite case C and Z flags will be set to zero.

TST instruction is doing AND operation between the first argument, and eight-bit
constant, during which the result is not written in first argument, like in case of AND
operation. If result of AND operation is zero, then flag Z will be set to one. TST
instruction gives possibility to test if certain bit of some register is set to zero or one.
As eight-bit constant should be taken mask value, which has all zeroes, and one in
position where are test bits. In this case, flag Z shows that bit is set to one. PSoC
microcontrollers support conditional, unconditional and subprogram jumps.

Decision and Control statements

Instructions of relative jumps allow us to continue program execution from given


label if condition for that jump is met, which means that appropriate flag is set - C, for
jumps JC and JNC, and Z for JZ and JNZ jumps. If condition is not met, program
continues to execute the next instruction.

Unconditional jumps use two sets of instructions, depending on how far jump address
is. For close jumps instructions JMP and JACC are used, while instruction LJMP is
used for far jumps.

39
Instructions JACC uses offset jump relative to given label, whose value is stored in
register A.

Calling routine (CALL) and return (RET) from subprogram, as well as returning from
interrupt (RETI) are executed the same way as in other microcontrollers. Instructions
for stack operations Instructions PUSH and POP are, in standard ways, allowing
storing values of important registers inside of stack during procedure calling. PUSH
instruction is copying value of register A and X, while instruction POP returns values
in opposite order. Stack is LIFO ordered, which means Last In First Out, which
explains a little bit more the way PUSH and POP instructions function. Stack is
positioned in upper part of RAM, so it wouldn’t overlap with defined variables.
Beside holding important registers, these instructions allow transporting procedure
parameters over stack, by storing parameter using PUSH before procedure call, and
taking it from stack by calling PUSH instruction from inside of procedure.
Instructions PUSH and POP with help of index addressing allow realization of local
variables inside procedures, which will be discussed later in examples part.

Accessing ROM Data that is stored in ROM can be accessed with help of instructions
INDEX and ROMX. INDEX is of special importance during look-up table reading.
Offset of the element that is being accessed is previously stored in accumulator A,
while the label of look-up table is called as argument. Result of read value is stored in
register A.

Other instructions Of other instructions, most important one is NOP, which does no
special operation, but is used for time delaying that lasts four instruction cycles.

4.2 Operators
Among instructions, where constants appear, it is possible to form statements with
help of assembler operators for arithmetic and logic functions. Execution of operators
has nothing with work of microcontroller, because that work is being done by
compiler during program translation. Next table gives comprehensive list of assembly
operators.

4.3 Constants
Decimal constants are written without any prefixes, while hexadecimal ones have
prefix 0x or $, while binary ones have 0b or %. Constant character arrays are written
inside of quotation marks.

4.4 Instruction set


(work in progress)

4.5 Directives
Directives represent useful elements in assembly that give various information of
interest for program translation. Some of more important directives will be covered
further.

40
DB

DB directive is convenient for look-up table forming where bytes are used as data.
Binary values of constants are written inside of ROM memory at the address specified
by label.

Table1: DB 1,2,3

DW, DWL

When it is needed to form look-up tables with word type elements, then it is possible
to use directives DW and DWL, depending on which byte do they store first, lower
then higher or contrary.

Table2: DW 0x1234,0x1235
Table3: DWL 0x1234,0x1235

DS

During the work with serial communication or writing data on LCD, it is often needed
to use ASCII values instead of binary. Directive DS writes to program memory ASCII
values of constant array of characters that are written inside the quotes. In the case of
character “0”, in memory will be written character ASCII value 48.

Table4: DS “0123456789”

When all elements of constant character array are loaded in memory, there is a need to
somehow detect an end of array. Because of that it is common to add ASCII character
NULL to an end of array, which is represented as binary 0.

Table5: DS “HelloWorld” DB 0

INCLUDE

include "filename" Directive include is used to insert content of given .asm or .inc
files. In this way it is possible to combine several files which contain different parts of
program, thus improving code readability and reusability. There is a directive in the
beginning of main program include “m8c.inc” which enables access to
microcontrollers registers. File PSoCAPI.inc is used as a connection towards files that
contain procedures for working with selected programmable blocks.

; Assembly main line


include "m8c.inc" //
include "memory.inc" // Constants & macros for SMM/LMM and Compiler
include "PSoCAPI.inc" // PSoC API definitions for all User Modules
include "User.inc"
export _main

_main:
call PWM16_1_Start
.terminate: jmp .terminate

EXPORT

41
export procedure_name

Directive EXPORT is being used to mark that the procedure written in current file can
be used in other files. Directive Export is put before procedure implementation,
usually in the begging of that file. As an example is given file with procedures for
programmable component PWM16.

EQU

equ value

Directive EQU enables giving constant name to some value Before compiling that
name is automatically changed into according constant value.

4.6 Addressing modes


There are several ways to fetch data during instruction execution, which are all called
under one name addressing methods Depending on whether data is a constant, RAM
variable or register variable, there are immediate, direct, index and indirect addressing
method. Beside these complicated looking names, very simple procedures are hidden.

Immediate addressing

When data is a constant value, then it is considered as immediate addressing. For


example: Data could be RAM variable, or a register. Easiest way to access value of
that variable is by putting it’s name inside of brackets. If we didn't put those brackets,
we would access address of that variable, instead of its value.

Register addressing

When accessing register, beside brackets, it is also needed to put registered word reg,
which shows that it is done in register address space.

Index addressing

One other thing that also happens very often is the need to access continuous memory
locations. In that case we could some help from register X, which has a possibility of
index addressing. Index register X is used to store address of some variable.
Incrementing and decrementing values of the index register it is possible, in a simple
way, to access elements of an array.

Using instruction MVI, it is no longer needed to continuously increment register X. In


this case variable which plays role of a pointers used instead of register X. Its value is
previously initialized to hold address of the variable that is being accessed. MVI
transfers values between accumulator A and value of the variable, with initialization
of pointer-variable so it stores address of next variable in array.

42
mét sè vÊn ®Ò n©ng cao
I. RTC
Để tạo RTC chính xác bạn nên dùng chế độ sleep của PsoC với tần số
1Hz tương ứng với 1s tạo ngắt một lần
- Chế độ Sleep có 2 tác dụng :
+ Làm RTC (khá chính xác nếu dùng thạch anh chuẩn 32,768
KHz),do đó có thể thay cho những con RealTime chuyên dụng như
DS1307
+Tạo 1 xung kích (ngắt) cho macro M8C Sleep làm việc giúp tiết
kiệm năng lượng cho PsoC.

Chúng ta có thể kích hoạt cho chế độ Sleep của PSoc bằng cách thiết lập các
thông số ngay trong Global với các thiết lập :
32K_Select chon internal nếu dùng clock nội hoặc external (nếu dùng clock
ngoài).
Sleep_timer : 1Hz tương ứng với 1s tạo ngắt một lần-chúng ta áp dụng điều
này để làm RTC.
code:
#pragma interrupt_handler SleepISR
BYTE sleepTimer=81;
void main()
{
M8C_EnableIntMask(INT_MSK0,INT_MSK0_SLEEP);
M8C_ClearWDTAndSleep;
//Clear sleep timer mask
M8C_EnableGInt;
//Enable global interrupts
while(1)
{

M8C_Sleep;
//CPU goes to sleep
//Wakes up on sleep timer interrupt
}

}
void SleepISR(void){

}
…..//Lam gi trong day cung duoc
}
}

Cách khác là có thể dùng IC chuyên dụng RealTimer. Đây là cách


sử dụng I2C để giao tiếp với RTC DS1307, các bạn có thể dùng cả
I2Cm(firmware) hoặc I2CHW(Hardware) để giao tiếp. Về phần cứng
không có gì, chỉ cần thêm điện trở Pullup vào đường SDA và SCL.

43
Thời gian đặt trong tx, bắt đầu bằng 00, sau đó là giây, phút, giờ, ngày
trong tuần, ngày trong tháng, tháng, năm,byte cuối cùng 0x93 là byte ghi
vào thanh ghi điều khiển của RTC.
#include <m8c.h> // part specific constants and macros
#include "PSoCAPI.h" // PSoC API definitions for all User Modules
#include "stdlib.h"

BYTE tx[]={0x00,0x00,0x22,0x23,0x07,0x19,0x11,0x05,0x93};
BYTE rx[8];
BYTE status;
unsigned char i=0;
void delay()
{
int i=0;
for(i=0;i<100;i++);
}
void main()
{
// Insert your main routine code here.
M8C_EnableGInt;
LCD_1_Start();
I2CHW_1_Start();
I2CHW_1_EnableMstr();
I2CHW_1_EnableInt();
I2CHW_1_InitRamRead(rx,8);
I2CHW_1_InitWrite(tx,9);
I2CHW_1_bWriteBytes(0x68,tx,9,I2CHW_1_CompleteXfer );
while(!I2CHW_1_bReadI2CStatus() &I2CHW_WR_COMPLETE);//wait for complete
delay();
I2CHW_1_ClrWrStatus();
I2CHW_1_bWriteBytes(0x68,tx,1,I2CHW_1_NoStop);
while(!I2CHW_1_bReadI2CStatus() &I2CHW_WR_COMPLETE);//wait for complete
I2CHW_1_ClrWrStatus();
while(1)
{
//read the time
I2CHW_1_bWriteBytes(0x68,tx,1,I2CHW_1_NoStop);
delay();
I2CHW_1_ClrWrStatus();
I2CHW_1_fReadBytes(0x68,rx,7,I2CHW_1_RepStart);
delay();
I2CHW_1_ClrRdStatus();
LCD_1_Position(0,0);
LCD_1_PrCString("T.gian");
LCD_1_Position(0,10);
LCD_1_PrHexByte(rx[2]);
LCD_1_PrCString(":");
LCD_1_PrHexByte(rx[1]);
LCD_1_PrCString(":");
LCD_1_PrHexByte(rx[0]);
}
}
Chú ý
DS1307 giao tiếp theo chuẩn I2C
Sơ đồ nối rất đơn giản như mã lệnh quy định các chân SDA, SCL, lưu ý cần có trở
kéo lên ở các chân SDA và SCL!
Một số lưu ý về thạch anh:
- Nên đặt TA càng gần chân X1, X2 của DS1307 càng tốt
- Nếu được thì lấy một vòng kim loại vòng xung quanh TA rồi hàn xuống mass sẽ
tăng độ ổn định
- Đường mạch nối chân TA với X1, X2 càng ngắn càng tốt và nên phủ mát
- Mạch bắt buộc phải có PIN backup cho DS1307 nếu không sẽ ko bao giờ ổn định

44
được!

II.Sleep Timer
Sleep timer là một timer luôn luôn chạy ngay cả khi CPU ở trạng thái Sleep
(vì thế nó có tên là SLEEP_TIMER), sử dụng nguồn clock 32.768Kh (internal or
External)
Có thể chọn tần số cho nó trong phần Global resource: ví dụ chọn 1Hz thì nó ngắt
1s/lần, 512Hz thì 1/512s 1 lần....Cái này đặt ở phần Editor/Global resource hoặc đặt
trong chương trình bằng cách tác động vào thanh ghi OCS_CR0, 2bit 4:3
Vecto ngắt của nó nằm ở địa chỉ cuối cùng , vào phần boot.asm (boot.tpl) đặt thêm
dòng lệnh: ljmp _sleep_timer_isr vào địa chỉ vecto ngắt cua nó

code trong chương trình


#include <m8c.h>
#define LED1 0x04 // P1_2
#define LED2 0x40 // P1_6
#pragma interrupt_handler SleepISR
BYTE sleepTimer=81;
void main()
{
//Turn on LED1 and LED2
PRT1DR&=~(LED1 | LED2);
INT_MSK0 |= INT_MSK0_GPIO;
M8C_ClearWDTAndSleep;
M8C_EnableIntMask(INT_MSK0, INT_MSK0_SLEEP);
M8C_EnableGInt;
while(1)
{
M8C_Sleep;
//CPU goes to sleep
//Wakes up on sleep timer interrupt
//Toggles LED2, counts down and returns
}

}
/////*******************************/////////////
void SleepISR(void){

PRT1DR^=LED1 ; // Toggle LED1


sleepTimer-=1;
if(sleepTimer==0)
{
M8C_DisableIntMask (INT_MSK0,INT_MSK0_SLEEP);
PRT1DR&=~LED2; // Turn off LED2
}
else
{
M8C_ClearWDTAndSleep; // Reset sleep timer
}
}

Vấn đề 1:
Khi CPU ở trạng thái sleep, ta phải cho phép Sleep_Timer ngắt thì nó mới có
khả năng đánh thức CPU dậy, còn nếu không nó chỉ hoạt động như một timer bình
thường, khác với các Timer khác là 15bit UP_COUNTER Timer, dùng nguồn 32Khz,
45
luôn được Enable
CPU khi ở trạng thái SLEEP sẽ chỉ được đánh thức khi có sự kiện ngắt xảy ra (ngắt ở
đây bao gồm cả WatchDog Reset, POR, XRESET....). Khi thoát khỏi trạng thái
SLEEP,lệnh đầu tiên nó sẽ thực hiện lệnh sẽ là lệnh tiếp theo sau lệnh M8C_Sleep()
do lệnh này được Pre_Fetch trước khi lệnh M8C_Sleep() được thực hiện xong, sau đó
mới đến chương trình phục vụ ngắt. Đúng là nó chỉ vào trạng thái SLEEP khi gặp
lệnh sleep
Vấn đề 2:
WDT (WatchDog TImer) của PSoC dùng để Reset CPU theo một khoảng thời
gian nhất đinh, ở đây thời gian này bằng 3 lần chu kì của Sleep_Timer. Mặc định, sau
khi khởi động WatchDog được Disable. Nếu ta enable thì sau khi Sleep_timer đếm
tràn 3 lần, ở xung clock tiếp theo sau sự kiện này sẽ có tín hiệu Reset ở đầu ra
Terminal Count của WDT, CPU sẽ bị reset và nó được đánh thức chứ không
giốngnhư bác nói về PIC, nó chỉ thoát khỏi trạng thái Sleep mà kô bị RESET...

Vấn đề 3:
Mục tiêu của việc thực hiện Sleep là giảm thiểu công suất trung bình của
nguồn tới mức có thể (tiết kiệm năng lượng). Psoc có 1 chế độ Sleep và có thể được
khởi tạo bằng phần mềm (firmware). Trong trạng thái này, CPU ngừng hoạt động tại
1 câu lệnh biên và các bộ dao động 24/48 MHz, module bộ nhớ Flash và dải điện áp
tham chiều bị tắt nguồn (không hoạt động), chỉ còn bộ dao động 32 Khz (trong hoặc
ngoài), các khối Psoc lấy xung nhịp từ bộ dao động 32 Khz này và mạch giám sát
nguồn là hoạt động.
Đối với các khối Psoc tương tự được thiết lập việc tắt nguồn sử dụng phần mềm thì
hoàn toàn độc lập trong chế độ này. Các khối tương tự ACB có thể vẫn hoạt động vì
chúng không yêu cầu nguồn xung nhịp. Tuy nhiên, các khối ASC, ASD sẽ không hoạt
động vì nguồn xung nhịp nội bộ cấp cho chúng bị ngừng hoạt động
CPU của Psoc có thể tỉnh dậy (wake up) khi xuất hiện ngắt hoặc sự kiện reset
xảy ra. Bộ định thời Sleep (Sleep Timer) có thể cung cấp các ngắt tuần tự để cho phép
hệ thống thức dậy, thăm dò ngoại vi hay thực hiện chức năng thời gian thực và sau đó
lại nhảy vào trạng thái Sleep. Các ngắt GPIO, ngắt giám sát nguồn, ngắt của các cột
tương tự và ngắt của các bộ định thời lấy xung nhịp từ nguồn 32Khz là các ví vụ về
ngắt không đồng bộ có thể cũng được sử dụng để đánh thức hệ thống.
WDT and EEPROM write requires caution. Just prior to using the EEPROM
write function, clear the WDT. If the WDT is set to to anything other than
8Hz then you must also change the sleep timer to 8Hz. The reason is that
the EEPROM write is time critical and requires that the interrupts are
disabled, it also takes around 10mS to execute. This means the WDT
won't be refreshed for 10ms or so. After the EEPROM write perform
another WDT clear. The second is not always required but ensures the
WDT refresh cycle will be met. After the write is performed the sleep
timer can be reset to refresh the WDT at the nominal rate you require.
III.PWM
Ở PSoC chúng ta có thể dùng Timer/Counter/PWM để tạo xung đầu ra có duty
cycle thay đổi được
Với PWM chẳng hạn, nó có 2 đầu ra là Count và TC (Terminal Count). TC chỉ là đầu
ra phụ, nó sẽ được kích lên mức High khi thanh ghi đếm đếm đến 0 và kéo dài trong 1
chu kì clock. Để điều chế độ rộng xung chỉ cần đầu ra Count là đủ. Nạp vào thanh ghi
compare giá trị PulseWidth, sau mỗi sườn lên của xung clock giá trị trong thanh ghi
đếm sẽ bị giảm đi 1 và PWM sẽ tiến hành so sánh giá trị trong thanh ghi đếm với giá
trị trong thanh ghi compare (theo luật less than hoặc less than or equal), khi nào điều
kiện so sánh chưa xảy ra thì xung ở chân COUNT còn ở mức thấp, khi nào điều kiện
46
so sánh xảy ra thì nó sẽ được đưa lên mức cao.Thay đổi giá trị này ta được xung có độ
rộng xung khác nhau (cùng chu kì).
Trong một chu kì có thể thay đổi thanh ghi compare (pulsewidth) bất kì lúc nào 
xung có hình dạng khác nhau.

47
Ví dụ : Để tạo xung vuông có thể cho M=99,N=49 khi đó (N+1)/M+1=1/2 xung
vuông

IV. ng¾t GPIO

code chương trình

#include <m8c.h>
#define LED1 0x04 // P1_2
#define LED2 0x40 // P1_6
#pragma interrupt_handler PSoC_GPIO_ISR
void Delay_e(unsigned int t);
void main()
{

//P16=0,P12=0
PRT1DR&=~(LED1 | LED2);
INT_MSK0 |= INT_MSK0_GPIO;
M8C_EnableGInt;
//Enable global interrupts
48
while(1)
{
M8C_Sleep;
}

///**********************//
void PSoC_GPIO_ISR(void){
unsigned int temp,temp1,temp2;
temp=PRT1DR;
temp&=0x20;
Delay_e(10);
temp1=PRT1DR;
temp1&=0x20;
Delay_e(10);
temp2=PRT1DR;
temp2&=0x20;
if((temp==temp1)&&(temp==temp2)&&(temp==0x20))
{
PRT1DR|=LED2; //tat den xanh
}

}
------------------------------**********************--------------------------------------
Chú ý việc thiết lập cấu hình:

Cách thay đổi nguyên nhân sinh ngắt chân: Ví dụ như đầu tiên thì
đặt nguyên nhân ngắt chân là "rising edge". Sau khi sảy ra ngắt thì thay bằng
"falling edge"
Xem datasheet của nó trang 102, chỗ nói về thanh ghi PRTxICx.
Đây là thanh ghi được dùng để chỉ định kiểu ngắt cho các chân GPIO, có 4 mode:
PRTxIC1 = 0; PRTxIC0 = 0; -> DisableInt
PRTxIC1 = 0; PRTxIC0 = 1; -> FallingEdge

49
PRTxIC1 = 1; PRTxIC0 = 0; -> RisingEdge
PRTxIC1 = 1; PRTxIC0 = 1; -> ChangeFomRead

50
Giới thiệu về PsoC
Giới thiệu
1. Tổng quan hệ thống
2. CPU
3. Khối tạo dao động
4. Công suất tiêu thụ của vi điều khiển
5. Reset.
6. Các chân vào/ra số
7. Các chân vào/ra tương tự
8. Truy nhập vào các khối chức năng số lập trình được
9. Các khối có chức năng số lập trình được
10.Các khối có chức năng tương tự lập trình được
11.Khối tạo điện áp tham chiếu
12.Chế độ kích
13.Bộ nhân cộng MAC
14.Bộ suy giảm tần số lấy mẫu - Decimator
15.Khối điều khiển I2C (Intel IC Bus)
16.Khối điều khiển ngắt
17.Không gian địa chỉ

Giới thiệu

Khi phát triển các ứng dụng phức tạp, chúng ta thường cần thêm các khối ngoại
vi như bộ khuếch đại thuật toán, các bộ lọc, các bộ định thừoi, mạch logic số, các
khối chuyển đổi AD-DA v.v… Việc thiết lập thêm các khối ngoại vi là một việc khó
khăn, các thành phần mới sẽ chiếm thêm diện tích, yêu cầu phải được xem xét
cẩn thận trong quá trình thiết kế bản mạch in (PCB), tăng công suất tiêu thụ …
Tất cả các yếu tố này ảnh hưởng đáng kể đến giá thành và thời gian phát triển
một dự án.
Sự xuất hiện của PsoC đã giúp cho giấc mơ của các nhà thiết kế trở thành hiện
thực, thiết lập các dự án chỉ trên 1 chip.

PSoC: Programmable System on Chip

PSoC (Programmable System on Chip) giới thiệu một khái niệm hoàn toàn mới
cho các ứng dụng vi điều khiển. So với các vi điều khiển 8-bít tiêu chuẩn, các chip
PsoC có thêm các khối tương tự và số lập trình có khả năng lập trình được, chúng
cho phép việc thiết lập một số lượng lớn các ngoại vi.
Các khối số chứa một số các khối số nhỏ hơn có khả năng lập trình được có thể
được cấu hình cho các ứng dụng khác nhau. Các khối analog được sử dụng cho
việc phát triển các thành phần analog như các bộ lọc tương tự, các bộ so sánh.
Các bộ chuyển đổi AD-DA.

Có một số các họ PsoC khác nhau cho phép bạn lựa chọn phụ thuộc vào yêu cầu
của dự án. Sự khác nhau giữa các họ PsoC là số lượng các khối A/D có thể lập
trình được và số lượng các chân vào ra. Phụ thuộc vào các họ vi điều khiển, PsoC
có thể có từ 4 đến 16 khối số và từ 3 đến 12 khối tương tự có khả năng lập trình
được.

Các đặc điểm của PSoC microcontrollers

Một số đặc tính nổi bật của vi điều khiển - PsoC


- Khối nhân công, bộ nhân cứng 8x8 cho kết quả lưu trong thanh ghi cộng 32 bít
- Có khả năng thay đổi điện áp hoạt động 3.3V đến 5V
- Khả năng cung cấp điện áp thấp 1V
- Khả năng lựa chọn tần số nhờ lập trình.

51
Các khối lập trình cho phép bạn thiết lập :

- Bộ nhớ 16K bytes lập trình được


- 256 bytes RAM
- Chuyển đổi ADC độ phân giả tối đa 14 bít
- Chuyển đổi DAC độ phân giải tối đa 9 bít
- Khuếch đại điện áp lập trình được
- Các bộ lọc và so sánh lập trình được
- Các bộ đình thời và bộ đếm 8-16-32 bít
- Khối tạo mã CRC và mã giả ngẫu nhiên
- Hai khối UART song công
- Các thiết bị SPI
- Lựa chọn các kết nối cho tất cả các chân đầu ra
- Lựa chọn việc kết hợp các khối chức năng
- Lựa chọn cho việc lập trình trên vùng bộ nhớ xác định và ghi có bảo vệ
- Các chân I/O đều có các chế độ Pull up, Pull down, High Z, Strong, hoặc Open
pin state
- I2C Slaver hoặc Master và Multi-Master có tốc độ lên tới 400KHz
- Mạch giám sát tích hợp
- Khối tạo điện áp tham chiếu chính xác
1. Tổng quan hệ thống :

Các vi điều khiển PsoC dựa trên kiến trúc CISC 8-bit. Cấu trúc chung của chúng
bao gồm các khối sau đây :

Khối CPU : là trung tâm của vi điều khiển có chức năng thực hiện lệnh và điều
khiển chu trình hoạt động (workflow) của các khối chức năng khác

Khối tạo tần số dao động : tạo ra các tần số thích hợp cung cấp cho CPU hoạt
động cũng như cung cấp một tập hợp các tần số khác nhau cho các khối có chức

52
năng lập trình được. Các tần số được tạo ra dựa trên tần số tham chiếu bên trong
PsoC hoặc được cung cấp từ bên ngoài PsoC.

Khối điều khiển Reset : kích hoạt cho vi điều khiển hoạt động cũng như giúp
hồi phục trạng thái hoạt động bình thường của VDK khi xảy ra lỗi.

Bộ định thời Watch-Dog : được sử dụng để phát hiện ra các vòng lặp vô hạn
trong chương trình.

Bộ định thời Sleep : có thể kích hoạt vi điều khiển theo chu kì để thoát ra khỏi
chế độ tiết kiệm công suất. Nó cũng có thể được sử dụng như một bộ định thời
thông thường.

Các chân vào/ra : giúp cho việc giao tiếp giữa CPU và các khối chức năng
số/tương tự lập trình được cũng như giao tiếp với ngoại vi.

Khối chức năng số : có khả năng lập trình được cho phép người sử dụng tự cấu
hình nên các thành phần số tùy biến.

Khối chức năng tương tự : có khả năng lập trình được cho phép người sử dụng
tự cấu hình nên các thành phần tương tự như các bộ chuyển đổi dữ liệu AD/DA,
các bộ lọc, bộ thu nhận mã đa tần rời rạc DTMF, bộ đảo, các bộ khuếch đại thuật
toán OA.

Khối điều khiển ngắt : có chức năng xử lý các yêu cầu ngắt trong trường hợp
cần thiết.

Khối điều khiển I2C : giúp cho PsoC giao tiếp với các phần cứng khác theo
chuyẩn I2C

Khối tạo điện áp tham chiếu : cần thiết cho các thành phần analog và nằm bên
trong các khối tương tự có khả năng lập trình được.

Bộ nhân tổng MAC : thực hiện các phép nhân có dấu 8 bít

Hệ thống SMP : có thể được sử dụng như 1 phần của bộ chuyển dổi điện áp. Ví
dụ, nó có thể cung cấp công suất cho 1 VDK hoạt động chỉ bằng 1 pin 1.5V duy
nhất.
2. CPU

Trong suốt quá trình thực hiện CT, các lệnh được nap trong bộ nhớ chương trình
(bộ nhớ nhanh dạng flash) giống như các VDK thông thường. CPU tìm nạp 1 lệnh
tại 1 thời điểm từ bộ nhớ CT, giải mã lệnh và thực hiện các chức năng tương ứng.
CPU có 5 thanh ghi trong là PC (Program Counter- Thanh ghi đếm CT) , SP(Stack
Pointer- Thanh ghi con trỏ stack), A(Accumulator-Thanh ghi tích lũy), X(Index-
Thanh ghi chỉ số), và F(Flag-Thanh ghi cờ trạng thái) được sử dụng bởi ALU và
khối giải mã lệnh, chúng cũng được sử dụng kết hợp trong quá trình thực hiện
lệnh.

53
Các thanh ghi trong của CPU

Thanh ghi đếm CT - Program counter (PC) : đuợc dùng như 1 con trỏ lưu trữ
địa chỉ của lệnh sẽ được thực hiên tiếp theo. Với mỗi một câu lệnh mới, giá trị của
PC sẽ trỏ vào địa chỉ của lệnh tiếp theo trong bộ nhớ CT, lệnh này sẽ được giải
mã và thực thi.

Thanh ghi con trỏ stack - Stack pointer (SP) : lưu trữ địa chỉ của bộ nhớ
RAM, là nơi mà dữ liệu được ghi vào hoặc đọc ra nhờ các lệnh PUSH và POP tương
ứng. Khi những lệnh này được thực hiện, giá trị của SP sẽ tự động tăng hoặc giảm
tương ứng.

Thanh ghi tích lũy - Accumulator register (A) : là thanh ghi chính được dùng
trong các thuật toán, các phép toán logic hoặc trao đổi dữ liệu.

Thanh ghi chỉ số - Index register (X) : có thể được sử dụng như thanh ghi tích
lũy trong một số lớn các lệnh. Thanh ghi chỉ số X cũng được sử dụng để lưu trữ
chỉ số địa chỉ (chỉ số trong các vòng lặp)

Thanh ghi cờ trạng thái - Flag register (F) : Các bít của thanh ghi này mô tả
các kết quả sau khi một lệnh được thực hiện. Nó có 1 vai trò trong việc lựa chọn 1
trang(page) bộ nhớ RAM khi vi điều khiển PsoC có nhiều hơn 256 byte RAM. Bít
trạng thái Zero(Z) chỉ ra thanh ghi tích lũy lưu giữ giá trị 0, trong khi bít nhớ
Carry(C) chỉ ra rằng các phép toán logic hoặc các thuật toán được thực hiện có
nhớ dữ liệu.

Đơn vị toán học và logic - Arithmetic logic unit (ALU) : Là thành phần chuẩn
hóa của CPU, được sử dụng để thực hiện các phép toán +, -, dịch trái/phải cũng
như các phép toán logic. Dữ liệu xử lý bởi các lệnh này có thể được lưu trong các
thanh ghi trong A , X hoăck bộ nhớ RAM trong.

Lưu ý : PSoC chỉ có 5 thanh ghi nhưng rất linh hoạt khi lập trình do PSoC
có RAM nội thời gian truy xuất nhanh cho nên khi thực hiện trao đổi dữ
liệu có thể thực hiện lưu trữ/hoặc truy xuất trực tiếp vào RAM nội theo
các mode truy xuất địa chỉ mà vẫn đạt được hiệu suất mong muốn.

3. Khối tạo tần số dao động


Khối tạo tần số dao động là cần thiết cho sự hoạt động cỷa CPU cũng như các
khối có chức năng lập trình được. Mỗi một thành phần lập trình được yêu cầu một
tần số hoạt động riêng biệt.PSoC có một hệ thống dùng để tạo ra các tần số dao
động khác nhau, bằng cách lựa chọn các tham số tương ứng. Sơ đồ dưới đây thể
hiện hai hệ thống độc lập dùng để tạo ra hai tín hiệu SYSCLK và CLK32 (32Khz)

54
+ SYSCLK là dao động nội chủ chốt với tốc độ 24MHz, được sử dụng làm tần số
tham chiếu cho phần lớn các tín hiệu khác.

+ SYSCLKx2 = 2x SYSCLK = 48Mhz

+ 24V1 = SYSCLK/N1 với N1 là tham số lựa chọn trong khoảng từ 1 đến 16.
Do vậy 24V1 nằm trong khoảng từ 1.5MHz (N1=16) tới 24MHz (N1=1).

+ 24V2 = SYSCLK/(N1xN2) với (N1xN2) là tham số lựa chọn trong khoảng từ 1


Do vậy 24V1 nằm trong khoảng từ 93.75kHz (N1xN2=16) tới 24MHz (N1xN2=1).
+ 24V3 = (24V2, 24V1, SYSCLK hoặc SYSCLKx2)/N với N từ 1 đến 256.

+ CPU_CLK cung cấp tần số dao động cho CPU ảnh hưởng trực tiếp đến tốc độ
thực hiện lệnh. CPU_CLK được lựa chọn là một trong 8 tần số trong khoảng từ
93.75MHz cho tới 24MHz.

Các tần số 24V1, 24V2, 24V3 và CPUCLK có thể được thiết lập một cách dễ dàng
thông qua việc thiết lập các tham số tương ứng trong Device Editor hoặc trong
suốt quá trình thực hiện chương trình bằng cách thay đổi 3 bí thấp nhất trong
thanh ghi OSCCR0.

CLK32 là tín hiệu tần số thấp được sử dụng cho các khối có chức năng lập trình
được sử dụng cho hoạt động "wake-up" của bộ định thời Sleep trong trường hợp
các tín hiệu SYSCLK khác là không tích cực

Tín hiệu SYSCLK có thể được tạo ra nhờ một bộ dao động chủ bên trong IMO-
internal main oscillator trong khi CLK32 có thể được tạo ra nhờ dao động cục bộ
bên trong ILO- internal local

Sai số giới hạn đối với bộ tạo dao động trong là 2.5%. Do vậy đối với các ứng
dụng yêu cầu chính xác về thời gian ,tín hiệu SYSCLK nên được cung cấp từ một
dao động tham chiếu bên ngoài, dao động ngoài này nằm trong khoảng từ 1 tới
24 Mhz và được cung cấp qua chân P1[4] của PSoC. Tương tự đối với tín hiệu
CLK32 cũng có thể được tạo ra bằng 1 dao động tham chiếu ngoài có độ chính
xác phù hợp với yêu cầu thiết kế.

55
4. Microcontroller power consumption
PSoC thực hiện lệnh với tốc độ xấp xỉ gấp hai lần tần số được cung cấp trực tiếp
bởi CPUCLK.Mặc dù vậy việc cung cấp tần số hoạt động cao hơn không phải là
luôn luôn cần thiết và có ý nghĩa sẽ đạt hiệu suất tổng thể tốt hơn.
Nhược điểm chính của việc tăng tần số hoạt động chính là hiện tượng tăng công
suất tiêu thụ, đây là vấn đề chính ảnh hưởng tới việc cung cấp nguồn hoạt động.
Một nhược điểm khác của việc tăng tần số hoạt động chính là sự gia tăng của
nhiễu điện từ, gây ảnh hưởng tới các thiết bị xung quanh. Do vậy chúng ta cần sử
dụng 1 tần số thấp nhất nhưng vẫn đáp ứng đủ yêu cầu về tốc độ cho ứng dụng
của chúng ta.
Tần số mặc định cho VDK của PSoC là 3MHz đây là một giá trị thích hợp đối với
yêu cầu tốc độ cũng như công suất tiêu thụ. Để duy trì lâu nhất thời gian hoạt
động nhằm tiết kiệm công suất tiêu thụ do phần lớn các VDK chỉ hoạt động theo
chu kì, việc tiết kiệm công suất tiêu thụ là cần thiết và có thể đạt được nhờ việc
bắt "VDK" rơi vào chế độ "ngủ đông" (Sleep mode) mỗi khi VDK không giữ vai trò
quan trọng (ví dụ : khi VDK không xử lý dữ liệu, trao đổi với bộ nhớ dùng
DMA ...)
Việc tiết kiệm công suất tiêu thụ có thể được áp dụng cho mọi tần số khi CPU
ngừng thực hiện lệnh, đồng thời CPU32 và SLEEP là không tích cực. Vi điều khiển
được "đánh thức" (wake-up) khỏi chế Sleep bằng cách Resset hoặc bằng 1 ngắt
được tạo ra bởi bộ định thời Sleep hoặc 1 khối số có sử dụng tần số CPU32K.
Các chân GPIO (General Purpose In/Out) cũng có thể được sử dụng để đánh thức
CPU. Bộ định thời Sleep biểu hiện 1 bộ nhớ đặc biệt có vai trò chủ đạo trong việc
tạo ra một ngắt có chu kì có khả năng "đánh thức" CPU ra khỏi chế độ tiết kiệm
công suất. Tần số của ngắt tạo bởi bộ định thời Sleep nằm trong khoảng từ 1 tới
512 KHz.
Sau khi "đánh thức" VDK có thể thực hiện các lệnh bình thường cho tới khi chu kì
"ngủ đông" tiếp theo và chờ một ngắt "đánh thức" khác. Chỉ có 1 kiểu ngắt phù
hợp cho việc đánh thức VDK khỏi chế độ "ngủ đông" Sleep

5. Reset
POR
Trong quá trình VDK hoạt động, sự thay đổi điện áp cung cấp luôn diễn ra. Điều
này rất nguy hiểm nếu như điện áp cung cấp thấp hơn 1 giới hạn xác định, lúc
này VDK có những hoạt động không thể dự đoán được. Trong những trường hợp
phát hiện điến áp cung cấp nhỏ hơn giới hạn cho phép, VDK được chuyển tới
Power trong chế độ Reset và giữ nguyên ở chế độ này cho tới khi điển áp ổn định
nằm trên mức giới hạn, mức giới hạn này có thể được định nghĩa nhờ tham số
Trip Voltage

XRES
Tín hiệu reset ngoài cho phép người sử dụng thiết lập cho VDK vào trạng thái khởi
động thông qua một phím nhấn. Hoạt động Reset đạt được khi tín hiệu XRES

56
mang giá trị "1". Mạch reset đơn giản có thể được thiết kế bằng các điện trở pull-

down và 1 chuyển mạch.

WDR
Tín hiệu khởi tạo lại Watch dog reset (WDR) được dùng để tránh các vòng lặp vô
hạn trong phần mềm hoặc các chương trình sai sót nghiêm trọng, giúp cho hệ
thống quay trở lại từ chế độ bắt đầu (start state).
Tín hiệu WDR được tạo ra từ bộ định thời Watch dog timer (WDT) được khởi động
lại theo chu kì bên trong một chương trình chính, sau đó các chương trình con
tương ứng được thực hiện.
Trong chế độ bình thường (normal mode) sau một thời gian nhất định, WDT được
khởi động lại một lần và chương trình con vẫn tiếp tục thực hiện, nhưng nếu một
khối lệnh trong 1 chương trình con có sai sót WDT không thể reset, và WDR xảy
ra.
6. Vào/ra số
PsoC giao tiếp với các ngoại vi thông qua các chân vào ra In/Out. Cứ 8 chân hợp
thành 1 group có thê được truy nhập tức thời như các thành phần của 1 cổng.
Mặc dù vậy, các cổng có số hiệu khác nhau tùy thuộc vào loại PsoC mà chúng ta
sử dụng.

Thao tác đọc và ghi dữ liệu được thực hiện giống nhau trong mọi trường hợp. Các
thanh ghi truy nhập của các cổng được lưu trữ bên trong không gian địa chỉ thanh
ghi với định danh là PRT0DR, PRT1DR, PRT2DR, PRT3DR, PRT4DR or PRT5DR.

57
* Ghi dữ liệu qua cổng
- Giá trị cần ghi được ghi vào thanh ghi PRTxDR thông qua việc thiết lập giá trị
tương ứng cho thanh ghi nhờ sử dụng một mạch khởi tạo điều khiển các trang
thái cho các chân của cổng. Mạch khởi tạo này có thể gửi dữ liệu trực tiếp
(strong), thông qua các điện trở pull-up hoặc pull-down hoăc kênh máng hở ở đầu
ra
- Bên cạnh đó, có khả năng cách ly giá trị thanh ghi khỏi trạng thái của các chân
(Hi-Z)

* Đọc dữ liệu từ cổng


- Giá trị đọc được từ địa chỉ thanh ghi PRTxDR được lưu trữ vào thanh ghi A.

* Drive Mode
Có 8 mode cùng để kết nôi các thanh ghi với các chân thuộc cổng được lựa chon
thông qua 3 bít PRTxDM2, PRTxDM1 and PRTxDM0 ứng với các thanh ghi PRTxDR
tương ứng

+ Strong mode : được dùng khi cần kết nối trạng thái trong các thanh ghi
PRTxDR trực tiếp tới các chân của cổng. Cách này được sử dụng khi chân của
cổng là đầu vào.

+ Analog Hi-Z mode :được sử dụng khi kết nối với các tín hiệu analog như các
đầu vào của ADC. Trong trường hợp này, tất cả các liên kết trong giữa các thanh
ghi PRTxDR và chân bị tách rời do vậy tránh được nhiễu

58
+ Điện trở Pull-up hoặc pull-down : được sử dụng khi kết nối với phím bấm hoặc
các thiết bị khác. Những điện trở này xác định giá trị trên các đầu vào khi phím
bấm chưa được nhấn.
7. Vào/ra tương tự
Một số chân vào/ra bên cạnh các chức năng tiêu chuẩn còn có các chức năng trao
đổi dữ liệu vào ra dạng analog. Các chân của cổng P0 và 4 chân nhỏ nhất của
công P2 co thể được sử dụng để nhận tín hiệu analog. Các đầu vào của cổng P0
được kết nối tới các khối analog thông qua các bộ ghép kênh analog trong khi 4
chân nhỏ nhất của P2 được kết nối trực tiếp tới các khối chuyển mạch tụ điện(SC-
Switched Capacitor) lập trình được.

Các chân P2[4] và P2[6] có thể nhận giá trị điện áp tham chiếu từ bên ngoài. Các
chân đầu ra từ các khối analog có thể được kết nối tới 4 bộ đệm đầu ra, chúng
được kết nối tới các chân to P0[2],P0[3],P0[4], và P0[5] ( 4 chân này có chức
năng In/Out trong khi P0[0],P0[1],P0[6], và P0[7] chỉ có thể là input)

1.9 Các đường tín hiệu vào dùng chung (GIL)


Global input lines (GIL) : Có chức năng kết nối các chân input với đầu vào của các
Mux. GIL được chia thành hai nhóm chẵn (Global input odd – GIO) và (Global
input even – GIE) phụ thuộc vào chỉ số của cổng kết nối với Mux, theo nguyên tắc
cùng chỉ số chân. Nghĩa là đường dẫn GIO_0 có thể kết nối với chân số 0 của tất
cả các cổng có chỉ số cổng là lẻ như : P1[0], P3[0], P5[0]..

59
Ghép nối với Mux

Các bộ Mux được ghép nối với GIO và GIE theo hình vẽ dưới đây

1.10 Các khối số lập trình được


Các khối số lập trình được có thể được cấu hình thành các bộ định thời-Timer, bộ
đếm-counter, điều chế độ rộng xung – PWM, bộ tọa mã PRS (Pseudo Reed-
Solomon)-CRC và các giao tiếp ngoại vi như SPI, IrDA, UART tùy theo yêu cầu và
mục đích của người thiết kế.

60
Chức năng của từng khối số lập trình được liệt kê theo bảng sau :

Tần số giữ nhịp (CLK) :


Tần số giữ nhịp là cần thiết cho mọi thành phần tín hiệu số, phụ thuộc vào tốc độ
yêu cầu, chúng ta có một tập hợp các tần số để lựa chọn

- Các tần số dao động nội : VC1, VC2, VC3, SYSCLKx2, CPU_32
- Các dao động từ các khối liên quan : như Timer, Counter, PWM …
- Tín hiệu Broadcast (BC)
- Các chân tín hiệu vào RI và ra RO

Đầu vào của các thành phần :

Phần lớn các thành phần tín hiệu số bên cạnh tần số giữ nhịp còn có 1 hoặc hai
đầu vào số. Ví dụ trong trường hợp của countẻ và PWM, tín hiệu đầu vào được sử
dụng để khởi tạo bộ đếm. Có một vài khả năng khác nhau cho việc lựa chọn đầu
vào cho các thành phần
- Các chân RI (tín hiệu ngoài)
- Các chân RO (khi các khối được kết nối liên tiếp)
- Đầu ra từ các bộ so sánh analog.
- Các tín hiệu logic 0 (GND),1(VDD)

Đầu ra của các thành phần :


Các đầu ra số của các thành phần tín hiệu số được sử dụng để kết nối các khối lập
trình được với các chân tín hiệu ra RO.

Bộ ghép kênh - Multiplexer


Phụ thuộc vào trạng thái của Mux (địa chỉ) các chân tín hiệu ra RO hoặc các chân
tín hiệu vào RI của các khối lập trình được có thể được kết nối với nhau.

Mạch Logic
Các mạch logic có thể là :
- Lựa chọn 1 trong hai tín hiệu làm đầu ra
- Cổng NOT
- Thực hiện các phép toán logic AND, OR, XOR

61
Mạch điều khiển tín hiệu ra
Đầu ra của các mạch logic có thể được kết với 4 mạch điều khiển đầu ra, chúng
được kết nối tới 1 hoặc nhiều các đường tín hiệu GOL(global output lines )
Đầu ra của các khối lập trình được cũng được đánh chỉ số, do đó nó chỉ kết nối với
các chân GOO hoặc GOI cùng chỉ số hoặc có chỉ số lớn hơn 4 đơn vị so với chúng.

62

Das könnte Ihnen auch gefallen