SlideShare a Scribd company logo
50 Everyday Practical Electronics, November 2009
Teach-In 2010
By Walter Ditch
TEACH-IN 2010
LADDER LOGIC PROGRAMMING
FOR THE PIC MICRO
Part 1: Getting Started –
Working with Inputs and
Outputs
T
HIS IS THE ÚRST OF A SERIES OF SIX
ARTICLES
WHICH WILL SHOW YOU
HOW TO PROGRAM A VARIETY OF 0)#
MICROCONTROLLERS USING AN APPROACH
KNOWN AS LADDER LOGIC
7HY LADDER LOGIC 7ELL
THIS IS
THE PREFERRED SOFTWARE DEVELOPMENT
METHOD FOR A TYPE OF COMPUTER KNOWN
AS A 0,#
OR 0ROGRAMMABLE ,OGIC
#ONTROLLER 0,#S ARE RUGGED COM-
PUTERS
WHICH ARE COMMONLY USED
IN INDUSTRY TO CONTROL PRODUCTION
LINE OPERATIONS AND PROCESSES 4HEY
ARE DESIGNED TO BE EASILY CONÚGURED
AND USED BY ENGINEERS
TYPICALLY TO
PERFORM SIMPLE LOGICAL TASKS AND
SEQUENCES
,ADDER LOGIC HAS HISTORICALLY
PROVED VERY POPULAR WITH ELECTRICAL
ENGINEERS
SINCE IT ALLOWS CONTROL
ORIENTED SOFTWARE TO BE CREATED BY
LINKING TOGETHER lELECTRICALm ELEMENTS
SUCH AS INPUTS
OUTPUTS
LATCHES
COUNTERS
TIMERS
SHIFT REGISTERS AND
SEQUENCERS !S WEmLL SEE IN THIS SERIES
THE APPROACH IS QUITE INTUITIVE FOR
THOSE FROM AN ELECTRICAL OR ELECTRONIC
BACKGROUND
SINCE THE INDIVIDUAL
PROGRAMMING ELEMENTS ARE ALREADY
WELL UNDERSTOOD 4HE RESULTING SOURCE
CODE PROGRAMS ALSO TEND TO BE QUITE
SHORT AND EASY TO INTERPRET
4HIS ÚRST INSTALLMENT OF THE SERIES
CONCENTRATES ON DEVELOPING SIMPLE
0,#
STYLE PROGRAMS TO READ INPUTS
AND TO CONTROL OUTPUTS 7EmLL LOOK
AT THE GRAPHICAL REPRESENTATION OF A
CONTROL
ORIENTED SYSTEM USING A LAD-
DER DIAGRAM
AND ITS CONVERSION TO A
SOURCE CODE ÚLE
7EmLL THEN WORK THROUGH THE DE-
TAILED STEPS INVOLVED IN CREATING AND
TESTING 0,#
STYLE APPLICATIONS
USING A
VARIETY OF WIDELY AVAILABLE 0)#
BASED
HARDWARE AND SOFTWARE 4HE INTERNAL
METHOD OF OPERATION OF THE SUPPLIED
SOFTWARE WILL ALSO BE DISCUSSED
ENA-
BLING YOU TO DECIDE FOR YOURSELF WHEN
AND WHERE THIS APPROACH MIGHT BE
APPLICABLE
3UBSEQUENT PARTS OF THE SERIES WILL
INTRODUCE FURTHER SOFTWARE FEATURES
AND APPLICATIONS
INCLUDING
3IMPLE COMBINATIONAL AND SE-
QUENTIAL LOGIC LOGIC GATES AND LATCHES
4IMERS AND SHIFT REGISTERS
#OUNTERS AND PULSE
WIDTH
MODULATED 07- OUTPUTS
3EQUENCERS AND BYTE
ORIENTED
INSTRUCTIONS
! VARIETY OF MICROCONTROLLER
BASED
APPLICATIONS OF LADDER LOGIC WILL ALSO
BE DEVELOPED
INCLUDING ALARMS
MOTOR
CONTROLLERS
ROBOTICS
AND SEQUENCE
BASED SYSTEMS
4HE SOFTWARE SUPPLIED WITH THE
SERIES HAS BEEN PLACED INTO THE PUBLIC
DOMAIN BY THE AUTHOR
AND SO IS FREE
FOR YOU TO USE )T CURRENTLY WORKS WITH
ÚVE DIFFERENT 0)# MICROS 
!
!
AND
PLUS THE FOLLOWING COM-
MONLY AVAILABLE HARDWARESOFTWARE
PLATFORMS
 6ELLEMAN + 0ROGRAMMING
AND %XPERIMENTATION OARD
AVAILABLE
FROM A NUMBER OF MAIL ORDER SUPPLIERS
 0)#KIT4-  $EBUG %XPRESS
OARD
SUPPLIED BY -ICROCHIPDIRECT
www.microchipdirect.com
 -ATRIX -ULTIMEDIA 6ERSION 
0)#MICRO -#5 $EVELOPMENT OARD
AVAILABLE FROM THE Everyday Practical
Electronics EPE 2EADERS 3ERVICES
 0ROTEUS 63- ELECTRONIC CIRCUIT
SIMULATION SOFTWARE FROM ,ABCENTER
%LECTRONICS www.labcenter.co.uk 
(OPEFULLY
YOU WILL HAVE ACCESS TO
ONE OF THE ABOVE AND WILL BE ABLE TO
WORK ALONG WITH THE SERIES 3EEING
REALLY IS BELIEVING
AND THE BEST WAY
TO LEARN IS TO TRY THE CONCEPTS OUT FOR
YOURSELF )F YOU DO
) GUARANTEE YOUmLL
BE SURPRISED BY THE POWER AND SIMPLIC-
ITY OF LADDER LOGICØ
Comparing PLCs and
microcontrollers
4HE MAIN DIFFERENCES BETWEEN A
0,# AND A MICROCONTROLLER RELATE TO
Everyday Practical Electronics, November 2009 51
Teach-In 2010
size, complexity and, of course, cost.
The inputs and outputs circuits of
a PLC, for example, are extremely
rugged, with digital inputs often be-
ing connected via opto-isolators, and
digital output types including transis-
tor, thyristor, triac and relay. This al-
lows the PLC to directly control high
power devices, such as motors, pneu-
matic actuators and the like. A typical
implement combinational and se-
quential logic functions in electrical
control circuits, and it is in part this
electrical basis which makes it easy
for electrical engineers to understand
– even those without a computing
background. Consider, for example, a
simple electrical circuit consisting of
a switch and a lamp, and also its rep-
resentation using a ladder diagram, as
shown in Fig.1.2.
Considering the circuit on the left,
closing the switch will clearly cause
the lamp to light. The ladder diagram
on the right is equivalent, consisting
of a pair of vertical power rails, with
one or more horizontal ‘rungs’. (The
ladder-like appearance gives this
type of diagram its name.) Closing the
normally open switch contacts on the
left of the ladder diagram will con-
nect power through the horizontal
rung, hence lighting the lamp.
Historically, the output would
typically have been a relay coil, thus
allowing a relatively low voltage
control circuit to switch mains oper-
ated power devices. For this reason,
PLC inputs are often referred to as
contacts, while outputs are called
coils. It can be seen from the ladder
diagram that an output coil is rep-
resented graphically using a pair of
curved braces (although a circular
output symbol is sometimes seen).
This extremely simple concept is
the basis of PLC operation, and in part
explains why electrical engineers are
so comfortable writing PLC programs.
This added complexity is avoid-
ed here by the pre-configuration
of default settings, such as port
directions, in the supplied PLC header
ÚLES OR EXAMPLE
IN THE 0)#
VERSION
0ORT ! IS CONÚGURED TO BE AN
input, while Port B is an output.) You
can, of course, change these settings,
simply by editing the relevant section
OF THE HEADER ÚLE
BUT THE SOFTWARE IS
commerciallyavailablePLCisshownin
Fig.1.1, with input connections shown
at the top and outputs at the bottom.
While the I/O connections of a mi-
crocontroller operate at much lower
voltage and current than those of a
PLC, they are essentially the same from
a software point of view. The internal
structure of a microcontroller also
contains many similar elements to
those found inside a PLC, including a
central processing unit, program mem-
ory (ROM), together with a variety of
volatile and non-volatile data memory
types. (The content of volatile memory
types, such as static RAM, is lost when
power is removed, while non-volatile
memory,suchasEEPROM,isretained.)
The allocation of connections as in-
puts or outputs is, of course, pre-deter-
mined by the PLC manufacturer, since
this is a pre-requisite for the connection
of specialised interface circuitry. Not so
inthemicrocontrollerworld,wherethe
assembly language programmer nor-
mally has to decide on port directions,
PLUS A VARIETY OF OTHER CONÚGURATION
settings, prior to actually getting the
microcontrollertodosomethinguseful.
designed to work straight out of the
BOX
WITHOUT ANY NEED FOR CONÚGURA-
tion – just like a real PLC.
So, having established that PLCs
and microcontrollers have a lot in
Fig.1.1. A typical industrial PLC
Fig.1.2. A simple switch and lamp circuit (left) and its equivalent ladder
diagram (right)
common, let’s turn our attention to lad-
DER LOGIC
AND ÚND OUT WHAT IT HAS TO
offer in terms of software development.
Ladder diagrams and ladder
logic
Ladder logic owes its origin to
the use of switches and relays to
Ladder logic programs are also very
concise, with a section of code to (1)
read an input and then (2) control a
linked output requiring as little as
two lines of code. Listing 1.1 shows
a possible implementation.
In general, a PLC program is cre-
ated by converting each input contact
52 Everyday Practical Electronics, November 2009
Teach-In 2010
and output coil of the system’s ladder
diagram into a series of equivalent
program statements. Execution of the
program is then a continuously operat-
ing sequence of:
Reading inputs
Performing logic-based
calculations
Controlling outputs
This repeating process is known as
the scan cycle, and is shown graphi-
cally for a slightly more complex
example in Fig.1.3.
It can be seen that each rung of the
ladder diagram is evaluated from left
to right, starting at the top rung and
working progressively down (Steps 1
and 2 of Fig.1.3). The End of Program
A number of conclusions may be
immediately drawn from this method
of operation:
1. Execution of a PLC program con-
sists of a continuously operating pro-
gramloop(arepeatingscancycle),even
though this is not explicitly shown in
the program listing or ladder diagram.
2. The time taken for a single scan
cycle will increase in line with the
complexity of the program, since the
execution time for a single instruction
IS ÚXED BY THE MICROPROCESSOR CLOCK
frequency.
Slightly less obviously:
3. An externally applied input signal
WILL NEED TO BE PRESENT FOR A SUFÚCIENT
time to guarantee it being ‘seen’ by
the input phase of the
scanning loop.
4. The average time
taken to react to a
changing input is re-
lated to the scanning
loop duration.
5. It may take more
than one scanning
loop for the results of
complex calculations
to fully propagate
through the system.
This may lead to the
possibility of transient
glitches as calcula-
tions ‘ripple-though’.
In practice, you
SHOULD ÚND THAT LAD-
der logic solutions are
suitableinthemajority
of logic-based control
scenarios, since the computer is typi-
cally operating at much higher speed
than the system being controlled.
Now that the basic principles of
ladder logic programming have been
covered, the next step is to obtain the
required software, which will then
enable us to create and test an execut-
able program.
Obtaining the software
The ladder logic software is designed
to work with the MPLAB Integrated De-
velopmentEnvironment(IDE),whichis
freely available for download from the
Microchip website (www.microchip.
com),oronCD-Rom.Allthatisrequired
is to include a link to the appropriate
HEADER ÚLE FROM WITHIN THE ASSEMBLY
LANGUAGE SOURCE ÚLE
AT WHICH POINT A
variety of PLC-style commands become
available for use in your programs.
As mentioned earlier, versions of the
software are available for the following
commonly used PIC microcontrollers:
PIC16F627/PIC16F627A (head-
ER ÚLE l0,#m
PIC16F628/PIC16F628A (head-
ER ÚLE l0,#m
0)# HEADER ÚLE l
PLC’)
PIC16F88 (header files
‘16F88_L.PLC’ and ‘16F88_H.PLC’
offer low voltage and high voltage
program versions respectively)
0)# HEADER ÚLE l
PLC’)
)N PRACTICE
THE ÚRST FOUR OF THESE
are all 18-pin ICs, differing mainly in
THE QUANTITY OF ÛASH
BASED PROGRAM
memory, static RAM, or EEPROM-
based non-volatile data memory. The
PIC16F887 is a 44-pin IC, having
enhanced input/output capabilities.
These features are summarised in
Table 1.1.
Inclusion of the appropriate
header file will cause a number of
default settings to be chosen, such
as port directions, oscillator type
and so on. These settings have been
tested with a number of hardware
configurations, and are intended
to simplify the configuration proc-
ess as far as possible. (You should
of course review these settings to
ensure compatibility with your own
requirements.) Default options are
summarised in Table 1.2.
A number of required files are
available in a compressed ZIP file,
which may be obtained from the the
Library  Project Code section of
the Everyday Practical Electronics
website (www.epemag.com). The
contents of the ZIP file are given in
Table 1.3.
ld SWITCH ; Read state of Switch
out LAMP ; Output to Lamp
Listing 1.1. A notional section of a PLC program based on the circuit and
ladder diagram of Fig.1.2
Fig.1.3. The repeating scan cycle of a PLC executing
a ladder logic program
statement forces program execution to
RESUME FROM THE BEGINNING OF THE ÚRST
rung (Step 3), causing the program to
run continuously. This program might
be coded using statements such as
those given in Listing 1.2.
ld SWITCH_A ; Read state of Switch A
out LAMP_A ; Output to Lamp A
ld SWITCH_B ; Read state of Switch B
out LAMP_B ; Output to Lamp B
endp ; End of PLC program
Listing 1.2. A PLC program based on the ladder diagram of Fig.1.3
Everyday Practical Electronics, November 2009 53
Teach-In 2010
Filename Description
16F627.PLC PLC header file for the PIC16F627/627A microcontroller
16F628.PLC PLC header file for the PIC16F628/628A microcontroller
16F648.PLC PLC header file for the PIC16F648A microcontroller
16F88_L.PLC PLC header file for the PIC16F88 microcontroller – low voltage
programming enabled on pin RB3
16F88_H.PLC PLC header file for the PIC16F88 microcontroller – high voltage
programming enabled, pin RB3 available for general I/O
16F887.PLC PLC header file for the PIC16F887 microcontroller
PIC16F627.DSN Proteus VSM simulation – PIC16F627A based Digital I/O Board
PIC16F88.DSN Proteus VSM simulation – PIC16F88 based Digital I/O Board
PIC16F887.DSN Proteus VSM simulation – PIC16F887A based Digital I/O Board
Lst1_3.asm Source code file for Listing 1.3
Lst1_4.asm Source code file for Listing 1.4
Lst1_5.asm Source code file for Listing 1.5
Lst1_6.asm Source code file for Listing 1.6
Assembling and execut-
ing simple PLC-style
programs
In this section you will see
just how easy it is to create and
assemble simple programs and
then run them on a variety of
different PIC-based systems. I
recommend that you try these
activities out for yourself, if at
all possible.
Begin by extracting the entire
CONTENTS OF THE :)0 ÚLE TO A CON-
venient folder and then use the
MPLAB IDE’s File  Open menu
OPTION TO DISPLAY THE ÚLE l,ST?
asm’, the content of which is
GIVEN IN ,ISTING 
/UR ÚRST PROGRAM IS FUNCTION-
ally identical to the code snippet
PREVIOUSLY SEEN IN ,ISTING
BUT BASED ON THE 0)#
microcontroller. It is suitable
for use either with the PICkit 2
Debug Express board, or with
Proteus VSM electronic simu-
lation software. (Note that the
PICkit 2 board has a single input
SWITCH
LABELLED 37
WHICH IS
CONNECTED TO THE LEAST SIGNIÚCANT
bit of Port B, plus eight LEDs
connected to Port D – which
explains the choice of inputs
AND OUTPUTS IN ,ISTING 
Having displayed the source
ASM ÚLE IN -0,!
THE NEXT
step is to assemble it, in order
to create a machine code (.hex)
ÚLE
WHICH CAN LATER BE DOWN-
loaded and programmed. The
ÚRST STEP IS TO CHOOSE THE RE-
quired microcontroller type by
selecting the #ONlGUREªª3ELECTª
Device menu option, and then
selecting the PIC16F887 from
the Device drop-down list. Next
click on the blue title bar of the
SOURCE CODE ÚLE TO ENSURE IT IS
highlighted and then assemble
THE ÚLE BY SELECTING THE Project
 Quickbuild Lst1_3.asm menu
option. If everything has gone
TO PLAN YOU SHOULD SEE A ÛURRY
OF ACTIVITY AS THE ÚLE IS ASSEM-
BLED
CULMINATING IN A lUILD
Succeeded’ message, displayed in
the Build tab of the Output window.
The MPLAB IDE has now done its
JOB AND A ,ST?HEX ÚLE WILL HAVE
been created in the same directory
AS THE SOURCE CODE ÚLE
READY TO BE
programmed.
Device Program
(kWords)
RAM
(bytes)
EEPROM
(bytes)
Max I/O
(bits)
Other
Features
PIC16F627 1 224 128 16 2 comparators
PIC16F628 2 224 128 16 2 comparators
PIC16F648 4 256 256 16 2 comparators
PIC16F88 4 368 256 16 2 comparators
7-channel ADC
PIC16F887 8 368 256 35 2 comparators
14-channel ADC
Table 1.1. Major features of supported PIC microcontrollers
Device Inputs Outputs Other Features
PIC16F627 / 628
/ 648
Port A (5 bits) Port B (8 bits) Comparators disabled, pull-ups disabled
4MHz external crystal oscillator selected
Timer 0 configured for use by PLC software
MCLR enabled, Watchdog timer enabled
PIC16F88 Port A (5 bits) Port B (8 bits) Comparators disabled, pull-ups disabled
4MHz external crystal oscillator selected
Timer 0 configured for use by PLC software
MCLR enabled, Watchdog timer enabled
ADC disabled
PIC16F887 Port A (8 bits)
Port B (8 bits)
Port E (4 bits)
Port C (8 bits)
Port D (8 bits)
Comparators disabled, pull-ups disabled
4MHz internal oscillator selected
Timer 0 configured for use by PLC software
MCLR disabled, Watchdog timer enabled
ADC disabled
4ABLEªª$EFAULTª0)#ªSOFTWAREªCONlGURATIONªOPTIONS
Table 1.3. File contents of ‘PLC1.zip’
include 16F887.PLC ; Defines PLC instructions
ld PORTB, 0 ; Read Port B bit 0
out PORTD, 0 ; Output to Port D bit 0
endp ; End of PLC program
Listing 1.3. Reading a switch and outputting to an LED (Lst1_3.asm)
54 Everyday Practical Electronics, November 2009
Teach-In 2010
Syntax Function Ladder Diagram Symbol
ld REGISTER, BIT[0-7] Read an I/O bit
ld_not REGISTER, BIT[0-7] Read an I/O bit (inverted)
out REGISTER, BIT[0-7] Send to output bit
out_not REGISTER, BIT[0-7] Send to output bit (inverted)
Table 1.4. Bit input/output commands
Fig.1.4. A Proteus VSM simulation of the PIC16F887 microcontroller
What happens next depends on how
you intend to actually run the program.
If you are using the PICKit 2 board
then the next step is to run the PICkit
2 programmer application, then use
the File  Import Hex menu option
TO OPEN THE MACHINE CODE HEX ÚLE
created earlier. Next, click the Write
button to program the PIC16F887 mi-
crocontroller. You should see a green
Programming Successful message in
the programmer window at this stage.
Finally, apply power to the board by
clicking the On checkbox situated just
under the VDD PICkit 2 label
at the upper right.
Pressing Switch 1 will
now cause the LED con-
nected to RD0 to toggle on
and off. However, you may
note that the LED actually
goes out when the switch
is pressed, which is the
opposite of what you might
have expected. Examin-
ing the schematic diagram
supplied with the PICkit 2
documentation solves the
mystery, revealing that SW1
normally reads as a logic-1,
providing a logic-0 when
pressed. The required logic of our
program may be easily restored by
replacing the ‘ld’ instruction with its
negative logic ‘ld_not’ equivalent, as
given in Table 1.4.
From Table 1.4, we can also see
that a negative logic output command
Everyday Practical Electronics, November 2009 55
Teach-In 2010
(out_not) is available. Thus, we can
create a logical inversion either by
using ‘ld_not’ followed by ‘out’, or
‘ld’ followed by ‘out_not’. If you are
using the PICkit 2 board, then you
can use this information to modify the
program of Listing 1.3 so that pressing
the switch causes the LED to come on,
rather than go out.
If you are lucky enough to have the
full version of Proteus VSM, Version
7.0 or later, then this may be used to
simulate the operation of the program
of Listing 1.3. Begin by using Proteus
to open the supplied PIC16F887.DSN
ÚLE
WHICH WILL APPEAR AS SHOWN IN
Fig.1.4.
include 16F627.PLC ; Defines PLC instructions
ld PORTA, 0 ; Read Port A bit 0
out PORTB, 0 ; Output to Port B bit 0
ld PORTA, 1 ; Read Port A bit 1
out PORTB, 1 ; Output to Port B bit 1
endp ; End of PLC program
Listing 1.4. Reading and controlling multiple inputs and outputs (Lst1_4.asm)
Controlling multiple inputs
and outputs
To take a slightly more complex
example, suppose we wanted to con-
trol several inputs and outputs. This
could be achieved as illustrated by
Listing 1.4, shown for a PIC16F627-
based system.
Assuming you have a suitable PIC
programmer and experimentation
board, such as the Velleman K8048, the
ÚRST STEP IS TO USE THE -0,! )$% TO
CREATE A MACHINE CODE ÚLE REMEMBER-
ing of course to set the device type to
either the PIC16F627 or PIC16F627A,
as appropriate). Next, connect the
Fig.1.5. The output produced by Listing 1.4, running on a Velleman K8048 board
include 16F887.PLC ; Defines PLC instructions
ld PORTE, 3 ; Read Port E bit 3 (ICSP pin 1)
out PORTD, 3 ; Output to Port D bit 3
ld PORTB, 7 ; Read Port B bit 7 (ICSP pin 4)
out PORTD, 2 ; Output to Port D bit 2
ld PORTB, 6 ; Read Port B bit 6 (ICSP pin 5)
out PORTD, 1 ; Output to Port D bit 1
ld_not PORTB, 0 ; Read Port B bit 0 inverted (SW1)
out PORTD, 0 ; Output to Port D bit 0
endp ; End of PLC program
Listing 1.5. Controlling up to four inputs using the PICkit 2 Debug Express
(Lst1_5.asm)
programmer to your PC via the sup-
plied serial cable and then download
and execute the program. When the
program is executed, pressing a switch
CONNECTED TO THE ÚRST TWO BITS OF 0ORT
A should cause the corresponding bit
of Port B to be activated, as shown in
Fig.1.5.
If you have access to the Proteus
VSM software then you use this to load
the ‘PIC16F627.DSN’ simulation and
then follow the procedure described
earlier to load and execute the program
of Listing 1.4.
Surprisingly, it is also possible to
develop similarly complex programs
for the PICkit 2 Debug Express board,
despite the fact that the PCB is limited
to a single physical input switch! The
trick in this case is to use the PICkit 2
Logic Tool application to control up to
three additional digital input signals
via the In Circuit Serial Programming
(ICSP) interface, which links the ‘black
box’ to the PIC16F887 PCB. When not
being used to download programs,
the Logic tool allows inputs RE3, RB7
and RB6 to be controlled by activating
pins 1, 4 and 5 of the ICSP interface
respectively.
To see this in action for yourself,
begin by assembling the program of
Listing 1.5, and then download the
RESULTING MACHINE CODE ÚLE TO THE
PIC16F887 in the normal way.
Next, enable power to the PCB by
clicking the On check-box and then
select the Tools  Logic Tool option
from the pull-down menu, which will
display the PICkit 2 Logic Tool dialog
of Fig.1.6.
Ensure the Mode option is set to
Logic I/O by clicking the button at the
upper right, and then click the Enable
Our machine code program created
earlier must be logically attached to
the PIC16F887, prior to running the
simulation. To do this, right-click on
component U1 and select the Edit
Properties option from the context
menu to display the Edit Component
dialog. From here, you can click the
YELLOW FOLDER ICON AND BROWSE TO ÚND
THE l,ST?HEXm ÚLE CREATED EARLIER
Close the dialog and then click the Play
button at the lower left of the Proteus
window to run the simulation. You’ll
then be able to click on the input con-
nected to bit 0 of Port B, which should
cause the corresponding bit of Port D
to change (as illustrated by Fig.1.4).

More Related Content

PPTX
An introduction to robotics classification, kinematics and hardware
PDF
ME6601 DESIGN OF TRANSMISSION SYSTEMS TWO MARK QUESTION & ANSWERS
PDF
Spindle Repair & Rebuilding Services
PDF
Gearbox design - MECH 393 final project
PPTX
Shaft.pptx
PDF
Robots dynamics and control
PDF
Initial Guidance to Obtain Representative Meteorological Observations at Urba...
PPTX
Shaft couplings 3 rigid flange coupling
An introduction to robotics classification, kinematics and hardware
ME6601 DESIGN OF TRANSMISSION SYSTEMS TWO MARK QUESTION & ANSWERS
Spindle Repair & Rebuilding Services
Gearbox design - MECH 393 final project
Shaft.pptx
Robots dynamics and control
Initial Guidance to Obtain Representative Meteorological Observations at Urba...
Shaft couplings 3 rigid flange coupling

Viewers also liked (11)

PDF
Ladder logic tutorial
PDF
Ladder logic fundamentals plc tutorial
PPTX
Programmable Logic Controller and ladder logic programming
PPTX
Ladder Logic and Touch Screen PLC Programming Tutorial/Training
PDF
PLC and SCADA training.
PPTX
INDUSTRIAL AUTOMATION USING PLC
PDF
PLC - Programmable Logic Controller
PPTX
PLC LADDER DIAGRAM
PPT
PLC Basic
PPTX
Basics of Automation, PLC and SCADA
PPTX
ppt on PLC
Ladder logic tutorial
Ladder logic fundamentals plc tutorial
Programmable Logic Controller and ladder logic programming
Ladder Logic and Touch Screen PLC Programming Tutorial/Training
PLC and SCADA training.
INDUSTRIAL AUTOMATION USING PLC
PLC - Programmable Logic Controller
PLC LADDER DIAGRAM
PLC Basic
Basics of Automation, PLC and SCADA
ppt on PLC
Ad

Similar to Teach-In : Ladder Logic for PIC Micro (20)

PDF
Plc documentation final
PPT
Programmable_Logic_Controllers_Introduction_to_PLCs__(Chapter_1)_Lec1.ppt
PDF
Plc ppt
PPT
10617568.ppt
PDF
n5acb0f1c011fb.pdf
PDF
IRJET- A Study of Programmable Logic Controllers (PLC) and Graphical User Int...
PPTX
Unit 4 - PLC.pptx
PDF
D. CHAPTER dffrtgfffffffgggfffdddFIVE.pdf
PDF
PLC: Introducción al PLC
PDF
IRJET-A Study of Programmable Logic Controllers (PLC) and Graphical User Inte...
DOCX
Plc notes
PDF
AutomatingManufacturingSystemsWithPLCs.pdf
PDF
Controladores lógicos programables por Frank D. Petruzella.pdf
PDF
Controladores lógicos programables por Frank D. Petruzella.pdf
PPTX
Plc (PROGRAMMABLE LOGIC CONTROLLER)
PDF
Introduction to PLC
PDF
Basic PLC Programming program The Fundamental Knowledge of PLC.pdf
PDF
PDF
PLC-Programmable-Logic-Controller-Book.pdf
PDF
Introduction to automation
Plc documentation final
Programmable_Logic_Controllers_Introduction_to_PLCs__(Chapter_1)_Lec1.ppt
Plc ppt
10617568.ppt
n5acb0f1c011fb.pdf
IRJET- A Study of Programmable Logic Controllers (PLC) and Graphical User Int...
Unit 4 - PLC.pptx
D. CHAPTER dffrtgfffffffgggfffdddFIVE.pdf
PLC: Introducción al PLC
IRJET-A Study of Programmable Logic Controllers (PLC) and Graphical User Inte...
Plc notes
AutomatingManufacturingSystemsWithPLCs.pdf
Controladores lógicos programables por Frank D. Petruzella.pdf
Controladores lógicos programables por Frank D. Petruzella.pdf
Plc (PROGRAMMABLE LOGIC CONTROLLER)
Introduction to PLC
Basic PLC Programming program The Fundamental Knowledge of PLC.pdf
PLC-Programmable-Logic-Controller-Book.pdf
Introduction to automation
Ad

Recently uploaded (20)

PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPT
Mechanical Engineering MATERIALS Selection
PPTX
Welding lecture in detail for understanding
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPTX
Construction Project Organization Group 2.pptx
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPTX
Sustainable Sites - Green Building Construction
PPTX
UNIT 4 Total Quality Management .pptx
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PDF
PPT on Performance Review to get promotions
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PPTX
Internet of Things (IOT) - A guide to understanding
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
Lecture Notes Electrical Wiring System Components
Model Code of Practice - Construction Work - 21102022 .pdf
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Mechanical Engineering MATERIALS Selection
Welding lecture in detail for understanding
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
Construction Project Organization Group 2.pptx
CYBER-CRIMES AND SECURITY A guide to understanding
Sustainable Sites - Green Building Construction
UNIT 4 Total Quality Management .pptx
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPT on Performance Review to get promotions
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
OOP with Java - Java Introduction (Basics)
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
Internet of Things (IOT) - A guide to understanding
Operating System & Kernel Study Guide-1 - converted.pdf
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
Lecture Notes Electrical Wiring System Components

Teach-In : Ladder Logic for PIC Micro

  • 1. 50 Everyday Practical Electronics, November 2009 Teach-In 2010 By Walter Ditch TEACH-IN 2010 LADDER LOGIC PROGRAMMING FOR THE PIC MICRO Part 1: Getting Started – Working with Inputs and Outputs T HIS IS THE ÚRST OF A SERIES OF SIX ARTICLES
  • 2. WHICH WILL SHOW YOU HOW TO PROGRAM A VARIETY OF 0)# MICROCONTROLLERS USING AN APPROACH KNOWN AS LADDER LOGIC 7HY LADDER LOGIC 7ELL
  • 3. THIS IS THE PREFERRED SOFTWARE DEVELOPMENT METHOD FOR A TYPE OF COMPUTER KNOWN AS A 0,#
  • 4. OR 0ROGRAMMABLE ,OGIC #ONTROLLER 0,#S ARE RUGGED COM- PUTERS
  • 5. WHICH ARE COMMONLY USED IN INDUSTRY TO CONTROL PRODUCTION LINE OPERATIONS AND PROCESSES 4HEY ARE DESIGNED TO BE EASILY CONÚGURED AND USED BY ENGINEERS
  • 6. TYPICALLY TO PERFORM SIMPLE LOGICAL TASKS AND SEQUENCES ,ADDER LOGIC HAS HISTORICALLY PROVED VERY POPULAR WITH ELECTRICAL ENGINEERS
  • 7. SINCE IT ALLOWS CONTROL ORIENTED SOFTWARE TO BE CREATED BY LINKING TOGETHER lELECTRICALm ELEMENTS SUCH AS INPUTS
  • 12. SHIFT REGISTERS AND SEQUENCERS !S WEmLL SEE IN THIS SERIES
  • 13. THE APPROACH IS QUITE INTUITIVE FOR THOSE FROM AN ELECTRICAL OR ELECTRONIC BACKGROUND
  • 14. SINCE THE INDIVIDUAL PROGRAMMING ELEMENTS ARE ALREADY WELL UNDERSTOOD 4HE RESULTING SOURCE CODE PROGRAMS ALSO TEND TO BE QUITE SHORT AND EASY TO INTERPRET 4HIS ÚRST INSTALLMENT OF THE SERIES CONCENTRATES ON DEVELOPING SIMPLE 0,# STYLE PROGRAMS TO READ INPUTS AND TO CONTROL OUTPUTS 7EmLL LOOK AT THE GRAPHICAL REPRESENTATION OF A CONTROL ORIENTED SYSTEM USING A LAD- DER DIAGRAM
  • 15. AND ITS CONVERSION TO A SOURCE CODE ÚLE 7EmLL THEN WORK THROUGH THE DE- TAILED STEPS INVOLVED IN CREATING AND TESTING 0,# STYLE APPLICATIONS
  • 16. USING A VARIETY OF WIDELY AVAILABLE 0)# BASED HARDWARE AND SOFTWARE 4HE INTERNAL METHOD OF OPERATION OF THE SUPPLIED SOFTWARE WILL ALSO BE DISCUSSED
  • 17. ENA- BLING YOU TO DECIDE FOR YOURSELF WHEN AND WHERE THIS APPROACH MIGHT BE APPLICABLE 3UBSEQUENT PARTS OF THE SERIES WILL INTRODUCE FURTHER SOFTWARE FEATURES AND APPLICATIONS
  • 18. INCLUDING 3IMPLE COMBINATIONAL AND SE- QUENTIAL LOGIC LOGIC GATES AND LATCHES 4IMERS AND SHIFT REGISTERS #OUNTERS AND PULSE WIDTH MODULATED 07- OUTPUTS 3EQUENCERS AND BYTE ORIENTED INSTRUCTIONS ! VARIETY OF MICROCONTROLLER BASED APPLICATIONS OF LADDER LOGIC WILL ALSO BE DEVELOPED
  • 22. AND SEQUENCE BASED SYSTEMS 4HE SOFTWARE SUPPLIED WITH THE SERIES HAS BEEN PLACED INTO THE PUBLIC DOMAIN BY THE AUTHOR
  • 23. AND SO IS FREE FOR YOU TO USE )T CURRENTLY WORKS WITH ÚVE DIFFERENT 0)# MICROS !
  • 24. !
  • 25. AND
  • 26. PLUS THE FOLLOWING COM- MONLY AVAILABLE HARDWARESOFTWARE PLATFORMS 6ELLEMAN + 0ROGRAMMING AND %XPERIMENTATION OARD
  • 27. AVAILABLE FROM A NUMBER OF MAIL ORDER SUPPLIERS 0)#KIT4- $EBUG %XPRESS OARD
  • 28. SUPPLIED BY -ICROCHIPDIRECT www.microchipdirect.com -ATRIX -ULTIMEDIA 6ERSION 0)#MICRO -#5 $EVELOPMENT OARD
  • 29. AVAILABLE FROM THE Everyday Practical Electronics EPE 2EADERS 3ERVICES 0ROTEUS 63- ELECTRONIC CIRCUIT SIMULATION SOFTWARE FROM ,ABCENTER %LECTRONICS www.labcenter.co.uk (OPEFULLY
  • 30. YOU WILL HAVE ACCESS TO ONE OF THE ABOVE AND WILL BE ABLE TO WORK ALONG WITH THE SERIES 3EEING REALLY IS BELIEVING
  • 31. AND THE BEST WAY TO LEARN IS TO TRY THE CONCEPTS OUT FOR YOURSELF )F YOU DO
  • 32. ) GUARANTEE YOUmLL BE SURPRISED BY THE POWER AND SIMPLIC- ITY OF LADDER LOGICØ Comparing PLCs and microcontrollers 4HE MAIN DIFFERENCES BETWEEN A 0,# AND A MICROCONTROLLER RELATE TO
  • 33. Everyday Practical Electronics, November 2009 51 Teach-In 2010 size, complexity and, of course, cost. The inputs and outputs circuits of a PLC, for example, are extremely rugged, with digital inputs often be- ing connected via opto-isolators, and digital output types including transis- tor, thyristor, triac and relay. This al- lows the PLC to directly control high power devices, such as motors, pneu- matic actuators and the like. A typical implement combinational and se- quential logic functions in electrical control circuits, and it is in part this electrical basis which makes it easy for electrical engineers to understand – even those without a computing background. Consider, for example, a simple electrical circuit consisting of a switch and a lamp, and also its rep- resentation using a ladder diagram, as shown in Fig.1.2. Considering the circuit on the left, closing the switch will clearly cause the lamp to light. The ladder diagram on the right is equivalent, consisting of a pair of vertical power rails, with one or more horizontal ‘rungs’. (The ladder-like appearance gives this type of diagram its name.) Closing the normally open switch contacts on the left of the ladder diagram will con- nect power through the horizontal rung, hence lighting the lamp. Historically, the output would typically have been a relay coil, thus allowing a relatively low voltage control circuit to switch mains oper- ated power devices. For this reason, PLC inputs are often referred to as contacts, while outputs are called coils. It can be seen from the ladder diagram that an output coil is rep- resented graphically using a pair of curved braces (although a circular output symbol is sometimes seen). This extremely simple concept is the basis of PLC operation, and in part explains why electrical engineers are so comfortable writing PLC programs. This added complexity is avoid- ed here by the pre-configuration of default settings, such as port directions, in the supplied PLC header ÚLES OR EXAMPLE
  • 35. 0ORT ! IS CONÚGURED TO BE AN input, while Port B is an output.) You can, of course, change these settings, simply by editing the relevant section OF THE HEADER ÚLE
  • 36. BUT THE SOFTWARE IS commerciallyavailablePLCisshownin Fig.1.1, with input connections shown at the top and outputs at the bottom. While the I/O connections of a mi- crocontroller operate at much lower voltage and current than those of a PLC, they are essentially the same from a software point of view. The internal structure of a microcontroller also contains many similar elements to those found inside a PLC, including a central processing unit, program mem- ory (ROM), together with a variety of volatile and non-volatile data memory types. (The content of volatile memory types, such as static RAM, is lost when power is removed, while non-volatile memory,suchasEEPROM,isretained.) The allocation of connections as in- puts or outputs is, of course, pre-deter- mined by the PLC manufacturer, since this is a pre-requisite for the connection of specialised interface circuitry. Not so inthemicrocontrollerworld,wherethe assembly language programmer nor- mally has to decide on port directions, PLUS A VARIETY OF OTHER CONÚGURATION settings, prior to actually getting the microcontrollertodosomethinguseful. designed to work straight out of the BOX
  • 37. WITHOUT ANY NEED FOR CONÚGURA- tion – just like a real PLC. So, having established that PLCs and microcontrollers have a lot in Fig.1.1. A typical industrial PLC Fig.1.2. A simple switch and lamp circuit (left) and its equivalent ladder diagram (right) common, let’s turn our attention to lad- DER LOGIC
  • 38. AND ÚND OUT WHAT IT HAS TO offer in terms of software development. Ladder diagrams and ladder logic Ladder logic owes its origin to the use of switches and relays to Ladder logic programs are also very concise, with a section of code to (1) read an input and then (2) control a linked output requiring as little as two lines of code. Listing 1.1 shows a possible implementation. In general, a PLC program is cre- ated by converting each input contact
  • 39. 52 Everyday Practical Electronics, November 2009 Teach-In 2010 and output coil of the system’s ladder diagram into a series of equivalent program statements. Execution of the program is then a continuously operat- ing sequence of: Reading inputs Performing logic-based calculations Controlling outputs This repeating process is known as the scan cycle, and is shown graphi- cally for a slightly more complex example in Fig.1.3. It can be seen that each rung of the ladder diagram is evaluated from left to right, starting at the top rung and working progressively down (Steps 1 and 2 of Fig.1.3). The End of Program A number of conclusions may be immediately drawn from this method of operation: 1. Execution of a PLC program con- sists of a continuously operating pro- gramloop(arepeatingscancycle),even though this is not explicitly shown in the program listing or ladder diagram. 2. The time taken for a single scan cycle will increase in line with the complexity of the program, since the execution time for a single instruction IS ÚXED BY THE MICROPROCESSOR CLOCK frequency. Slightly less obviously: 3. An externally applied input signal WILL NEED TO BE PRESENT FOR A SUFÚCIENT time to guarantee it being ‘seen’ by the input phase of the scanning loop. 4. The average time taken to react to a changing input is re- lated to the scanning loop duration. 5. It may take more than one scanning loop for the results of complex calculations to fully propagate through the system. This may lead to the possibility of transient glitches as calcula- tions ‘ripple-though’. In practice, you SHOULD ÚND THAT LAD- der logic solutions are suitableinthemajority of logic-based control scenarios, since the computer is typi- cally operating at much higher speed than the system being controlled. Now that the basic principles of ladder logic programming have been covered, the next step is to obtain the required software, which will then enable us to create and test an execut- able program. Obtaining the software The ladder logic software is designed to work with the MPLAB Integrated De- velopmentEnvironment(IDE),whichis freely available for download from the Microchip website (www.microchip. com),oronCD-Rom.Allthatisrequired is to include a link to the appropriate HEADER ÚLE FROM WITHIN THE ASSEMBLY LANGUAGE SOURCE ÚLE
  • 40. AT WHICH POINT A variety of PLC-style commands become available for use in your programs. As mentioned earlier, versions of the software are available for the following commonly used PIC microcontrollers: PIC16F627/PIC16F627A (head- ER ÚLE l0,#m PIC16F628/PIC16F628A (head- ER ÚLE l0,#m 0)# HEADER ÚLE l PLC’) PIC16F88 (header files ‘16F88_L.PLC’ and ‘16F88_H.PLC’ offer low voltage and high voltage program versions respectively) 0)# HEADER ÚLE l PLC’) )N PRACTICE
  • 41. THE ÚRST FOUR OF THESE are all 18-pin ICs, differing mainly in THE QUANTITY OF ÛASH BASED PROGRAM memory, static RAM, or EEPROM- based non-volatile data memory. The PIC16F887 is a 44-pin IC, having enhanced input/output capabilities. These features are summarised in Table 1.1. Inclusion of the appropriate header file will cause a number of default settings to be chosen, such as port directions, oscillator type and so on. These settings have been tested with a number of hardware configurations, and are intended to simplify the configuration proc- ess as far as possible. (You should of course review these settings to ensure compatibility with your own requirements.) Default options are summarised in Table 1.2. A number of required files are available in a compressed ZIP file, which may be obtained from the the Library Project Code section of the Everyday Practical Electronics website (www.epemag.com). The contents of the ZIP file are given in Table 1.3. ld SWITCH ; Read state of Switch out LAMP ; Output to Lamp Listing 1.1. A notional section of a PLC program based on the circuit and ladder diagram of Fig.1.2 Fig.1.3. The repeating scan cycle of a PLC executing a ladder logic program statement forces program execution to RESUME FROM THE BEGINNING OF THE ÚRST rung (Step 3), causing the program to run continuously. This program might be coded using statements such as those given in Listing 1.2. ld SWITCH_A ; Read state of Switch A out LAMP_A ; Output to Lamp A ld SWITCH_B ; Read state of Switch B out LAMP_B ; Output to Lamp B endp ; End of PLC program Listing 1.2. A PLC program based on the ladder diagram of Fig.1.3
  • 42. Everyday Practical Electronics, November 2009 53 Teach-In 2010 Filename Description 16F627.PLC PLC header file for the PIC16F627/627A microcontroller 16F628.PLC PLC header file for the PIC16F628/628A microcontroller 16F648.PLC PLC header file for the PIC16F648A microcontroller 16F88_L.PLC PLC header file for the PIC16F88 microcontroller – low voltage programming enabled on pin RB3 16F88_H.PLC PLC header file for the PIC16F88 microcontroller – high voltage programming enabled, pin RB3 available for general I/O 16F887.PLC PLC header file for the PIC16F887 microcontroller PIC16F627.DSN Proteus VSM simulation – PIC16F627A based Digital I/O Board PIC16F88.DSN Proteus VSM simulation – PIC16F88 based Digital I/O Board PIC16F887.DSN Proteus VSM simulation – PIC16F887A based Digital I/O Board Lst1_3.asm Source code file for Listing 1.3 Lst1_4.asm Source code file for Listing 1.4 Lst1_5.asm Source code file for Listing 1.5 Lst1_6.asm Source code file for Listing 1.6 Assembling and execut- ing simple PLC-style programs In this section you will see just how easy it is to create and assemble simple programs and then run them on a variety of different PIC-based systems. I recommend that you try these activities out for yourself, if at all possible. Begin by extracting the entire CONTENTS OF THE :)0 ÚLE TO A CON- venient folder and then use the MPLAB IDE’s File Open menu OPTION TO DISPLAY THE ÚLE l,ST? asm’, the content of which is GIVEN IN ,ISTING /UR ÚRST PROGRAM IS FUNCTION- ally identical to the code snippet PREVIOUSLY SEEN IN ,ISTING
  • 43. BUT BASED ON THE 0)# microcontroller. It is suitable for use either with the PICkit 2 Debug Express board, or with Proteus VSM electronic simu- lation software. (Note that the PICkit 2 board has a single input SWITCH
  • 45. WHICH IS CONNECTED TO THE LEAST SIGNIÚCANT bit of Port B, plus eight LEDs connected to Port D – which explains the choice of inputs AND OUTPUTS IN ,ISTING Having displayed the source ASM ÚLE IN -0,!
  • 46. THE NEXT step is to assemble it, in order to create a machine code (.hex) ÚLE
  • 47. WHICH CAN LATER BE DOWN- loaded and programmed. The ÚRST STEP IS TO CHOOSE THE RE- quired microcontroller type by selecting the #ONlGUREªª3ELECTª Device menu option, and then selecting the PIC16F887 from the Device drop-down list. Next click on the blue title bar of the SOURCE CODE ÚLE TO ENSURE IT IS highlighted and then assemble THE ÚLE BY SELECTING THE Project Quickbuild Lst1_3.asm menu option. If everything has gone TO PLAN YOU SHOULD SEE A ÛURRY OF ACTIVITY AS THE ÚLE IS ASSEM- BLED
  • 48. CULMINATING IN A lUILD Succeeded’ message, displayed in the Build tab of the Output window. The MPLAB IDE has now done its JOB AND A ,ST?HEX ÚLE WILL HAVE been created in the same directory AS THE SOURCE CODE ÚLE
  • 49. READY TO BE programmed. Device Program (kWords) RAM (bytes) EEPROM (bytes) Max I/O (bits) Other Features PIC16F627 1 224 128 16 2 comparators PIC16F628 2 224 128 16 2 comparators PIC16F648 4 256 256 16 2 comparators PIC16F88 4 368 256 16 2 comparators 7-channel ADC PIC16F887 8 368 256 35 2 comparators 14-channel ADC Table 1.1. Major features of supported PIC microcontrollers Device Inputs Outputs Other Features PIC16F627 / 628 / 648 Port A (5 bits) Port B (8 bits) Comparators disabled, pull-ups disabled 4MHz external crystal oscillator selected Timer 0 configured for use by PLC software MCLR enabled, Watchdog timer enabled PIC16F88 Port A (5 bits) Port B (8 bits) Comparators disabled, pull-ups disabled 4MHz external crystal oscillator selected Timer 0 configured for use by PLC software MCLR enabled, Watchdog timer enabled ADC disabled PIC16F887 Port A (8 bits) Port B (8 bits) Port E (4 bits) Port C (8 bits) Port D (8 bits) Comparators disabled, pull-ups disabled 4MHz internal oscillator selected Timer 0 configured for use by PLC software MCLR disabled, Watchdog timer enabled ADC disabled 4ABLEªª$EFAULTª0)#ªSOFTWAREªCONlGURATIONªOPTIONS Table 1.3. File contents of ‘PLC1.zip’ include 16F887.PLC ; Defines PLC instructions ld PORTB, 0 ; Read Port B bit 0 out PORTD, 0 ; Output to Port D bit 0 endp ; End of PLC program Listing 1.3. Reading a switch and outputting to an LED (Lst1_3.asm)
  • 50. 54 Everyday Practical Electronics, November 2009 Teach-In 2010 Syntax Function Ladder Diagram Symbol ld REGISTER, BIT[0-7] Read an I/O bit ld_not REGISTER, BIT[0-7] Read an I/O bit (inverted) out REGISTER, BIT[0-7] Send to output bit out_not REGISTER, BIT[0-7] Send to output bit (inverted) Table 1.4. Bit input/output commands Fig.1.4. A Proteus VSM simulation of the PIC16F887 microcontroller What happens next depends on how you intend to actually run the program. If you are using the PICKit 2 board then the next step is to run the PICkit 2 programmer application, then use the File Import Hex menu option TO OPEN THE MACHINE CODE HEX ÚLE created earlier. Next, click the Write button to program the PIC16F887 mi- crocontroller. You should see a green Programming Successful message in the programmer window at this stage. Finally, apply power to the board by clicking the On checkbox situated just under the VDD PICkit 2 label at the upper right. Pressing Switch 1 will now cause the LED con- nected to RD0 to toggle on and off. However, you may note that the LED actually goes out when the switch is pressed, which is the opposite of what you might have expected. Examin- ing the schematic diagram supplied with the PICkit 2 documentation solves the mystery, revealing that SW1 normally reads as a logic-1, providing a logic-0 when pressed. The required logic of our program may be easily restored by replacing the ‘ld’ instruction with its negative logic ‘ld_not’ equivalent, as given in Table 1.4. From Table 1.4, we can also see that a negative logic output command
  • 51. Everyday Practical Electronics, November 2009 55 Teach-In 2010 (out_not) is available. Thus, we can create a logical inversion either by using ‘ld_not’ followed by ‘out’, or ‘ld’ followed by ‘out_not’. If you are using the PICkit 2 board, then you can use this information to modify the program of Listing 1.3 so that pressing the switch causes the LED to come on, rather than go out. If you are lucky enough to have the full version of Proteus VSM, Version 7.0 or later, then this may be used to simulate the operation of the program of Listing 1.3. Begin by using Proteus to open the supplied PIC16F887.DSN ÚLE
  • 52. WHICH WILL APPEAR AS SHOWN IN Fig.1.4. include 16F627.PLC ; Defines PLC instructions ld PORTA, 0 ; Read Port A bit 0 out PORTB, 0 ; Output to Port B bit 0 ld PORTA, 1 ; Read Port A bit 1 out PORTB, 1 ; Output to Port B bit 1 endp ; End of PLC program Listing 1.4. Reading and controlling multiple inputs and outputs (Lst1_4.asm) Controlling multiple inputs and outputs To take a slightly more complex example, suppose we wanted to con- trol several inputs and outputs. This could be achieved as illustrated by Listing 1.4, shown for a PIC16F627- based system. Assuming you have a suitable PIC programmer and experimentation board, such as the Velleman K8048, the ÚRST STEP IS TO USE THE -0,! )$% TO CREATE A MACHINE CODE ÚLE REMEMBER- ing of course to set the device type to either the PIC16F627 or PIC16F627A, as appropriate). Next, connect the Fig.1.5. The output produced by Listing 1.4, running on a Velleman K8048 board include 16F887.PLC ; Defines PLC instructions ld PORTE, 3 ; Read Port E bit 3 (ICSP pin 1) out PORTD, 3 ; Output to Port D bit 3 ld PORTB, 7 ; Read Port B bit 7 (ICSP pin 4) out PORTD, 2 ; Output to Port D bit 2 ld PORTB, 6 ; Read Port B bit 6 (ICSP pin 5) out PORTD, 1 ; Output to Port D bit 1 ld_not PORTB, 0 ; Read Port B bit 0 inverted (SW1) out PORTD, 0 ; Output to Port D bit 0 endp ; End of PLC program Listing 1.5. Controlling up to four inputs using the PICkit 2 Debug Express (Lst1_5.asm) programmer to your PC via the sup- plied serial cable and then download and execute the program. When the program is executed, pressing a switch CONNECTED TO THE ÚRST TWO BITS OF 0ORT A should cause the corresponding bit of Port B to be activated, as shown in Fig.1.5. If you have access to the Proteus VSM software then you use this to load the ‘PIC16F627.DSN’ simulation and then follow the procedure described earlier to load and execute the program of Listing 1.4. Surprisingly, it is also possible to develop similarly complex programs for the PICkit 2 Debug Express board, despite the fact that the PCB is limited to a single physical input switch! The trick in this case is to use the PICkit 2 Logic Tool application to control up to three additional digital input signals via the In Circuit Serial Programming (ICSP) interface, which links the ‘black box’ to the PIC16F887 PCB. When not being used to download programs, the Logic tool allows inputs RE3, RB7 and RB6 to be controlled by activating pins 1, 4 and 5 of the ICSP interface respectively. To see this in action for yourself, begin by assembling the program of Listing 1.5, and then download the RESULTING MACHINE CODE ÚLE TO THE PIC16F887 in the normal way. Next, enable power to the PCB by clicking the On check-box and then select the Tools Logic Tool option from the pull-down menu, which will display the PICkit 2 Logic Tool dialog of Fig.1.6. Ensure the Mode option is set to Logic I/O by clicking the button at the upper right, and then click the Enable Our machine code program created earlier must be logically attached to the PIC16F887, prior to running the simulation. To do this, right-click on component U1 and select the Edit Properties option from the context menu to display the Edit Component dialog. From here, you can click the YELLOW FOLDER ICON AND BROWSE TO ÚND THE l,ST?HEXm ÚLE CREATED EARLIER Close the dialog and then click the Play button at the lower left of the Proteus window to run the simulation. You’ll then be able to click on the input con- nected to bit 0 of Port B, which should cause the corresponding bit of Port D to change (as illustrated by Fig.1.4).
  • 53. 56 Everyday Practical Electronics, November 2009 Teach-In 2010 Fig.1.6. Controlling digital inputs via the PICkit 2 Logic Tool dialog IO button to allow logic levels to be directly observed or controlled. Next, set pins 4 and 5 to be outputs, at which point you should be able to control the state of the LEDs connected to outputs RD0-RD3, with the program of Listing 1.5 running. (Note that Pin 6 in Fig.1.5 IS IDENTIÚED ON THE SCHEMATIC DIAGRAM as an Auxiliary signal. This pin is not connected to the PIC16F887 IC, by default, and so is not used here.) Using the PICmicro MCU development board 4HE ÚNAL PIECE OF HARDWARE TO LOOK at in this installment is the Version 3 PICmicro MCU Development board, as shown in Fig.1.7. This comprehensive board is avail- able from the EPE Readers’ Services, and is supplied as standard with a PIC16F88 microcontroller, although a wide variety of other PICs are also supported. The board brings out the inputs of Port A and the outputs of Port B via switches and LEDs at the lower left and lower right respectively. A 16MHz crystal oscillator is supplied IN A SOCKET AT THE LOWER RIGHT
  • 54. WHICH IS four times faster than the 4MHz default used by the PLC software. If you are PLANNING TO DO SERIOUS WORK WITH THE PLC software, I’d recommend replac- ing this with a 4MHz crystal – which will ensure that time-dependent programs covered in later parts of the series run at the correct speed. )NCIDENTALLY
  • 55. THE 0,# HEADER ÚLE IS CONÚGURED TO AUTOMATICALLY ENABLE an internal RC oscillator at 4MHz in the event that the external oscillator fails to start.) A USB cable is supplied as standard, although the board can also accommo- date an external DC supply (shown at the upper left of Fig.1.7). If the board is powered from the USB cable, then the PIC must be programmed using ‘low VOLTAGE PROGRAMMINGm
  • 56. WHICH MAKES use of Port B, bit 3 (RB3). To use LVP with the PIC16F88, the upper (RB3) jumper to the left of the LCD display must be positioned to the left, as shown in the image. (Be sure to do this with the power removed, and be very careful which jumper you enable, to avoid damaging the PIC microcon- troller.) 4WO VERSIONS OF THE HEADER ÚLE are provided, supporting low volt- age or high voltage programming (‘PIC16F88_L.PLC’ and ‘PIC16F88_H. PLC’ respectively). Listing 1.6 shows a suitable test program, which also demonstrates the use of active-low inputs and outputs, as originally seen in Table 1.4. 4HE PROGRAM IS ÚRST ASSEMBLED IN the normal way, by using the MPLAB IDE. A supplied PIC programming APPLICATION 000 IS THEN USED TO ÚRST OPEN THE ASSEMBLED (EX ÚLE AND THEN transfer it via the USB cable to the PIC micro. The program will then run automatically. A Proteus simulation of the 16F88 microcontroller (PIC16F88.DSN) is also provided, for those readers with access to this powerful software. Operation is the same as that described earlier – see Fig.1.4 and associated text for details. Troubleshooting tips While operation should be mostly trouble free, the following trouble- shooting tips will help you to resolve ANY ISSUES AS QUICKLY AS POSSIBLE 1.TheMPASMassemblerusedbythe MPLAB IDE is case sensitive and it is a requirement that all PLC commands should be entered in lower case, and any parameters IN UPPER CASE 4HE ÚRST STEP IS THEREFORE TO CAREFULLY CHECK THE listing for typographical errors. Fig.1.7. Running a simple bit input/output program on the PICmicro MCU development board
  • 57. Everyday Practical Electronics, November 2009 57 Teach-In 2010 2. Ensure that the relevant include ÚLE IS IN THE SAME DIRECTORY AS THE ASSEMBLER SOURCE ÚLE
  • 58. OTHERWISE THE ASSEMBLER MAY BE UNABLE TO LOCATE IT 7HEN USING THE -0,! )$%
  • 59. CHECK THAT YOU HAVE SELECTED THE CORRECT MICROCONTROLLER TYPE
  • 60. PRIOR TO ATTEMPTING TO ASSEMBLE THE SOURCE CODE ÚLE 4HE ASSEMBLER CREATES A NUMBER OF OTHER ÚLES WHICH MAY CONTAIN USEFUL DIAGNOSTIC INFORMATION )N PARTICULAR
  • 61. AN ERROR ERR ÚLE IS CREATED WITH DETAILS OF ANY ERRORS
  • 62. AND A LISTING LST ÚLE WILL CONTAIN FULL DETAILS OF THE SOURCE CODE
  • 63. THE MACHINE CODE GENERATED
  • 64. PLUS ANY ERRORS 4RY TO KEEP ÚLENAMES AND ÚLE PATHNAMES SHORT 3OME VERSIONS OF THE -0!3- ASSEMBLER WILL GIVE AN ERROR IF THE ÚLENAME PORTION OF THE SOURCE ÚLE NAME IS LONGER THAN EIGHT CHARACTERS 9OU MAY ALSO GET AN ERROR IF THE FULL PATHNAME IS LONGER THAN CHARACTERS ; (Low voltage programming version ; with RB3 used as the LVP pin) ld PORTA, 0 ; Read Port A bit 0 out PORTB, 2 ; Output to Port B bit 2 ld_not PORTA, 1 ; Read Port A bit 1 (inverted) out PORTB, 5 ; Output to Port B bit 5 ld PORTA, 2 ; Read Port A bit 2 out_not PORTB, 6 ; Output to Port B bit 6 (inverted) ld_not PORTA, 3 ; Read Port A bit 3 (inverted) out_not PORTB, 7 ; Output to Port B bit 7 (inverted) endp ; End of PLC program Listing1.6.ControllingnormalandinvertedsignalswiththePIC16F88(Lst1_6.asm) #ONSIDER TEMPORARILY COMMENT- ING OUT LINES WHICH YOU SUSPECT MAY BE CAUSING AN ERROR 9OU CAN DO THIS BY ADDING A SEMICOLON TO THE START OF THE LINE )T MAY ALSO BE USEFUL TO TEMPORARILY ADD ADDITIONAL LINES TO YOUR PROGRAM
  • 66. THE 7ATCH WIN- DOW MAY PROVIDE USEFUL DEBUGGING INFORMATION 7EmLL LOOK AT THIS 0ROTEUS FEATURE LATER IN THE SERIES Final thoughts )N THIS ÚRST ARTICLE WEmVE FOCUSED ON READING AND CON- TROLLING INDIVIDUAL INPUTS AND OUTPUTS EAR IN MIND THAT THIS IS ONLY A SMALL PORTION OF THE AVAILABLE COMMAND SET
  • 67. AND WEmLL BE PROGRESSIVELY INTRODUCING ADDITIONAL FEATURES OF THE SOFTWARE IN THE REMAINING ÚVE PARTS OF THE SERIES 7EmVE ALSO DEMONSTRATED THAT THE SOFTWARE CAN BE USED WITH A VARIETY OF 0)# MICROCONTROLLERS
  • 68. WITH COMMONLY AVAILABLE PROGRAMMER AND EXPERIMEN- TATION BOARDS
  • 69. AND EVEN WITH ELECTRONIC CIRCUIT SIMULATION SOFTWARE 4HE NEXT INSTALLMENT WILL BEGIN BY USINGLADDERLOGICELEMENTSTOCONSTRUCT SIMPLE COMBINATIONAL LOGIC CIRCUITS BASED ON OOLEAN OPERATORS SUCH AS !.$
  • 70. /2
  • 71. AND %/2 EXCLUSIVE /2 7EmLL THEN MOVE ON TO CONSIDER THE DEVELOPMENT OF SIMPLE SEQUENTIAL LOGIC SYSTEMS
  • 73. AND ALSO THE CREATION OF VARIABLE FREQUENCY PULSED OUTPUTS 7EmLL THEN USE THESE CONCEPTS TO DE- VELOP A SIMPLE AND EXTENDABLE ALARM CIRCUIT
  • 74. USING JUST A FEW LINES OF CODE
  • 75. AND SUITABLE AS THE BASIS OF EITHER A CAR ALARM OR BURGLAR ALARM EATURES WILL INCLUDE MULTIPLE INPUT SENSORS
  • 76. A LATCHED ALARM STATUS OUTPUT
  • 77. AND A PULSED ARMEDDISARMED ,%$ COOL COMPONENTS Established in 2004, Cool Components supplies interesting, useful and powerful electronic components at excellent prices. Arduino Boards + Shields Fast Update GPS Modules Olimex PIC, AVR + ARM Boards Serial Bluetooth Adaptors Plug-In Media Player Modules Serial Controlled OLED Displays Iron-On PCB Fabrication Servos + Servo Controllers WWW.COOLCOMPONENTS.CO.UK Follow product news on: twitter.com/coolcomponents 0871 288 7685 We work with manufacturers including Sparkfun, Olimex, Arduino and many others to bring you the best from the cutting edge of new electronic technology. include 16F88_L.PLC ; Defines PLC instructions
  • 78. Everyday Practical Electronics, December 2009 By Walter Ditch TEACH-IN 2010 LADDER LOGIC PROGRAMMING FOR THE PIC MICRO Part 2: Working with Combinational and Sequential Logic T HIS is the second instalment of a six-part series, discussing the use of ladder logic programming methods with PIC microcontrollers. Ladder logic is the fundamental basis of Programmable Logic Controllers (PLCs), which are a specialised type of industrial computer, designed to be easily programmed by engineers. Thus, the aim of using ladder logic is to simplify the development process, making PIC programming accessible to the widest possible audience. You may recall that last month we discussed the use of ladder diagrams to graphically represent simple electrical circuits, and converted these to execut- able machine code programs for the PIC micro by using commands such as: ‘ld’(readaninputbit);‘out’(sendresult toanoutputbit);plustheirnegativelog- ic counterparts ‘ld_not’ and ‘out_not’ respectively. We saw that a PLC-style programexecutesbyfollowingarepeat- ing cycle of reading inputs, performing calculations and controlling outputs, known as the scan cycle. The PLC software itself consisted of A SERIES OF lHEADER ÚLESm
  • 79. AVAILABLE FOR A number of common PIC microcontrol- lers, including the 16F627A, 16F628A, 16F648, PIC16F88 and PIC16F887. By including the appropriate header ÚLE INTO OUR SOURCE CODE PROGRAMS
  • 80. WE were able to use the freely available MPLAB Integrated Development Envi- ronment (IDE) to assemble our ladder logicprogramsintoexecutablemachine code programs, which could then be downloaded to a variety of commonly available PIC development boards. Hardware demonstrated in Part 1 includedtheVellemanK8048board,Mi- crochip Direct’s PICkit 2 Debug Express board, Matrix Multimedia’s PICmicro MCU Development board, plus Proteus VSM electronic circuit simulation soft- ware from Labcenter Electronics. Moving on In this second instalment, we’ll continue our tour of ladder logic by looking at: Creation of repeating waveforms by using ‘oscillators’ Combining inputs using simple combinational logic operators (AND and OR) Availability of other logical func- tions (NOT, NAND, NOR, XOR, and XNOR) Using internal memory locations (auxiliary relays) to hold intermedi- ate results and to solve complex logic networks Creationoflatched(stored)outputs to capture momentary input signals, including the provision of set and reset inputs outputs. We’ll then use these concepts to de- velop a simple and extendable alarm circuit, using just a few lines of code, and suitable as the basis of either a car alarm or burglar alarm. Features will include multiple input sensors, a latched alarm status output, and a pulsed armed/disarmed LED. Simple systems The above concepts will be drawn together to create a number of simple BUTUSEFULSYSTEMS
  • 81. INCLUDINGAÛASHING ‘system armed’ indicator, plus a simple alarm circuit. These simple building blocks may be used as the basis of a wide variety of more complex systems, with potential applications being mainly limited by your imagination. The article concludes by discussing the PLC software’s internal operation in a little more detail. This knowledge willproveusefulwhendebuggingyour own programs, or should you decide to modify or extend the PLC software to suit your own purposes. All program listings for this article are available from the Library Project Code section of the Everyday Practical Electronics website (http://www.epe mag.com/ 9OUmLL ALSO NEED THE ÚLES from Part 1 – particularly the various 0)# HEADER ÚLES q SO )mD SUGGEST THAT YOU lUNZIPm ALL ÚLES INTO A SINGLE FOLDER Also, make sure you have installed
  • 82. Everyday Practical Electronics, December 2009 the freely available MPLAB IDE software, which will be needed to actually assemble the example programs. And of course, in order to actually test the programs, you will need a suitable PIC develop- ment board or simulation software. Creating repeating waveforms by using oscillator bits The PLC software provides two 8-bit registers, OSCH and OSCL, which contain a total of 16 oscillators, with periodic times ranging from 512Ps to 16.77 seconds, based on the default clock frequency of 4MHz. Available periodic times and frequencies are shown in Table 2.1. is important to also be aware that they are also used internally as time refer- ences by several other PLC commands yet to be considered, including timers and PWM (pulse width modulated) outputs.Forthisreason,theuseofadif- ferent clock frequency to the assumed value of 4MHz is likely to cause time- critical programs to run correspond- ingly faster or slower. Simple combinational logic functions Simple switch-based and ladder logic circuits may easily be developed to implement Boolean logic functions such as AND and OR, as shown in Fig.2.1. Two or more switches in series cre- ates an AND function, since all input contacts must be simultaneously closed to activate the output device (or output coil). Similarly, parallel switch contacts will provide a logical OR ar- rangement, with one or more closed contacts creating a route for the power TO ÛOW ALONG THE RUNG
  • 83. THUS ACTIVATING the output device. Notice in Fig.2.1 that all inputs and outputs have been labelled, thus it is possible to state the logical operation of the upper and lower systems in Fig.2.1 as: ‘LAMP = A AND B’, (switches in series), and ‘LAMP = A OR B’ (switches in parallel). The example program of Listing 2.2 shows a possible coding for these logical operations, based on the 16F88 microcontroller. In this case, the output on Port B bit 0 is generated by ANDing the lower two input bits on Port A, while Port B bit 1 is the result of ORing bits 2 and 3 of Port A. This method is extendable, simply add successive logical opera- tors in order to increase the number of inputs. Also, note that NAND or NOR operators may easily be created by replacing the ‘out’ instruction with its negative logic equivalent ‘out_not’. A simple application which com- bines oscillators with logic functions Waveform production OR THE BENEÚT OF INQUISITIVE READERS
  • 84. this section explains how the oscilla- tor waveforms are produced, and also covers the derivation of the periodic times of Table 2.1. (This is not essential reading, so you can skip this and come back to it later.) Recall from Part 1 that the PLC soft- ware assumes an oscillator frequency of4MHz.Thissignalisusedtogenerate a number of other waveforms, includ- 26+ +LJK )UHTXHQF 2VFLOODWRUV
  • 86. %LW SRVLWLRQ 3HULRGLF 7LPH)UHTXHQF %LW 3RVLWLRQ 3HULRGLF 7LPH)UHTXHQF 0 1 3 6 7 ȝV N+] PV +] PV +] PV +] PV +] PV +] PV +] PV +] 0 1 3 6 7 PV +] PV +] PV +] V +] V +] V +] 8.389 s / 0.119 Hz 16.77 s / 0.06 Hz Table 2.1. Square wave signals available from the OSCH and OSCL registers An obvious application of these SIGNALS IS TO CREATE A ÛASHING OUTPUT using an LED. All that is needed is to load the required oscillator bit and then send it to the desired output port. This is illustrated by the example of Listing 2.1, which is suitable for use either with the PICkit 2 Debug Express board, or with Proteus VSM electronic simulation software. Note: The examples in this series are written for a variety of PIC mi- CROCONTROLLERS
  • 87. IN ORDER TO REÛECT THE wide range of devices commonly available. You can easily adapt any of the programs in this series to work with other supported PIC mi- CROCONTROLLERS q JUST MODIFY THE ÚRST line to load the appropriate header ÚLE
  • 88. AND THEN CHANGE THE IDENTITY OF input and output port bits to suit those available. Use the information previously given in Part 1 as a guide (see Table 1.2 and associated text for more details). In the next section, we’ll see how oscillators may be usefully combined with simple Boolean logic functions, SO THAT AN OUTPUT ÛASHES ONLY WHEN A predetermined condition is true. ing four non-overlapping (quadrature) 1MHz waveforms (Q1, Q2, Q3, Q4) and also a basic 1MHz square waveform, AS MAY BE CONÚRMED BY STUDYING THE appropriate PIC data sheet. The PLC software uses this 1MHz square wave signal to continuously increment an 8-bit timer register (Timer0, also re- ferred to as OSCH here), but using a 1:256 prescaler (frequency divider). Thus, the OSCH register increments once every 256Ps. A 0 1 transition followed by a 1 0 transition is required to produce one complete square waveform, resulting in the stated periodic time of 512Ps for bit 0 of OSCH. Periodic times of subsequent bits are derived by repeat- edly doubling this initial value (and frequencies are, of course, calculated as the reciprocal of periodic times.) The PLC software uses a Timer0 (OSCH) overflow interrupt to incre- ment the low frequency oscillator register (OSCL), in effect creating a 16-bit timer register in software, from the 8-bit timer provided in hardware. These waveforms may be used di- rectly in user programs. However, it Listing 2.1. Creating a 2Hz pulsed output (Lst2_1.asm)
  • 89. Everyday Practical Electronics, December 2009 wouldbetoenableapulsedoutputonly when a key is pressed. A simple exam- ple is shown in Listing 2.3 – this time written for for the PIC16F627/627A microcontroller. of connecting a virtual oscilloscope to Port B bit 1 using the Proteus VSM software. As can be seen, the measured peri- odic time of 530Ps, obtained using the be ‘seen’ by the PLC software until its next pass through the scan cycle.) Other logical operations It was previously seen from Fig.2.1 that two normally-open switches in series creates a logical AND function, while parallel switches provide a logi- cal OR (inclusive-OR to be precise). The related exclusive-OR function provides an output if precisely one of the inputs is true, which is logically equivalent to the statement ‘The out- put is true if (A is true and B is false) OR (A is false and B is true)’. Listing 2.4 gives an example. In addition to optionally inverting the output bit, as previously discussed, it is also possible to perform logical operations where one of the input bits is inverted. The full range of Boolean logic functions, based on normally- open or normally-closed input con- tacts, is shown in Table 2.2. Using internal memory to hold intermediate results While the above methods may be used to solve simple Boolean logic cir- cuits, more complex logical problems may require an alternative technique. Consider for example the ladder dia- gram of Fig.2.3. The trick in this case is to use standard logical operators to solve each horizontal ‘rung’ of the lad- der diagram, writing the result to a series of auxiliary relays. These intermediate results may then be combined using standard logical commands to calculate the final output state. Listing 2.5 demonstrates the use OF THE LEAST SIGNIÚCANT BIT OF REGISTER AUX0 to hold the intermediate result FROM THE ÚRST RUNG
  • 90. THIS BEING LOGI- cally combined with the result from THE SECOND RUNG TO PRODUCE THE ÚNAL output on bit 0 of Port B. You should now have a good un- derstanding of the ‘single bit’ combi- national logic capabilities of the PLC software. For future reference, it is worth mentioning that a number of ‘byte oriented’ logical commands are also available, which will be discussed later in the series. The next section demonstrates how the application of feedback from out- put to input may be used to create a simple latch, which is, of course, the basis of sequential logic. Fig.2.1. Switch-based and ladder logic versions of Boolean logic functions Listing 2.2. Simple logical functions (Lst2_2.asm) Listing2.3.Generatingwaveformsusingoscillatorsandsimplelogic(Lst2_3.asm) This example demonstrates the wide range of frequencies available, with the high frequency signal on Port B being much too fast to see with the naked eye. Fig.2.2 shows the result Proteus VSM simulation, compares quite well with the predicted value of 512Ps from Table 2.1. (Some ran- DOM ÛUCTUATION IS INEVITABLE
  • 92. Everyday Practical Electronics, December 2009 Using feedback to create latched outputs Surprisingly, it is possible to read the state of an output in just the same way as an input. This allows feedback to be applied, which in turn enables the creation of circuits where a mo- mentary input signal causes an output to be Set or latched until it is manually cancelled. Fig.2.4 shows the creation of a latch circuit using standard ladder logic commands. In this case a momentary signal on the Set input, Port A bit 0, enables the latch output (commonly referred to as Q in bistable circuits), which is connected to Port B bit 0. The key to understanding this circuit is to notice from Fig.2.4 that the state of the Q out- put is also connected in parallel with the Set input, proving a logical OR arrangement. Thus, the latch is held in the on state once the momentary Set input is removed. The circuit remains enabled until the normally closed Re- set input (Port A, 1) is pressed, which breaks the circuit and resets the latch. The ladder diagram also contains an optional second rung which reads the Q output (Port B bit 0) and generates an inverted (Not Q) output on Port B bit 1. A program listing is given in Listing 2.6, which is suitable for use with the PIC16F88 microcontroller. The PLC software also includes a dedicated latch command, which pro- vides an alternative to using separate ladder logic commands. Fig.2.5 shows a ladder diagram incorporating the latch, while Listing 2.7 gives a modi- ÚED LISTING
  • 93. ALSO BASED ON THE microcontroller While the use of the latch command does reduce the source code by a cou- ple of lines, the actual machine code generated is identical in either case. Which approach to use is therefore a matter of personal preference. Fig.2.2. Connecting a virtual scope to the Port B bit 1 output in Proteus VSM Listing 2.4. The exclusive-OR operator (Lst2_4.asm) Table 2.2. Single-bit Boolean logic commands Fig.2.3. A complex logic circuit requiring a two-stage approach
  • 94. Everyday Practical Electronics, December 2009 Building simple systems To bring together some of the con- cepts discussed, let’s begin by creating A BRIEÛY ÛASHING ,%$ OUTPUT
  • 95. AS MIGHT be found in the ‘system armed’ output of an immobiliser circuit. We’ll use a latch to arm or disarm the circuit, statements are optional, having the effect of reducing the pulse width to 1/8 of its initial value. The program may be executed either using the appropriate Proteus VSM simulation (for those readers with ac- cess to this software), or by using the Listing 2.5. Using internal relays to solve complex logic circuits (Lst2_5.asm) The program uses bits 0 to 2 of Port A as input sensors, and Port A bit 3 as a Reset signal (1 = reset, 0 = system armed). Notice that the sensor status automatically becomes the input to the latch, with the latch output being sent TO AN ,%$ CONNECTED TO OUTPUT 0/24 bit 0 (this might be a buzzer or sounder in a real alarm). Momentarily pressing the switch connected to Port A bit 3 resets the latch, cancelling the alarm. A possible program for the 16F627 MICROCONTROLLER IS GIVEN IN ,ISTING Possible enhancements would in- clude a pulsed alarm output, and the provision of a ‘system armed’ indica- tor, similar to that seen previously. These additions are left as exercises for the reader. A further potential development would be the automatic cancellation of the alarm after a given period of time, in order to prevent unnecessary annoyance due to false triggering. This enhancement will have to wait until next month, when timers will be covered. Internal operation of the PLC software A more detailed understanding of THE UNDERLYING OPERATION OF THE 0,# software is useful at this stage, not only for curiosity’s sake, but also to explain the types of error messages which will inevitably be encountered as you begin to write programs of your own. !S YOU WILL BE AWARE
  • 96. THE -0,! )NTEGRATED $EVELOPMENT %NVIRONMENT )$% USES AN ASSEMBLER TO TRANSFORM YOUR SOURCE CODE TEXT ÚLE INTO AN Fig.2.4. Creation of a latched output by usingstandardladderlogiccommands Fig.2.5. Using a dedicated latch, rather than separate ladder logic commands WITH THE OUTPUT BEING SENT IN THE ÚRST instance to an auxiliary relay. When enabled, the output will be made to ÛASH BY !.$ING WITH A (Z OSCILLA- tor signal, and the pulse width will THEN BE REDUCED BY !.$ING TOGETHER several higher frequency oscillator BITS ,ISTING SHOWS A POSSIBLE SOLUTION
  • 97. BASED ON THE 0)# microcontroller. )T CAN BE SEEN FROM ,ISTING THAT THE LATCH USES 0ORT BITS AND AS THE Set and Reset inputs, with the latch output being sent initially to auxiliary relay AUX bit 0. The latched signal IS MADE TO PULSE AT (Z BY !.$ING with low frequency oscillator register /3#, BIT
  • 98. AND IS DISPLAYED BY OUT- PUTTING TO THE ,%$ CONNECTED TO 0ORT $ BIT 4HE INTERVENING THREE !.$ Fig.2.6. Ladder diagram for a simple alarm with three sensors 0)#KIT $EBUG %XPRESS BOARD )N THE latter case, recall from Part 1 of the se- RIES THAT YOU CAN USE THE 0)#KIT ,OGIC Tool to set and reset the bistable. Pin 5 IS CONNECTED TO 0ORT BIT
  • 100. WHILE 0IN 0ORT BIT acts as Reset. (Slightly confusingly, YOU NEED TO CONÚGURE THESE TWO PINS AS OUTPUTS IN THE ,OGIC 4OOL SINCE THEY are used to drive the corresponding INPUTS ON THE 0)# /UR ÚNAL EXAMPLE IS A SIMPLE ALARM circuit with three sensor inputs and a latched alarm output. If one or more of the sensors is momentarily activated then the alarm will be trig- gered, and remain in this state until the alarm is manually cancelled. The ladder diagram for the alarm is shown in Fig.2.6.
  • 101. Everyday Practical Electronics, December 2009 executable machine code program. This powerful software has a macro facil- ity, which allows a text string to be automatically replaced by a section of USER DEÚNED TEXT
  • 102. PRIOR TO ASSEMBLY 4HE MACRO DEÚNI- tion may optionally expect one or more arguments (text strings), and the user supplied values will be automatically inserted into the output text by the assem- bler, prior to conversion to machine code. Consider the implementation of the ‘ld’ instruction as an example, as shown in Fig.2.7. As can be seen, the ‘ld’ macro accepts two argu- ments, ld_arg1 and ld_arg2. The macro substitution causes the original source code line to be replaced by three lines of assembly language. It is important to be aware that any assembler errors are likely to relate to the source code after the macro substitution, which does admittedly make the debugging process a little MORE DIFÚCULT Notice that the above section of code results in the logic level present on the input port being placed INTO THE LEAST SIGNIÚCANT BIT of the (LSB) Working regis- ter (W), which is actually a general feature of the PLC software. The correspond- ing ‘out’ instruction, for example, simply takes WHATEVER IT ÚNDS IN THE ,3 of the W register and sends it to the selected output PORT
  • 103. AS MAY BE CONÚRMED by examining the appro- PRIATE HEADER ÚLE IN A TEXT editor such as Windows Notepad. An interesting observa- tion at this stage relates to the ‘endp’ or end program PLC instruction, which is of course, yet another macro. Anexaminationoftheheader ÚLE SHOWS THAT THIS IS SIMPLY a jump instruction, which forcesthePLCprogramtorun Listing 2.6. Creating a self-latching circuit by reading the state of an output (Lst2_6.asm) Listing 2. 7. Using the latch command (Lst2_7.asm) ,ISTINGªª#REATINGªAª@SYSTEMªARMED ªmASHINGªOUTPUTª ,ST?ASM Listing 2.9. A simple alarm program (Lst2_9.asm)
  • 104. Everyday Practical Electronics, December 2009 continuously–thisbeingthebasisofthe PLC’s repeating scan cycle. An obvious conclusion based on the above macro substitution is that any machine code programs are likely to be considerably larger than the source code might suggest. Thus, the main advantage of the ladder logic approach IS IN SIMPLIÚCATION OF THE DESIGN PROC- ess, rather than reduction in code size. Summary and next steps This second part of the series began BY CONSIDERING THE CREATION OF ÛASHING outputsofawiderangeoffrequenciesby using oscillator bits. We also looked at single-bitcombinationallogicfunctions, including AND, OR and Exclusive-OR, and discussed the potential incorpora- tion of inverted inputs and outputs (NAND and NOR for example). More complex logical circuits were solved by use of internal storage (auxiliary relays) to hold intermediate results. We then used feedback from outputs in order to create simple self-latching circuits (simple sequential logic) and combined THESE CONCEPTS TO CREATE A SIMPLE ÛASH- ing ‘system armed’ warning light and an alarm circuit. Wealsodiscussedthemacrosubstitu- tion method used by the PLC software, AND SAW THAT THE ÚNAL MACHINE CODE programwillbeconsiderablylargerthan the source code would suggest. Hopefully, the power of ladder logic as a design tool has been in part demon- strated by the fact that a simple burglar alarm system could be created in ap- PROXIMATELY ÚVE LINES OF SOURCE CODE (as seen in Listing 2.9), and without any need to delve into the internal architec- ture of the chosen PIC microcontroller. The next part of the series will con- tinue the tour of the sequential logic ca- pabilitiesofthePLCsoftware,bylooking at timers and shift registers. The use of timers will enable an action to be per- formed for a given period of time, while shift registers will make it easy to create simple running light displays. Fig.2.7. Macro substitution, as used by the PLC software’s ‘ld’ instruction Please add £2.75 pp per order. Prices include UK VAT. See website for overseas prices. Special Offer prices for limited period or while stocks last. Peak Electronic Design Ltd, West Road House, West Road, Buxton, Derbyshire, SK17 6HF. tel. 01298 70012 www.peakelec.co.uk sales@peakelec.co.uk Measure capacitance and ESR! Capacitance from 1uF to 22,000uF ESR from 0.01 ohms to 20 ohms Battery included + Gold plated croc clips This new model of the famous offers all the great features of the ESR60 but with extended measurement range and audible alerts. Atlas ESR Atlas ESR PlusThis is the ! The New Atlas ESR Plus, Model ESR70 Atlas SCR - Model SCR100 Atlas ESR - Model ESR60 £89 inc VAT £75 inc VAT £79 inc VAT Passive component analyser. Automatically identify and measure inductors, capacitors and resistors. Auto frequency selection. Removable probes. 1uH - 10H 1pF - 10,000uF 1 Ohms - 2M Atlas LCR - Model LCR40 £79 inc VAT NEW MODEL Special Offer! Includes the Atlas LCR Passive Component Analyser (model LCR40), Atlas DCA Semiconductor Analyser (model DCA55), premium padded carry case and user guides. Complete with extra spare battery. You’re ready to go! Atlas Star Pack (LCR/DCA) £125 inc VAT Ideal Gift and Money Saving too! This pack saves you £20 Connect Triacs or Thyristors any way round. Auto part identification and pinout display. Categorises gate from 100uA to 100mA. Load conditions regulated at 12V, 100mA, even for a dying battery. Measures gate voltage drop. Long life alkaline battery supplied. Supplied with premium probes. electronic design ltd Christmas gift ideas... Capacitance from 1uF to 22,000uF. ESR from 0.01 ohms to 40 ohms. Great for ESR and low resistance measurements (short tracing etc). Automatic controlled discharge function. Audible Alerts (for good ESR, poor ESR, open circuit and more). Gold plated croc clips. User Guide and Battery included. was £97 was £87 Atlas DCA - Model DCA55 £55 inc VAT Darlingtons MOSFETs Diodes Transistors LEDs and more... The famous Peak Atlas, now with fitted premium probes. Just connect any way round to identify the type of semiconductor, pinout and lots of parameters too. Complete with battery, user guide and probes. Look! New Probes. Reduced Price! ...and if you change your mind after Christmas then no worries, you can have an exchange or refund without question. “ “
  • 105. HandsOn Technology http://www.handsontec.com ISP to ICP Programming Bridge: HT-ICP200 In-Circuit-Programming (ICP) for P89LPC900 Series of 8051 Flash Controllers. ICP uses a serial shift protocol that requires 5 pins to program: PCL, PDA, Reset, VDD and VSS. ICP is different from ISP (In System Programming) because it is done completely by the microcontroller’s hardware and does not require a boot loader. Program whole series of P89LPC900 µController from NXP Semiconductors… USB-RS232 Interface Card: HT-MP213 A compact solution for missing ports… Thanks to a special integrated circuit from Silicon Laboratories, computer peripherals with an RS232 interface are easily connected to a USB port. This simple solution is ideal if a peripheral does not have a USB port, your notebook PC has no free RS232 port available, or none at all ! Classic P89C51 Development/Programmer Board: HT-MC-02 HT-MC-02 is an ideal platform for small to medium scale embedded systems development and quick 8051 embedded design prototyping. HT-MC-02 can be used as stand-alone 8051 C Flash programmer or as a development, prototyping, industry and educational platform. For professional, hobbyists…
  • 106. 42 Everyday Practical Electronics, January 2010 Teach-In 2010 By Walter Ditch TEACH-IN 2010 LADDER LOGIC PROGRAMMING FOR THE PIC MICRO Part 3: Timers and Shift Registers P ART three of this series on ladder logic (PLC-style) pro- gramming for the PIC micro continues the tour of sequential logic by looking at timers and shift registers. This builds upon previous coverage of input/output commands, oscillators, combinational logic and self-latching circuits, allowing an increasingly wide variety of systems to be developed. Timers often prove useful when building ladder-logic-based systems, making it easy to add time delays and timed outputs. For example, delaying AN ACTION FOR A SPECIÚC INTERVAL AN ON delay timer) or performing a task for a given period of time (a pulsed timer output).Timerapplications considered here will include an automatic alarm timer and a switch de-bounce circuit. Shift registers Shift registers are also valuable, allowing a binary pattern held in a register to be shifted to the left or right. A typical shift register application would be the creation of a moving light display, although they have many other uses. The present article will also delve into the PLC software’s use of internal memory (registers). This knowledge mayberequiredwhenwritingprograms, andoftenprovesusefulwhendebugging ladder logic software applications. For example, the internal state of a timer or counter is normally only visible to the PROGRAMMER AS A SINGLE ÚNISHEDNOT ÚNISHEDSTATUSBIT
  • 107. BUTTHEINTERNALCOUNT valueisalsoavailableasabytevalue–if you know where to look. In passing, a few of the PLC soft- ware’s byte processing commands will be introduced, these being used to sim- plify the coding of some of the example programs. A byte I/O command, for example, will be used to display the internal content of a shift register on a chosen output port. We’ll also make use of a byte comparison command to simplify the coding of a rudimentary ‘KnightRider’ style display. Coverage of the sequential logic capabilities of the PLC software will continue next month with the intro- duction of counters and pulse-width- modulated (PWM) signals. As discussed previously, all pro- gram listings for this article are avail- able from the Library Project Code section of the Everyday Practical Electronics website (www.epemag. com). It is suggested that you copy THE ÚLES FROM EACH PART OF THE SERIES into a single folder on your com- puter, which will ensure you have EASY ACCESS TO THE 0,# HEADER ÚLES supplied with Part 1. You should also have installed the MPLAB IDE software, and of course you will need a suitable PIC development board or simulation software in order to actu- ally try out your programs. Please see earlier articles for further details of the development process, supported PIC microcontrollers, and associated hardware and software. Also, remember that the example programs may easily be converted to run on any of the supported PIC micro- CONTROLLERS 4O DO THIS
  • 108. ÚRST MODIFY THE HEADER ÚLE REFERENCE
  • 109. AND THEN CHANGE input and output port assignments to suit those available with the chosen microcontroller. Using low speed timers So far, most of the programs consid- ered have either produced an output IF A SPECIÚC CONDITION IS TRUE AT THAT instant (combinational logic), or have latched a momentary input signal (sim- ple sequential logic). This has allowed the development of some useful ap- plications, including the simple alarm circuit of Listing 2.9, as seen in Part 2. A useful addition to this circuit would be the use of a timer to cancel the alarm after a period of inactivity. 4O THAT END
  • 110. WEmLL ÚRST SEE HOW TO CON- ÚGURE A LOW SPEED TIMER
  • 111. AND THEN USE a timer with a simple alarm circuit. The PLC software provides up to 16 built-in timers, eight of which are ‘low speed’, with the remainder
  • 112. Everyday Practical Electronics, January 2010 43 Teach-In 2010 An important difference between a timer and a latch is that the en- able input needs to be continuously applied, in order to ‘enable’ the timer to count. If a momentary enable input is required, then this should be used TO ÚRST SET A LATCH
  • 113. WITH THE LATCHED output enabling the timer. A typical example would be the addition of a timeout feature to the alarm circuit previously considered in Part 2, List- ING ! POSSIBLE MODIÚED PROGRAM is given in Listing 3.2, based on the PIC16F627/627A microcontroller. Considering the program opera- tion, it can be seen that Port A bits 0-2 act as three separate input sen- sors. The combined sensor status is stored temporarily in auxiliary relay Begin counting An enable signal derived from Port A bit 0 causes the timer to begin COUNTING 4HE TIMER IS PRECONÚGURED WITH A ÚNAL VALUE IN THE RANGE OF TO 255, which allows time delays of up to 255 seconds to be achieved. The timer’s status bit becomes set after the time period has expired. Removing the enable bit resets the timer to its initial value and clears the output bit of the timer. Thus, the timer has three possible states. 1. Reset (enable input = 0, status output = 0) 2. Timer in progress (enable input = 1, status output = 0) 4IMER ÚNISHED ENABLE
  • 114. STATUS = 1) Fig.3.1. Using a low-speed timer to GIVEªAªlVE SECONDªDELAY being ‘high speed’. For time delays in the range 4ms to 1 second, you can use a high-speed timer, while longer delays, in the range 1 to 255 seconds, may be achieved with a low-speed timer. (Even longer delays are pos- sible by using ‘custom timer’ circuits, as will be seen in Part 4.) The creation of a sim- ple time delay using a low-speed timer is shown in the ladder diagram of Fig.3.1 above. This example provides A ÚVE SECOND TIME DELAY (an on-delay timer), with the timer’s output bit TIML bit 0, going high five seconds after the input bit PORTA bit 0. An equivalent program, based on the PIC16F88 microcontroller, is given in Listing 3.1 4HE ÚRST ARGUMENT SUP- plied to the low-speed timer command ‘timl’ is thetimernumber,whichis intherange0to7.Thecor- responding bit of register TIML(0-7)holdsthestatus bitforfortheselectedlow- speed timer. (Thus, TIML bit0holdsthestatusbitfor low-speed timer 0, and so on).RecallalsofromPart1, that PLC command names arelowercase(timl),while register names are upper case (TIML). include 16F88_L.PLC ; Defines PLC instructions ; (Low voltage programming enabled) ld PORTA, 0 ; Read Enable input timl 0, 05H ; Low Speed Timer 0, final value = 5 seconds ld TIML, 0 ; Read low speed timer 0 status bit out PORTB, 0 ; Output timer 0 status to Port B bit 1 endp ; Marks end of PLC program ,ISTINGªª#REATINGªAªlVEªSECONDªDELAYªUSINGªAªLOW SPEEDªTIMERª ,ST?ASM ; I/O Schedule ; Sensors = Port A bits 0-2 (1 = active) ; Armed/Reset = Port A bit 3 ; (1 = armed / 0 = reset) ; Output = Port B bit 0 (1 = triggered) include 16F627.PLC ; Defines PLC instructions ld PORTA, 0 ; Load Sensor 1 or PORTA, 1 ; Or with Sensor 2 or PORTA, 2 ; Or with Sensor 3 out AUX0, 0 ; Output Alarm Sensor Status to AUX0, 0 ld AUX0, 0 ; Read Alarm Sensor status (Set input) latch AUX0, 1, AUX0, 2 ; Latched Alarm Status to AUX0 bit 1 ; Reset = AUX0 bit 2 ld AUX0, 1 ; Read Latched Alarm status timl 0, 0x05 ; Low Speed Timer 0 with 5 second timeout ld TIML, 0 ; Read Alarm Timeout (1 = timeout reached) and_not AUX0, 0 ; Don't reset if active (* optional *) or_not PORTA, 3 ; OR with inverted Arm/Disarm input ; (0 = disabled) out AUX0, 2 ; Output Reset Alarm signal ld AUX0, 1 ; Read Latched Alarm signal and_not TIML, 0 ; Disable if timed out (* optional *) out PORTB, 0 ; Alarm output to buzzer / indicator endp ; Marks end of PLC program ,ISTINGªª!DDINGªAªTIMEOUTªTOªAªSIMPLEªALARMª ,ST?ASM
  • 115. 44 Everyday Practical Electronics, January 2010 Teach-In 2010 AUX0 bit 0, which in turn is used as the Set input to a latch circuit. The Q output of the latch is sent to bit 1 of register AUX0, while bit 2 of the same register provides the Reset input signal to the latch. Next, the latch output becomes the INPUT TO A ÚVE SECOND TIMER
  • 116. WITH THE timer output being used to reset the LATCH
  • 117. HENCE CANCELLING THE ALARM ÚVE SECONDS IS ÚNE FOR TESTING PURPOSES
  • 118. but a longer time delay would, of course, be used in practice). Finally, an audible or visible alarm output is generated by copying the latch output state to an appropriate output port bit (Port B bit 0 in this example). Notice that two of the program lines are marked as ‘optional’ in the comments at the right. Try adding and removing these lines to see the differ ent behaviours of the alarm, following a timeout. With both lines removed, the alarm will automatically reset after A TIME OUT
  • 119. THUS RE ENABLING THE ALARM (suitable for a retail exit barrier alarm, for example). However,thisbehaviourmightcause annoyanceinaresidential burglar alarm, where a faulty sensor could cause THEALARMTOBERE TRIGGERED REPEATEDLYAFTEREACHTIME out. In the latter case, adding the two optional LINES HAS THE EFFECT OF ÚRST preventing a reset while a sensor remains active, and second, cancelling theoutputifthealarmhas timed out. High-speed timer applications Operation of the eight HIGH SPEED TIMERS IS AL most identical to that al READYSEENWITHLOW SPEED timers, but with three SIGNIÚCANT DIFFERENCES
  • 120. AS given below. 4HE lTIMHm HIGH speed timer) command is used in place of ‘timl’. !S WITH LOW SPEED TIM ers, remaining command arguments are the timer number (0 to 7) followed BY THE ÚNAL TIMER VALUE IN the range 1 to 255. 2. The high speed tim er’s status bit is available from the appropriate bit of the TIMH register, with a value of ‘1’ indicat ING THAT THE TIMER IS ÚNISHED 2ECALL that low speed timers use the TIML register.) 3. The timer’s internal count value increments once every four millisec onds, giving possible time delays from 4ms to approximately one second. Note: As you may have already GUESSED
  • 121. LOW SPEED AND HIGH SPEED timers are actually implemented as counters, with the input to the coun ter being derived from an appropriate oscillator bit. This knowledge will prove useful in Part 4, when we build a custom timer. On the bounce One problem often encountered when dealing with input switches is that of contact bounce. This mechani cal effect is analogous to dropping a tennis ball onto a hard surface, and then watching it bounce several times before settling. Exactly the same effect occurs when the mechanical contacts of a switch are closed,butwiththetimeforthecontacts tosettlebeingmeasuredinmilliseconds. Contact bounce can be particularly troublesome where an input switch is directly connected to a counter, with a single switch press causing the counter to increment multiple times. A useful high speed timer applica tion would be a switch debounce cir CUIT
  • 122. WITH A TO MS ON DELAY TIMER being typically suitable. The output of THE ON DELAY TIMER MAY THEN BE USED as the debounced input signal. Listing 3.3 gives a simple example, written this time for the PIC16F887 microcon troller, and making use of a repeating input waveform being derived from an oscillator bit. Pulsed outputs The timers considered so far have all BEEN OF THE lON DELAYm VARIETY )T IS ALSO possible to produce a pulse output by MAKING A RELATIVELY SMALL MODIÚCATION to the program. The trick in this case is to realise that during the timer period the enable input will be high, while at the same time the status bit will be include 16F887.PLC ; Defines PLC instructions ld OSCH, 7 ; Read a 15.26 HZ waveform (T = 65.54 ms) out PORTD, 0 ; Send waveform to Port D bit 0 ld PORTD, 0 ; Read Port D bit 0 ; (15.26 Hz waveform = Enable input) timh 0, 03H ; High Speed Timer 0, final value = 3 ; (T = 3 x 4 ms = 12 ms) ld TIMH, 0 ; Read timer status bit out PORTD, 1 ; Output debounced signal endp ; Marks end of PLC program Listing 3.3. A switch debounce circuit based on a high speed timer (Lst3_3.asm) include 16F887.PLC ; Defines PLC instructions ld OSCH, 7 ; Read a 15.26 HZ waveform (T = 65.54 ms) out PORTD, 0 ; Send waveform to Port D bit 0 ld PORTD, 0 ; Read Port D bit 0 ; (15.26 Hz waveform = Enable input) timh 0, 03H ; High Speed Timer 0, final value = 3 ; (T = 3 x 4 ms = 12 ms) ld TIMH, 0 ; Load timer status bit out PORTD, 1 ; Output debounced (on-delay) signal ld OSCH, 7 ; Read high speed timer Enable input and_not TIMH, 0 ; AND with inverted Status bit out PORTD, 2 ; Output pulse waveform to Port D bit 2 endp ; Marks end of PLC program Creation of on-delay and pulse output waveforms (Lst3_4.asm).Listing 3.4. Creation of on-delay and pulse output waveforms (Lst3_4.asm)
  • 123. Everyday Practical Electronics, January 2010 4 Teach-In 2010 outputs respectively. Notice that, based on the timebase of 5ms per division, the pulse width is approximately 12ms, which is in agreement with the delay value selected in Listing 3.4. Use of internal storage and debugging programs An understanding of the PLC software’s use of internal memory is useful when debugging pro- grams, and may in some cases be required when actually writing programs (as will be seen in the next section). The PLC software uses a variety of PIC registers to hold its internal state, some of which have already been introduced. Each of these registers (around 100 in total) holds a single byte of data. Addresses associated with these registers, and others yet to be introduced, can be viewed by opening ANY OF THE 0,# HEADER ÚLES IN A TEXT editor. Listing 3.5 shows a short (and SLIGHTLY SIMPLIÚED EXTRACT Considering the timers discussed in the previous section, each of the low and high frequency timers uses a dedicated register to hold its internal COUNT VALUE
  • 124. IN ADDITION TO THE ÚN- ISHEDNOT ÚNISHED STATUS BITS HELD IN the TIMH and TIML registers. Under normal circumstances, the internal count values are not directly visible to the programmer. However, it may be useful to view these registers when debugging programs – after, of course, ÚNDING THE APPROPRIATE ADDRESSES FROM THE HEADER ÚLE Available debugging options related to the display of internal registers include: 1. Adding one or more ‘watch’ com- mands in an Integrated Development low. Listing 3.4 shows the creation of bothon-delayandpulsedoutputs,once again using a repeating oscillator bit as the input. Resulting waveforms are shown in Fig.3.2, which was produced with the program of Listing 3.4 running on a PICkit 2 Debug Ex- press development board, and viewed using a Tektronix TDS2004B four- channeldigitalstor- age oscilloscope. In this case, the original wave- form is shown in orange, while the blue and magenta traces give the on- delay and pulse Fig. 3.2.Output waveforms viewed using an oscilloscope OSCH E H 01 ; High fre uency oscillator register A 0 E H 20 ; Internal relay outputs A 1 E H 21 A 2 E H 22 A 3 E H 23 A 4 E H 24 A 5 E H 25 A 6 E H 26 A 7 E H 27 ; (8 bytes x 8 bits = 64 internal relays) OSCL E H 28 ; Low fre uency oscillator register Listing 3.5. A small selection of internal memory used by the PLC software Fig.3.3. Debugging with the aid of the Watch window in Proteus VSM software
  • 125. 4 Everyday Practical Electronics, January 2010 Teach-In 2010 Notice that the above listing uses THE l8m PREÚX TO INDICATE A NUMBER IN HEXADECIMAL FORMAT 4HIS FORMAT WAS ALSO SEEN WHEN ADDING A WATCH STATEMENT IN 0ROTEUS 63-
  • 126. IN IG AND THE ASSOCIATED TEXT 4HE -0,! )$% ASSEMBLER -0!3- ACCEPTS NU- MERIC DATA IN A VARIETY OF OTHER NUMBER BASES RADIXES AND FORMATS
  • 128. OCTAL
  • 129. DECIMAL OR DENARY AND HEXADECIMAL ! FEW OF THE ACCEPTED FORMATS IN- CLUDE Bmm BINARY
  • 131. Dmm DECIMAL AND HmFFm HEXADECIMAL
  • 132. WITH THE ÚRST CHAR- ACTER BEING ACCEPTED IN EITHER UPPER OR LOWER CASE /NE WHICH IS MOST SUITABLE DEPENDS ON YOUR PERSONAL PREFERENCE
  • 133. TOGETHER WITH THE APPLI- CATION 3EE THE -0!3- ASSEMBLERmS HELP ÚLE FOR A FULL LIST OF SUPPORTED NUMBER FORMATS 7EmLL REVISIT THE USE OF BYTE TRANSFER INSTRUCTIONS IN THE NEXT SECTION
  • 134. WHERE THEY WILL BE USED WITH SHIFT REGISTER PROGRAMS TO MAKE THE RESULT VISBLE ON A BANK OF OUTPUT ,%$S Shift registers 3HIFT REGISTERS ARE USEFUL CIRCUITS
  • 135. WHICH HAVE MANY POTENTIAL USES
  • 136. IN- CLUDING THE CREATION OF MOVING LIGHT DISPLAY PATTERNS
  • 138. OR EVEN THE TEMPORARY STORAGE OF PASS FAIL INFORMATION RE- LATED TO COMPONENTS passing along a pro- DUCTION LINE 4HE IN- TERNAL STRUCTURE OF A SIMPLE SHIFT REGISTER IS SHOWN IN IG 4HIS SIMPLE SHIFT REGISTER HOLDS A NUMBER OF DATA BITS INSIDE AN INTERNAL WORKING REGISTER %ACH CLOCK PULSE CAUSES THE DATA TO BE SHIFTED ONE PLACE TO THE RIGHT
  • 139. IN THE DIRECTION OF THE AR- ROWS .EW DATA IS SHIFTED IN AT THE LEFT HAND SIDE SUPPLIED BY AN EXTERNAL SOURCE
  • 140. WHILE OLD DATA IS SHIFTED OUT AT THE RIGHT BEING EITHER DISCARDED OR USED ELSEWHERE !LTHOUGH THIS SIMPLE SHIFT REGISTER IS UNIDIRECTIONAL
  • 141. A USEFUL ADDITIONAL FEATURE WOULD BE A $IRECTION INPUT
  • 142. ALLOWING DATA TO BE SHIFTED EITHER TO THE LEFT OR RIGHT
  • 143. UNDER PROGRAM CONTROL 5P TO EIGHT SHIFT REGISTERS ARE AVAIL- ABLE IN THE 0,# SOFTWARE NUMBERED TO
  • 144. EACH OF WHICH HAS AN BIT WORKING REGISTER 4HESE MAY BE USED SINGLY
  • 145. OR MAY BE LINKED TOGETHER lEND TO ENDm IN MULTIPLES OF BITS
  • 146. ALLOWING A COMPOSITE SHIFT REGISTER WITH UP TO BITS TO BE CREATED %ACH SHIFT REGISTER HAS AN lIMPLICITm DATA INPUT
  • 147. PROVIDED BY THE RESULT OF THE PREVIOUS INSTRUCTION
  • 150. EACH OF WHICH ARE SPECIÚED USING A PORT NAME AND A PORT BIT ! DEDICATED BIT WORKINGREGISTERHOLDSTHEINTERNALSTATE OFEACHSHIFTREGISTER
  • 151. ANDTHISVALUEMAY BE COPIED TO AN OUTPUT PORT
  • 152. IF REQUIRED 4HE SYNTAX OF THE SHIFT REGISTER COM- MAND HAS THE FOLLOWING GENERAL FORM shift NUMBER[0-7], CLOCK_REG, CLOCK_BIT[0-7], RESET_REG, RESET_BIT[0-7], DIRECTION_REG, DIRECTION_ BIT[0-7] Syntax Function puti TE, RE ISTER Loads an immediate byte value into a destination register (puti = put immediate). putr RE 1, RE 2 Copies the content of a source register to a destination register, leaving the source unaltered (putr = put register). Table 3.1. Available byte transfer commands include 16F627.PLC ; Defines PLC instructions puti 0x0F, A 0 ; Load 0x0F (hex.) into register A 0 putr A 0, PORT ; Copy A 0 register to Port endp ; Marks end of PLC program Listing 3.6. Transferring data bytes between registers (Lst3_6.asm) %NVIRONMENT )$%
  • 153. IN ORDER TO VIEW THE STATE OF INTERNAL REGISTERS AS THE PROGRAM IS RUNNING WHICH IS GENERALLY THE PREFERRED METHOD
  • 154. IF AVAILABLE 5SING A BYTE TRANSFER COMMAND TO TEMPORARILY COPY AN INTERNAL REGISTER TO AN OUTPUT PORT
  • 155. ALLOWING ITS STATE TO BE DIRECTLY VIEWED ON EXTERNALLY CON- NECTED ,%$S OR SEGMENT DISPLAYS Byte transfer OREXAMPLE
  • 158. SELECT THE 7ATCH 7INDOW OPTION FROM THE$EBUGPULL DOWNMENU.EXT
  • 159. RIGHT CLICK ON THE DISPLAYED 7ATCH WINDOW AND SELECT THE !DD )TEMS Y !DDRESS OPTION FROM THE CONTEXT MENU %NTER THE NAME OF THE REGISTER TO BE OBSERVED
  • 160. ITS ADDRESS WITH THE PREÚX l8m INDICATING A HEXADECIMAL NUMBER AND THE REQUIRED DISPLAY FORMAT IG SHOWSTHEADDITIONOFAWATCHSTATEMENT IN ORDER TO VIEW THE INTERNAL COUNT AS- SOCIATEDWITHLOW SPEEDTIMER REGISTER 4)-,
  • 161. THIS BEING SUITABLE FOR DEBUG- GING THE PROGRAM OF ,ISTING 3HOULD A FULL BLOWN )$% NOT BE AVAIL- ABLE
  • 162. THEN AN ALTERNATIVE WOULD BE TO USE A BYTE COPY COMMAND TO COPY THE REGISTER OF INTEREST TO AN UNUSED OUTPUT PORT YTE )/ COMMANDS MAY BE USED EITHER TO LOAD AN IMMEDIATE PROGRAM SPECIÚED BYTE VALUE INTO A REGISTER
  • 163. OR TO COPY A BYTE VALUE FROM ONE REGISTER TO ANOTHER 4ABLE GIVES THE SYNTAX AND OPERATION OF THE TWO AVAILABLE VARIANTS 4HE USE OF BYTE TRANSFER COMMANDS IS NOT MANDATORY
  • 164. BUT IS CERTAINLY MUCH QUICKER THAN THE REPETITIVE COPYING OF INDIVIDUAL BITS WITH lLDm AND lOUTm COMMANDS 4HE EXAMPLE OF ,ISTING ILLUSTRATES JUST HOW EASY IT IS TO LOAD A BYTEVALUEINTOATEMPORARYREGISTERAND THEN COPY THE RESULT TO AN OUTPUT PORT Fig.3.4. A simple shift register
  • 165. Everyday Practical Electronics, January 2010 4 Teach-In 2010 Fig.3.5. Ladder diagram for a simple shift register program The trick in this case is to under- stand exactly how data enters and exits each shift register. As already seen, the data input to a shift register is supplied by the result of the previous command. Similarly, data shifted out of one shift register becomes available to the next command (or is discarded if unused). Thus, all that is necessary to cascade multiple shift registers is to write each shift register command on successive lines, so the output of one shift register then becomes the input to the next. Use of one or more Watch state- ments is a useful strategy when debug- ging programs containing multiple shift registers, as long as a suitably equipped IDE is available. You may then create a watch statement for each shift register and observe data rippling through from one working register to the next. (Note in relation to Listing 3.8 that registers SHIFT0- SHIFT2 make use of memory loca- tions 0x47-0x49.) Light chaser 4HE ÚNAL EXAMPLE FOR THIS PART OF THE series involves repeatedly moving a single illuminated LED to the left and right of an output port, which is the basis of the well known KnightRider display (from the classic TV series of the same name). This is shown graphi- cally in Fig.3.6. A latch is used to control the di- rection of the shift register, with the latch being automatically set and reset as the illuminated bit ‘bounces’ off each side of the output register. Changing the direction of the shift register is achieved in software by linking the latch’s Q output to the Fig.3.6. Animating a simple ‘KnightRider’ display A simple shift register application is shown by the ladder diagram of Fig.3.5. The example program uses a 0.25Hz input signal as the data input to a shift register, with the clock being driven by a 1Hz signal. This creates an alternating pattern of two ones, followed by two zeros, since the clock frequency is four times faster than that of the data input. A visible output is produced by the ‘putr’ command, which copies the shift reg- ister’s output register (SHIFT0)acrosstoPort B. The equivalent pro- gramisgiveninListing 3.7, in this case based on the PIC16F627 mi- crocontroller. It is also straight- forward to link or ‘chain’ multiple shift registers, as shown in the example of Listing 3.8, this time written for the PIC16F887 microcontroller. include 16F887.PLC ; Defines PLC instructions ld OSCL, 7 ; Read OSCL bit 7 (Data input) shift 0, OSCL, 3, PORTA, 0, PORTA, 1 ; Shift register 0 ; Data in = OSCL bit 7 ; Clock = OSCL bit 3 ; Reset = Port A bit 0 ; Direction = Port A bit 1 shift 1, OSCL, 3, PORTA, 0 , PORTA, 1 ; Chained shift register 1 shift 2, OSCL, 3, PORTA, 0 , PORTA, 1 ; Chained shift register 2 putr SHIFT0, PORTD ; Copy SHIFT0 working register to Port D endp ; Marks end of PLC program Listing 3.8. Chaining multiple shift registers (Lst3_8.asm).Listing 3.8. Chaining multiple shift registers (Lst3_8.asm) include 16F627.PLC ; Defines PLC instructions ld OSCL, 5 ; Read OSCL bit 5 (Data input) shift 0, OSCL, 3, PORTA, 0, PORTA, 1 ; Shift register 0 ; clock = OSCL bit 3, ; Reset = Port A bit 0, ; Direction = Port A bit 1 putr SHIFT0, PORT ; Copy SHIFT0 working register to Port endp ; Marks end of PLC program Listing 3.7. A simple shift register program (Lst3_7.asm)Listing 3.7. A simple shift register program (Lst3_7.asm)
  • 166. 4 Everyday Practical Electronics, January 2010 Teach-In 2010 shift register’s direction input and then using the state of the left and right bits of the shift register’s output register to set and reset the latch, respectively. If a single illuminated bit can somehow be ‘injected’ into the shift register then this pattern will continuously shift left and right, as the latch is set and reset. Thus, the remaining problem is to inject an illuminated bit into the working REGISTER IN THE ÚRST PLACE In comparison One answer would be to design a combinational logic circuit that would detect the binary pattern ‘0000 0000’ and then automatically inject a logic 1 into the shift register. This is quite feasible, but a simpler solution would be to introduce an appropriate instruction from the byte comparison family of commands. These commands either allow a reg- ister to be compared with a numeric value (immediate value), or permit two registers to be compared, with the command outputting a logic 1 if the result of the comparison is true. Avail- able byte comparison types include: Greater than (immediate and register-based – gti and gtr commands) Greater than or equal (immedi- ate and register-based – gtei and gter commands) Equal (immediate and register- based – eqi and eqr commands) Not equal (immediate and register- based – nei and ner commands) Less than (immediate and register- based – lti and ltr commands) Less than or equal (immediate and register-based–lteiandltercommands). Thus, we can use the ‘eqi’ (equal to an immediate value) command to inject a logic 1 into the shift register, should the output register be empty. The resulting program is given in Listing 3.9, written for the PIC16F627/627A microcontroller. Notice that the program uses bit 0 of Port A as the reset input. This is ÚNE IF YOU WANT THE ABILITY TO MANU- ally enable and disable the output display. If you want to run the shift register continuously then it is pos- sible to permanently disable the reset input, either in hardware or in software. The hardware approach is to physically ground the reset input, although this effectively wastes an input port bit. You can also disable the reset input in software, by replacing the refer- ence to PORTA, 0 with a reference which always returns a ‘0’. To this end, the PLC software provides a reg- ister with the name ‘LOGIC’, with bit 1 of this register preprogrammed to a value of ‘1’ and bit 0 of the same reg- ister containing ‘0’. Thus, replacing the reference to ‘PORTA, 0’ in Listing 3.9 with ‘LOGIC, 0’ will permanently disable the reset function. This is clearly a remarkably com- pact program, considering the com- plexity of the task performed. The main sub-tasks performed by the program are: 1. Using a latch to control the shift register direction. 2. Setting and resetting the latch when a non-zero bit reaches bits 7 and 0 of the shift register’s working register, respectively. 3. Injecting a logic 1 into the shift register if the working register is empty. 4. Copying the shift register’s work- ing register to an output port, in order to make it visible. 5. Optionally allowing the display to be blanked by resetting the shift register. 4OCONÚRMYOURUNDER- standing of the program’s operation,youshoulden- sure that you can match eachoftheabovedescrip- tive points to the actual section of code perform- ing that task. Note that we’ll be using a sequencer com- mand later in the series to create much more POWERFUL AND ÛEXIBLE ANIMATED DIS- plays than those seen so far – and the associated programs will be even shorter! Summary Part 3 of the series has contin- ued the tour of the PLC software’s sequential logic capabilities, focus- ing on timers and shift registers. Low-speed and high-speed timers have been introduced, offering time delays ranging from four millisec- onds to approximately 255 seconds. 4HE CONÚGURATION OF ON DELAY AND pulse output timers has been dis- cussed, and these have been applied in applications as diverse as alarms and switch debounce circuits. A range of shift register applica- tions has also been developed. This has included the use of single and chained shift registers, repeating pattern displays based on oscilla- tor bit inputs, and even a simple KnightRider-style display. We have looked at the use of in- ternal memory by the PLC software, and have seen how this knowledge could be used when debugging PLC software, either by adding watch statements, using a suitably capable IDE, or by adding debugging instruc- tions to programs. A number of byte processing instruction categories has also been introduced and used to sim- plify the coding of programs (selected byte transfer and byte comparison commands were used). Next month The next part of the series will in- troduce further sequential logic capa- bilities of the PLC software, including counters and the creation of pulse- width-modulated (PWM) signals. include 16F627.PLC ; Defines PLC instructions ; Latch controls shift direction ; (direction changes when 1 reaches end) ld SHIFT0, 7 ; MSb of working register = Set input latch A 0, 0, SHIFT0, 0 ; A 0, 0 = output ; LSb of working register = Reset input e i PORT , 0x00 ; Input a logic-1 if Port = 00000000 shift 0, OSCL, 0, PORTA, 0, A 0, 0 ; Shift register 0, clock = OSCL bit 0, ; Reset using Port A bit 0 = 1 ; Direction = output of latch putr SHIFT0, PORT ; Copy SHIFT0 working register to Port endp ; Marks end of PLC program Listing 3.9. A simple light chaser program
  • 167. HandsOn Technology is a manufacturer of high quality educational and professional electronics kits and modules, uController development/evaluation boards. Inside you will find Electronic Kits and fully assembled and tested Modules for all skill levels. Please check back with us regularly as we will be adding many new kits and products to the site in the near future. Do you want to stay up to date with electronics and computer technology? Always looking for useful hints, tips and interesting offers? http://www.handsontec.com Inspiration and goals... HandsOn Technology provides a multimedia and interactive platform for everyone interested in electronics. From beginner to diehard, from student to lecturer... Information, education, inspiration and entertainment. Analog and digital; practical and theoretical; software and hardware... HandsOn Technology provides Designs, ideas and solutions for today's engineers and electronics hobbyists. Creativity for tomorrow's better living... HandsOn Technology believes everyone should have the tools, hardware, and resources to play with cool electronic gadgetry. HandsOn Technology's goal is to get our hands On current technology and information and pass it on to you! We set out to make finding the parts and information you need easier, more intuitive, and affordable so you can create your awesome projects. By getting technology in your hands, we think everyone is better off We here at HandsOn like to think that we exist in the same group as our customers curious students, engineers, prototypers, and hobbyists who love to create and share. We are snowboarders and rock-climbers, painters and musicians, engineers and writers - but we all have one thing in common...we love electronics! We want to use electronics to make art projects, gadgets, and robots. We live, eat, and breathe this stuff!! If you have more questions, go ahead and poke around the website, or send an email to sales@handsontec.com. And as always, feel free to let your geek shine - around here, we encourage it...
  • 168. Everyday Practical Electronics, February 2010 49 Teach-In 2010 By Walter Ditch TEACH-IN 2010 LADDER LOGIC PROGRAMMING FOR THE PIC MICRO Part 4: Counters and Pulse- Width-Modulated Waveforms P ART four of this series on ladder logic (PLC-style) programming for the PIC micro continues the tour of sequential logic features by looking at counters and the genera- tion of pulse-width-modulated (PWM) waveforms. (Recall that previous in- stalments have covered topics includ- ing inputs and outputs, combinational logic, oscillators, latches, timers, shift registers, byte transfer and byte com- parison commands.) Thesebuildingblockshavebeenused toconstructanumberofsimplesystems, using a programming approach called ladderlogic,whichhascloseparallelsto thedesignandconstructionofelectronic circuits. Thus, the designer (that’s you!) simply uses ladder logic program state- ments to connect together the required electronic building blocks in order to construct a fully working system. A machine code program is then automatically generated for the chosen PIC microcontroller by using the as- sembler’s macro substitution feature. This process has close parallels with the use of a compiler to convert a high levellanguageprogram(suchasBASIC, PascalorC)intomachinecode–includ- ing, of course, the inevitable increase in SIZE OF THE ÚNAL MACHINE CODE PROGRAM It must be admitted that the macro substitution method used here lacks some of the sophistication of a true high level language, such as syntax checking and meaningful (high level) error messages. However, electronics ENTHUSIASTS SHOULD ÚND IT RELATIVELY easy to write ladder-logic-style pro- grams, and the source code programs are normally very concise. I hope that you will use the tech- niques presented here in order to adapt the example programs, and to develop new ladder logic programs. It really is most satisfying to see your own design running on a small piece of silicon, per- forming tasks exactly as you intended! Software Asexplainedpreviously,allprogram listingsforthisseriesareavailablefrom theLibraryProjectCodesectionofthe Everyday Practical Electronics website (www.epemag.com). You’ll also need THE HEADER ÚLES SUPPLIED WITH 0ART
  • 169. which should be ‘unzipped’ into a single folder, together with the sample ÚLES FROM EACH PART OF THE SERIES Make sure you have installed the freely available MPLAB IDE software, which will be needed to assemble the example programs. And of course, in order to actually test the programs, you will need a suitable PIC development BOARD
  • 170. ÚTTED WITH ONE OF THE SUPPORTED PIC microcontroller types, or simula- tion software such as Proteus VSM from Labcenter Electronics. Counter applications As their name suggests, counters are used when you need to keep track of the number of times an event has oc- curred. In its most basic application, the counter simply provides a signal when the predetermined number of input signals has been detected – as in a simple unidirectional counter. Counters are also available which can count up or down – a bidirectional counter. Both types of counter main- tain a running total of the number of inputs received, in addition to the MORE BASIC ÚNISHEDNOT ÚNISHED STATUS output. Counters may be used as build- ing blocks in a wide variety of more complex designs, with motor control being a typical application. For ex- ample, linking a counter to a stepper motor controller will allow a simple position control system to be created. It is also possible to vary the speed of a DC motor by using a counter as the input to a variable PWM waveform. In this case, a unidirectional counter would provide a ‘soft start’ feature, and a bidirectional counter would allow the motor speed to be dynamically increased or decreased. Unidirectional counters may also be combined with oscillator signals to create custom time delays, as will be seen shortly.
  • 171. 50 Everyday Practical Electronics, February 2010 Teach-In 2010 on a simulator, such as Proteus VSM, compared to a real PIC development board – and the difference is no fault of the simulator. Switch bounce is an un- wanted effect associationed with real switches, and can cause the counter to jump forward by an unpredictable number of steps for each key-press. Fortunately, a software-based switch debounce circuit has already been developed (refer back to Listing 3.3 and associated text) which can be easily added, as given in the program of Listing 4.2. On-delay timer You can see that the original input to the counter (bit 0 of Port A) is now used to drive an on-delay timer hav- ing a delay of 12ms. The output of the on-delay timer (bit 0 of register TIMH) in turn becomes the input to the coun- ter, with the remainder of the second PROGRAM BEING IDENTICAL TO THE ÚRST ! useful exercise is to load the programs of Listings 4.1 and 4.2 on to a suitable development board, comparing the ac- tual number of switch presses required to set the counter’s Status bit – the ÚRST MAY VARY AND THE SECOND WILL BE exactly ten switch presses every time. As mentioned earlier, it is easy to create a custom timer by combining an oscillator waveform and a unidirec- tional counter. Referring back to Part 2, Table 2.1, it can be seen that a variety Unidirectional counters The PLC software provides up to eightunidirectional(uponly)counters, plus a further eight bidirectional counters. Operation of a basic unidi- rectionalcounterisquitesimilartothat alreadyseenwithtimers,whichshould come as no surprise, since a timer is little more than a counter with an oscil- lator hard-wired to its input. A simple unidirectional counter application is illustrated by the example of Fig.4.1. include 16F88_L.PLC ; Defines PLC instructions ; (Low voltage programming enabled) ld PORTA, 0 ; Read Port A bit 0 (clock input) ctr 0, 0AH, PORTA, 1 ; Counter 0 ; Final value = 10 (0AH), ; Reset = Port A bit 1 ld CTR, 0 ; Read counter 0 status bit (1 = finished) out PORTB, 0 ; Output counter 0 status to Port B bit 0 endp ; Marks end of PLC program The previous input value provides the clock input to the counter, which is typically the result of a ‘ld’ or ‘ld_not’ instruc- TION 4HE ÚRST PARAM- eter actually supplied to the ‘ctr’ command is the counter number, which must be in the range 0-7. Remaining PARAMETERS ARE THE ÚNAL value (1-255), followed by the reset register and reset bit (0-7). Each rising edge of the Clock input causes the internal counter register to increment. The counter’s Status bit becomes set when the counter reaches its PRE PROGRAMMED ÚNAL value, which is in the range 1-255 (a final value of 10 is shown in the example of Fig.4.1). The counter’s status bit is available from the Listing 4.1. Counting pulses using a unidirectional counter (Lst4_1.asm) equivalent bit of the CTR register (so, for example, bit 0 of the CTR register holds the status bit for counter 0). Both the internal count value and the status bit are cleared by applying a logic 1 to the Reset input. So, the Reset input must be held low during normal operation of the counter. The internal count value is not re- quired in simple counter programs, so IT IS SUFÚCIENT TO KNOW THAT THE COUNTER IS EITHER ÚNISHED 3TATUS
  • 173. INTERNAL count values are available, if required, fromregistersCTR0-CTR7respectively, and this running total may be used in more advanced applications. (An in- ternal count value will be used later as partofamotorspeedcontrollersystem, and further counter-based applications will be explored in Part 6.) An equivalent program is given in Listing 4.1, written for the PIC16F88 microcontroller, and with low volt- age programming enabled on bit 3 of Port B. The program uses the result from the previous command as the Clock input (obtained by reading the state of Port A bit 0), while Port A bit 1 provides the Reset input to the counter. The Status bit for counter 0 is loaded from bit 0 of the CTR register and is displayed on Port B bit 0. This is one program which may give a visibly different result when tested Fig.4.1. A simple counter circuit, shown in ladder diagram form include 16F88_L.PLC ; Defines PLC instructions ; (Low voltage programming enabled) ld PORTA, 0 ; Read Port A bit 0 (Count input) timh 0, 03H ; High Speed Timer 0, final value = 3 ; (T = 3 x 4 ms = 12 ms) ld TIMH, 0 ; Read timer status bit (debounced input) ctr 0, 0AH, PORTA, 1 ; Counter 0, final value = 10 (0AH), ; Reset = Port A bit 1 ld CTR, 0 ; Read counter 0 status bit (1 = finished) out PORTB, 0 ; Output counter 0 status to Port B bit 0 endp ; Marks end of PLC program Listing 4.2. Adding a debounced switch input to the simple counter application (Lst4_2.asm)
  • 174. Everyday Practical Electronics, February 2010 5 Teach-In 2010 of oscillator frequencies are available from registers OSCH and OSCL, with period times ranging from 512Ps to 16.77 seconds.Combiningtheseinputs with the ability to count from 1-255 input cycles gives an incredibly wide range of potential time delays, ranging from a few milliseconds up to a maxi- mum of 255 × 16.77 seconds, or 4,276 seconds (approximately 71 minutes). As an example, let’s assume that a timedelayof20minutes(1200seconds) is required – for a burglar alarm time- out perhaps. A quick calculation shows that 1200 seconds ÷ 255 would require a period time of 4.7 seconds, which unfortunately is not directly available from the OSCL or OSCH registers. However, from Table 2.1, the next higher period time is 8.389 seconds, whichisavailablefrombit6oftheOSCL register. A quick calculation shows that a count value of 143, combined with a periodtimeof8.389secondswouldgive a calculated time delay of 1199.627 sec- onds,whichisveryclosetoourrequired timedelayvalue.Listing4.3showshow this might be coded for the PIC16F627 microcontroller. Don’t expect this program to do anything too exciting – it takes 20 minutes just to turn on a single LED! However, it might be useful to combine this custom timer with the burglar alarm program previ- ously seen in Listing 3.2, in order to provide a more practical time-out period. (This is left as an exercise for the reader.) Longer delays If even longer delays are required, then it is pos- sible to cascade multiple counters, in a similar way to the shift registers seen in Part 3. You can link up to eight counters, thus creating a single hybrid counter/timer up to eight bytes wide. The trick in this case is to use each counter’s status output ‘directly’ as the count input to the next stage, at the same time using it to reset the current stage OF THE COUNTER !N OVERÛOW FROM THE previous counter will then cause the next stage to increment, before reset- ting the current stage back to zero. As an example, Listing 4.4 shows a two- stage custom timer, this time written for the PIC16F887 microcontroller. A repeating 1Hz oscillator waveform IS USED AS THE INPUT TO THE ÚRST COUNTER
  • 175. WHICH HAS A ÚNAL VALUE OF .OTICE that the counter uses its own status bit to reset itself back to zero. The output OF THE ÚRST COUNTER AUTOMATICALLY BE- comes the input to the next counter (or may be manually read from bit 0 of the CTR register), causing the sec- ond counter to be cascaded from the ÚRST q THIS TIME HAVING A ÚNAL VALUE of six, and once again using its own status bit as a reset signal. The state OF EACH COUNTER IS ÚNALLY COPIED TO registers PORTC and PORTD, allowing direct viewing on LEDs assumed to be connected to these ports. (Listing 4.4 is particularly suitable for use with the Proteus VSM 16F887 simulation supplied with Part 1.) The next section considers bidirec- tional or up/down counters, which tend to be more versatile than their unidirectional counterparts, although quite similar from a programming perspective. Bi-directional (up/down) counters Eight bi-directional counters are available, and suitable for applications where it is necessary to count values which may either increase or decrease. Consider as an example, a system designed to control entry to a car park, based on the number of spaces available. In this case, the number of spaces available would decrease as cars enter the car park, but would rise as cars leave. Coding of the bi-directional counter command is similar to its unidirec- tional counterpart, but with the addi- tion of a direction control input. The ctr_ud command has the following syntax: include 16F627.PLC ; Defines PLC instructions ld OSCL, 6 ; 8.389 s periodic time clock input ctr 0, d'143', PORTA, 1 ; Counter 0, final value = 143 ; Reset = Port A bit 1 ld CTR, 0 ; Read counter 0 status bit (1 = finished) out PORTB, 0 ; Output counter 0 status to Port B bit 0 endp ; Marks end of PLC program Listing 4.3. Using a custom timer to create a 20 minute delay (Lst4_3.asm) include 16F887.PLC ; Defines PLC instructions ld OSCL, 3 ; Count 1 second pulses ctr 0, d'10', CTR, 0 ; Count to 10 then reset ctr 1, d'6', CTR, 1 ; Count to 6 then reset putr CTR0, PORTC ; Copy low byte to Port C putr CTR1, PORTD ; Copy high byte to Port D endp ; Marks end of program Listing 4.4. Creating a multiple-byte custom counter/timer (Lst4_4.asm) ctr_ud CTR_NUMBER[0-7], FINAL_VALUE[1-255], DIRECTION_REGISTER, DIRECTION_BIT[0-7], RESET_REGISTER, RESET_BIT[0-7] A further difference is the provision of two status bits, compared to the one used by the unidirectional counter. The upper threshold is set when the ÚNAL VALUE IS REACHED AND THE LOWER one by the initial value. These status bits may be read from the appropri- ate bits of registers CUP (count up STATUS AND #$. COUNT DOWN STATUS respectively. (So, for example, the up- per and lower status bits for up/down COUNTER ÚVE WOULD BE AVAILABLE FROM BITS #50
  • 177. RESPECTIVELY Applying a 1 to the Reset input clears the internal count value, at the same time setting the appropriate bit of the #$. REGISTER SINCE THE INTERNAL COUNT now contains zero). Current count value If you need to know the current count value, then this information is available from registers CUD0–
  • 178. 5 Everyday Practical Electronics, February 2010 Teach-In 2010 cars currently inside the car park, and this would need to be scalable to an arbitrary number of digits, to suit the actual capacity. The number of available spaces would need to be displayed in decimal form, since few motorists can read binary or hexa- decimal numbers. Finally, suitablehardwareinterfac- ing would be required, including entry/exit sen- sors, time delays, and switch debounce logic. In cases like this, where the PLC software doesn’t quite do what you might require,thenoneapproach is to consider extending the PLC instruction set by As can be seen, the mark-to-space ratio is DEÚNED AS THE PROPOR- tion of time the wave- form is high, relative to the time the waveform is low. The duty cycle measures the time the waveform is high, rela- tive to the period (time) of the waveform. The ‘duty cycle’ ap- proach is used by the PLC software, with pulse width and period TIME VALUES SPECIÚED in multiples of 1/500th of a second (ie 2ms). PWM signals may be created, based either ON DIRECTLY SPECIÚED VALUES lIMMEDI- ate’ values), or based on the content of internal registers – with the latter method being more suited to dynamic MODIÚCATION DURING RUN TIME 5P TO four PWM outputs of each type may be created. The ‘pwmi’ command produces UP TO FOUR ÚXED VALUE IMMEDIATE PWM waveforms. The repeating pulse waveform is driven by an internal clock, which is linked to a 500Hz signal (taken internally from OSCH, 2). The three command arguments are the register number (0-3); the number of 2ms time periods the waveform should be high (1-255); followed by the total number of time periods in the waveform period (1-255). Output #5$
  • 179. WHERE THE ÚNAL DIGIT OF THE register name is determined by the counter number. (To use the car park spaces analogy again, the ctr_ud com- MANDmS ÚNAL VALUE PARAMETER WOULD be used to specify the capacity of the car park, the current count value would be equivalent to the number of cars currently inside the car park, WHILE THE APPROPRIATE #50 AND #$. status bits would indicate that the car park was either full or empty, respectively.) The example of Listing 4.5 shows an UPDOWN COUNTER CONÚGURED TO COUNT up to ten pulses on Port A bit 0, with INITIAL VALUE AND ÚNAL VALUE STATUS bits available from Port C, bits 1 and 0 respectively. The program counts pulses applied to bit 0 of Port A, displaying the cur- RENT COUNT VALUE ON ,%$S ASSUMED TO include 16F887.PLC ; Defines PLC instructions ld PORTA, 0 ; Read Port A bit 0 ; (clock input to up down counter) ctr_ud 0, 0x0A, PORTA, 1, PORTA, 2 ; Up down counter 0, ; Final value = 0x0A (10) ; Direction = Port A bit 1 (1 = Up, 0 = Down) ; Reset = Port A bit 2 (1 = Reset) ld CUP, 0 ; Load Up Down Counter 0 count-up status bit out PORTC, 1 ; Output final value reached status ld CDN, 0 ; Load Up Down Counter 0 count-down status bit out PORTC, 0 ; Output initial value reached status putr CUD0, PORTD ; Copy current count value to Port D endp ; Marks end of PLC program Listing 4.5. Using a bidirectional counter (Lst4_5.asm) BE CONNECTED TO 0ORT $ )NITIALLY
  • 180. OR following a reset applied to Port A bit 2, the internal count value will be zero, WHICHCAUSESTHE#$.
  • 181. STATUSBITTOBE set(asseenfromPortCbit0).Assuming THAT THE COUNTER IS CONÚGURED TO COUNT up, by applying a logic1 to Port A bit 1, then the counter will increment after EACH CLOCK PULSE UNTIL THE ÚNAL VALUE IS REACHED
  • 183. STATUS BIT IS set (linked to bit 1 of Port C). Bear in mind that the above car park scenario is used purely as an anal- ogy, and the program would certainly not be suitable in its current form to control a real car park for a number of reasons! To begin with, a display of the number of spaces available would be more useful than the number of adding custom macros of your own. For example, the addition of a custom decade counter macro with up, down, carry and borrow connections, and ca- pable of being cascaded, would make it easytodisplaythenumberofspacesasa decimalnumber.We’lllookatadvanced programming concepts, including cus- tomisation of the software, in the sixth AND ÚNAL PART OF THE SERIES Creating repeating pulses The PLC software makes it easy to create repeating pulse waveforms of VARIOUS CONÚGURATIONS 0ULSE WAVE- FORMS ARE COMMONLY DEÚNED IN TERMS of their frequency and either their mark-to-space ratio or duty cycle, as illustrated by Fig.4.2. Fig.4.2. Repeating pulse waveforms and their associated parameters
  • 184. Everyday Practical Electronics, February 2010 5 Teach-In 2010 capacity to modify the content of the registers used by the pwmr command at run-time, hence allowing real time control of the pulse width and period time respectively. As an example of this technique, Listing 4.8 shows the running count value of an up/down counter, being used to control the pulse width of a PWM waveform. Operation of the program is logically divided into three sections, with the ÚRST INITIALISING THE UPDOWN COUNTER
  • 185. THE SECOND CONÚGURING THE 07- SIG- nal, and the third actually making the waveform visible on an output port. Section 1: Applying an input to ei- ther bit 0 or bit 1 of Port A will enable the counter, but Port A bit 1 also serves to control the direction of the counter (1 = up/0 = down). Thus the former causes the counter to decrement, while waveforms are available by reading the appropriate bits of the PWMI reg- ister. (Thus, for example, the output waveform for the ‘pwmi, 2’ command may be read from bit 2 of the PWMI register.) Example of pwmi command As an example of the pwmi com- mand, the program Listing 4.6 creates FOUR ÚXED VALUE 07- WAVEFORMS
  • 186. with duty cycles of 20%, 40%, 60% and 80%, and with a base frequency of 50Hz. %XAMINING THE CREATION OF THE ÚRST waveform in detail, notice that the pwmi, 0 command is supplied with a pulse width of 2 × 2ms (2 × 1/500th of a second), while the period time is DEÚNED AS ¯ MS 4HUS
  • 187. THE PULSE is high for 4ms out of every 20ms, giving a 20% duty cycle and a base frequency of 50Hz. The waveform is made visible by copying the output bit from PWMI, 0 to bit 0 of Port D. Fig.4.3 shows the output produced by the program, running on a PICkit 2 Debug Express unit. !LTHOUGH IT IS EASY TO CREATE ÚXED duty cycle waveforms, the ability include 16F887.PLC ; Defines PLC instructions pwmi 0, d'02', d'10' ; 20 duty cycle on P MI, 0 pwmi 1, d'04', d'10' ; 40 duty cycle on P MI, 1 pwmi 2, d'06', d'10' ; 60 duty cycle on P MI, 2 pwmi 3, d'08', d'10' ; 80 duty cycle on P MI, 3 ld P MI, 0 ; Load P MI, 0 waveform (20 ) out PORTD, 0 ; Output to Port D bit 0 ld P MI, 1 ; Load P MI, 1 waveform (40 ) out PORTD, 1 ; Output to Port D bit 1 ld P MI, 2 ; Load P MI, 2 waveform (60 ) out PORTD, 2 ; Output to Port D bit 2 ld P MI, 3 ; Load P MI, 3 waveform (80 ) out PORTD, 3 ; Output to Port D bit 3 endp ; Marks end of PLC program ,ISTINGªª#REATINGªlXEDªDUTYªCYCLEªWAVEFORMSª ,ST?ASM to dynamically vary the duty cycle at run time can be more use- ful when developing applications – with potential scenarios including DC motor speed control, lamp dimmer circuits, or servo-based position control systems. include 16F627.PLC ; Defines PLC instructions puti d'02', AU 0 ; Put 2 into register AU 0 puti d'10', AU 1 ; Put 10 into register AU 1 pwmr 0, AU 0, AU 1 ; Create P M waveform based on AU 0 AU 1 ld P MR, 0 ; Load P MR, 0 output bit out PORTB, 0 ; Send P M signal to Port B bit 0 endp ; Marks end of PLC program ,ISTINGªª#REATINGªAªREGISTER BASEDª07-ªWAVEFORMª ,ST?ASM IGª#REATIONªOFªlXEDªDUTYªCYCLEªWAVEFORMSªUSING THEª0)#KITªª$EBUGª%XPRESSªUNIT The ‘pwmr’ com- mand produces up to four ‘variable’ or register-based PWM waveforms. The three arguments supplied to the pwmr com- mand are the regis- ter_number (0-3), the register containing the number of pulses the waveform should be high (0-255), fol- lowed by the regis- ter holding the total number of pulses in the waveform (1- 255). A simple example is given in Listing 4.7, WHICH ÚRST LOADS THE desired duty cycle parameter values into a pair of registers, and then uses the pwmr command to create a 20% duty cycle waveform. The real power of this method is the
  • 188. 5 Everyday Practical Electronics, February 2010 Teach-In 2010 Linking an up/down counter to an- other electronic sub-system (a PWM waveform generator in this case) is a powerful technique, and may be used as a building block in a wide variety of electronic systems. This concept will be explored further in Part 6, where a number of custom macros will be de- veloped, based on the general theme of ‘code conversion’, allowing direct con- nection of counters to devices includ- ing stepper motors, Gray-coded discs and seven-segment displays. Summary Part 4 of the series has continued the tour of sequential logic features of the PLCsoftware,introducingcountersand the generation of PWM waveforms. A wide vari- etyofsystemsmaynowbe developed, ranging from burglar alarms to motor speed controllers – and using only a few lines of code in each case. Next Month While the develop- ment of software using a ladder logic approach is clearly useful with microcontrollers, any practical system is likely to contain a combination ofhardwareandsoftware. Essentialconceptsrelated to hardware interfacing techniques will, there- fore, be considered in the nextandpenultimatepart,allowingthe PIC micro to be linked to a wide variety ofhardware,includingswitches,LEDs, transistors, relays, motors, solenoids and opto-couplers. Further byte-oriented capabilities of the software will be discussed, including the (surprisingly powerful) sequencer command. Byte-oriented logical and arithmetic capabilities will also be introduced, while other byte- ORIENTED CAPABILITIES WILL BE BRIEÛY recapped, including byte comparison and byte transfer commands. These concepts will enable us to ex- plorearangeofnewapplications,includ- ingLED-basedanimateddisplays,digital comparators and motor controllers. the latter makes it increment, with the rate of change controlled by ANDing the combined signal with OSCL, 1 (a 4Hz square wave signal). Section 2: The up/down counter is CONÚGURED TO COUNT UP TO A MAXIMUM value of 31, with the running count stored in register CUD 0. This value is thenusedbythepwmrcommandasthe pulse width value of a variable PWM WAVEFORM
  • 189. WITH A ÚXED PERIOD TIME pulses) obtained from register AUX1. Thus, the maximum duty cycle will be OR
  • 190. WITH A PERIOD TIME OF MS ¯ MS Section 3: The PWM status bit is read from bit 0 of register PWMR and copied to bit 0 of output Port B. include 16F627.PLC ; Defines PLC instructions ; First section configure up down counter ld PORTA, 0 ; Read Port A bit 0 (Slower input) or PORTA,1 ; OR with Port A bit 1 (Faster input) and OSCL,1 ; Clock input to up down counter ctr_ud 0, d'31', PORTA, 1, PORTA, 2 ; Up down counter 0, final value = 31 ; Direction = Port A bit 1 ; Reset = Port A bit 2 ; Up down counter working register = CUD0 ; Second section configure P M signal puti d'32', AU 1 ; Put 32 into register AU 1 (= period) pwmr 0, CUD0, AU 1 ; Create P M waveform based on CUD0 and AU 1 ; Third section display P M waveform ld P MR, 0 ; Load P M status bit out PORTB, 0 ; Output waveform to bit 0 of Port B endp ; Marks end of PLC program Listing 4.8. Varying pulse width by using a bidirectional counter (Lst4_8.asm) ELECTRONICS TEACH-IN 2 PIC N’ MIX A host of practical programming and interfacing information C FOR PICs A beginners guide to using the C programming language to programme PIC microcontrollers A hostA hoosthoshooostosststPLUSPLPLPL TheMicrochipnameandlogo,MPLAB,PIC anddsPIC are registered trademarks of Microchip Technology Incorporated in the USA and other co untries.© 2009MicrochipTechnologyInc.Allrightsreserved.Issue1.MCCD1016-02.0 9. Ele ctronics Teach-In 2 © Wimborne Publishing Ltd 2009 All the software for the projects/features in the Teach-In 2 series and PIC N’Mix in the Electronics Teach-In 2 book. Plus PIC Project Source Codes and PIC Tricks. MPLAB®IDE V8.20 (Integrated Develop men t Environmen t) MAPS V2.32 Latest Treelink Motor Control Solutions 16-bit Embedded Solutions 16-bit Tools Solutions Hum an Interface Solutions 8-bit PIC ®Microco ntrollers PIC24 Microco ntrollers PIC32 Microco ntrollers with USB dsPIC ®Digital Signal Controllers PIC NPIPICPIIC N’ MIN’N’N’ MIMIXMIXIXIX PLUPLPLLUPPLPLULUULUUSUSULUUSUSSSULUSUSUS USING PIC MICROCONTROLLERS A practical introduction Breadboard layouts to aid understanding Free software on CDROM Simple programmer project Free PIC Toolkit software Everything you need to get you started FROM THE PUBLISHERS OF £7.99 FREE CD-ROM dd 1 23/03/2009 11:39:27 £9.50 Including UK P P On sale in WHSmiths or available direct from us: 01202 873872 www.epemag.com ELECTRONICS TEACH-IN 2 PLUS CD-ROM
  • 191. 46 Everyday Practical Electronics, March 2010 Teach-In 2010 By Walter Ditch 0ARTª ª !DVANCEDª 0ROGRAMMINGª ANDª)NTERFACINGª4ECHNIQUESª T (% ÚFTH AND PENULTIMATE PART OF THIS SERIES BEGINS BY EXPLORING BASIC CONCEPTS RELATED TO HARD WARE INTERFACING
  • 192. INCLUDING METHODS OF CONNECTION TO INPUT DEVICES SUCH AS SWITCHES
  • 193. AND TO OUTPUTS INCLUDING ,%$S
  • 195. RELAYS
  • 196. SO LENOIDS AND MOTORS 4HIS KNOWLEDGE WILL GIVE YOU AN APPRECIATION OF THE HARDWARE DESIGN OF AN ACTUAL INDUSTRIAL 0,# q ALTHOUGH
  • 198. THE CIRCUITS CONSIDERED WILL BE RATHER MORE BASIC THAN THOSE OF A COMMERCIALLY AVAILABLE PRODUCT(ARDWAREDESIGNISALSOIMPOR TANT IN EMBEDDED CONTROL APPLICATIONS
  • 199. WHERE THE 0)# BECOMES AN INTEGRAL PART OF AN ELECTRONIC SYSTEM
  • 200. ADDING INTEL LIGENCE AND ÛEXIBILITY 7EmLL ALSO USE THE CHOSEN EXAMPLES TO DEMONSTRATE THE USE OF COMPUTER BASED ELECTRONIC SIMULATION SOFTWARE
  • 201. AS ILLUSTRATED BY 0ROTEUS 63- FROM ,ABCENTER %LECTRONICS ! NUMBER OF TIPS AND SUGGESTIONS WILL BE PROVIDED FOR THOSE USERS WISHING TO COMBINE 0,# STYLE PROGRAM DEVELOPMENT WITH USE OF ELECTRONIC SIMULATION SOFTWARE 4HE ARTICLE CONCLUDES BY DISCUSS ING A RANGE OF PROGRAMMING CONCEPTS
  • 202. WHICH HAVE BEEN GROUPED TOGETHER UNDER THE UMBRELLA TERM OF lAD VANCED PROGRAMMINGm 4OPICS COVERED INCLUDE • YTE ORIENTED PROGRAMMING DATA TRANSFER
  • 204. NUMERIC COMPARISON AND ARITHMETIC OPERATIONS •#REATION OF SIMPLE STATE BASED SYS TEMS BY USING THE BUILT IN SEQUENCER FEATURE #ONCEPTS COVERED HERE
  • 205. AND IN PREVIOUS PARTS OF THE SERIES
  • 207. WITH THE ÚNAL INSTALMENT FOCUSING ON THE DEVELOPMENT OF CUSTOM EXTENSIONS TO THE SOFTWARE ! NUMBER OF SOFTWARE SOLUTIONS WILL BE DEVELOPED
  • 208. MAK ING IT STRAIGHTFORWARD TO CONTROL THE HARDWARE DEVICES DISCUSSED HERE
  • 210. ALL PROGRAM LISTINGS FOR THIS SERIES ARE AVAILABLE FROM THE ,I BRARY 4UTORIALS SECTION OF THE 1 WEBSITE WWWEPEMAGCOM 9OUmLL ALSO NEED THE HEADER ÚLES SUPPLIED WITH 0ART
  • 211. WHICH SHOULD BE lUN ZIPPEDm INTO A SINGLE FOLDER
  • 212. TOGETHER WITH THE SAMPLE ÚLES FROM EACH PART OF THE SERIES -AKE SURE YOU HAVE INSTALLED THE FREELY AVAILABLE -0,! )$% SOFTWARE
  • 213. WHICH WILL BE NEEDED TO ASSEMBLE THE EXAMPLE PROGRAMS !ND OF COURSE
  • 214. IN ORDER TO ACTUALLY TEST THE PROGRAMS
  • 215. YOU WILL NEED A SUITABLE 0)# DEVELOPMENT BOARD
  • 216. ÚTTED WITH ONE OF THE SUPPORTED 0)# MICROCONTROLLER TYPES
  • 217. OR SIMULATION SOFTWARE SUCH AS 0ROTEUS 63- FROM ,ABCENTER %LECTRONICS (ARDWAREªDESIGNªCONCEPTS 0)# MICROCONTROLLERS ARE OFTEN USED IN lEMBEDDED SYSTEMSm
  • 218. WHERE THE 0)# BECOMES A ÛEXIBLE AND REPROGRAM MABLE ALTERNATIVE TO A HARD WIRED ELECTRONIC CIRCUIT !LTHOUGH SOPHISTI CATED INPUTOUTPUT CIRCUITRY IS ALREADY PROVIDED IN THE COMMERCIAL 0,#
  • 219. ANY INTERFACING HARDWARE MUST BE DESIGNED AND BUILT WHEREVER A 0)# MICROCON TROLLER IS DEPLOYED (ARDWARE DESIGN AND SOFTWARE DEVELOPMENT ARE BEST THOUGHT OF AS TWO SIDES OF THE SAME COIN
  • 220. AND MUST BE CONSIDERED TOGETHER WHEN ANY PRACTICAL SOLUTION IS BEING DEVELOPED !N APPRECIATION OF HARDWARE IN TERFACING TECHNIQUES CAN ALSO GREATLY ADD TO THE REAL WORLD RELEVANCE OF ANY LADDER LOGIC PROGRAMS DEVELOPED )T SURELY IS MORE INSPIRING
  • 222. TO CONTROL A $# MOTOR FROM A LADDER LOGIC OUTPUT
  • 223. RATHER THAN TO SIMPLY TURN AN ,%$ ON AND OFF q NOT LEAST DUE TO THE MANY PRACTICAL APPLICATIONS OF MOTORS (ARDWARE INTERFACING CONCEPTS CONSIDERED HERE WILL ALLOW THE 0)# MICRO TO BE LINKED TO A WIDE VARIETY OF HARDWARE
  • 225. ,%$S
  • 227. RELAYS
  • 228. MOTORS
  • 229. SOLENOIDS AND OPTOCOUPLERS 7($+,1 /$''(5 /2*, 352*5$00,1* )25 7+( 3, 0,52
  • 230. Everyday Practical Electronics, March 2010 47 Teach-In 2010 .OTE 4HE SUPPORTED 0)# MICRO CONTROLLERS ALL HAVE THE CAPABILITY TO ENABLE INTERNAL PULL UP RESISTORS CONNECTED TO 0ORT 4HIS OPTION IS DISABLED WITHIN THE 0,# SOFTWARE BY DEFAULT
  • 231. BUT MAY BE A CUSTOMISATION OPTION IN SITUATIONS WHERE 0ORT IS CONÚGURED AS AN INPUT PORT AS IN THE 0)# MODEL 7HILE THE CIRCUIT IG IS ÚNE WHEREINPUTSWITCHESAREDIRECTLYLINKED TO THE 0)#
  • 232. IT WOULD NOT BE ADEQUATE IN CASES WHERE THE USER WAS ALLOWED TO MAKE THEIR OWN CONNECTIONS VIA INPUT TERMINALS (IGHER VOLTAGES OR INCORRECT POLARITIESWOULDBEQUITELIKELYTOOCCUR
  • 233. LEADING TO THE LIKELIHOOD OF DAMAGE TO THE MICROCONTROLLER
  • 234. OR EVEN THE RISK OF ELECTRIC SHOCK TO THE USER ! MORE ROBUST INPUT CIRCUIT WOULD BE ADVISABLE IN THIS CASE
  • 235. INCORPORAT ING SOME KIND OF ELECTRICAL ISOLATION OF THE LOW VOLTAGE AND POTENTIALLY HIGH VOLTAGE SECTIONS /PTOCOUPLEROPTOISO LATOR CIRCUITS ARE IDEALLY SUITED TO THIS PURPOSE AND THESE WILL BE DISCUSSED SHORTLY
  • 236. FOLLOWING CONSIDERATION OF OUTPUT DEVICES )NTERFACINGªOUTPUTS !CCORDING TO THE 0)# DATA SHEET
  • 237. THE MAXIMUM CURRENT CAPACITY OF A SINGLE OUTPUT PORT IS M!
  • 238. BOTH AT LOGIC CURRENT BEING lSOURCEDm OR ÛOWING OUT OF THE PIN
  • 239. AND AT LOGIC CURRENT ÛOWING INTO THE PIN OR BEING lSUNKm (OWEVER
  • 240. THERE WILL ALSO BE AN OVER ALL MAXIMUM CURRENT LIMIT
  • 241. EITHER FOR THE OUTPUT PORT OR FOR ALL OUTPUT PORTS COMBINED q AND THIS IS QUITE DEVICE SPECIÚC 3OME EXAMPLES ARE LISTED BELOW • 0)#!!! q MAXI MUM CURRENT SUNKSOURCED BY 0/24! AND 0/24 COMBINED M! • 0)# q MAXIMUM CURRENT SUNKSOURCED BY 0/24! OR 0/24 SEPARATELY M! • 0)# q MAXIMUM CURRENT SUNKSOURCED BY ALL PORTS COMBINED M! $ESIGN CONSTRAINTS ALSO EXIST RE LATED TO THE MAXIMUM CURRENT SUNK OR SOURCED
  • 242. PLUS THE OVERALL POWER DISSIPATED BY THE ENTIRE DEVICE OR EXAMPLE
  • 243. THE 0)#!!! DATA SHEET GIVES THE FOLLOWING VALUES • -AXIMUM CURRENT OUT OF 633 PIN NEGATIVE POWER SUPPLY PIN M! • -AXIMUM CURRENT INTO 6$$ PIN POSITIVE POWER SUPPLY PIN M! 3TARTINGªWITHªTHEªDATAªSHEET 4HE DEÚNITIVE SOURCE OF INFORMA TION FOR THE HARDWARE DESIGNER IS THE APPROPRIATE 0)# DATA SHEET
  • 244. WHICH MAY BE DOWNLOADED FROM THE -ICROCHIP WEBSITE WWWMICROCHIPCOM IN 0$ 0ORTABLE $OCUMENT ORMAT FORMAT
  • 245. AND THEN VIEWED USING THE FREELY AVAIL ABLE !DOBE 2EADER SOFTWARE 0)# DEVICES REALLY DO VARY
  • 246. PAR TICULARLY IN THEIR CURRENT HANDLING CAPACITY
  • 247. SO MAKE SURE THAT YOU CARE FULLY READ THE DATA SHEET FOR THE ACTUAL MICROCONTROLLER BEING USED
  • 248. PRIOR TO DESIGNING ANY INTERFACING CIRCUITRY #ONNECTINGªINPUTªSWITCHES 0)# MICROCONTROLLERS ARE BASED IN TERNALLY ON #-/3 TECHNOLOGY
  • 249. SO ANY INPUT CIRCUITS WILL DRAW NEGLIGIBLE CUR RENT
  • 250. BEING EFFECTIVELY VOLTAGE CONTROL LED INPUT LEAKAGE CURRENTS OF P! OR LESS
  • 251. ARE DEÚNED IN THE DATA SHEET USING THE )), PARAMETER !CCEPTABLE VOLTAGE RANGES FOR HIGH AND LOW LOGIC LEVELS ARE SPECIÚED IN THE DATA SHEET USING THE 6)( AND 6), PARAMETERS RESPECTIVELY
  • 252. TYPICALLY USING A CALCULATION BASED ON THE POSITIVE SUPPLY VOLTAGE 6$$ 4HIS CAN SEEM COMPLEX
  • 253. BUT ASSUM ING A 6 POWER SUPPLY AND STANDARD INPUT CIRCUITRY
  • 254. A LOGIC WILL BE REC OGNISED AS A VOLTAGE IN THE RANGE 6 TO 6 ¯ 6$$
  • 255. WHILE A LOGIC WILL BE ANY VOLTAGE IN THE RANGE 6 TO 6 ¯ 6$$ 6 4HIS MAKES IT RELATIVELY STRAIGHTFOR WARD TO SUPPLY INPUT DATA BY USING SWITCHES
  • 256. USING NOTHING MORE COMPLEX THAN A SWITCH AND A RESISTOR FOR EACH PORT BIT 4HIS IS ILLUSTRATED BY IG )T IS ASSUMED HERE
  • 258. THAT A SIMPLE LADDER LOGIC PROGRAM IS RUNNING
  • 259. COPY ING INPUT PORT BITS FROM 0ORT ! TO THE EQUIVALENT OUTPUT PORT BITS OF 0ORT .OTICE THAT THE CIRCUIT SHOWS THREE DIFFERENT SWITCH INTERFACING METHODS
  • 260. AND SEVERAL OTHER CIRCUIT VARIATIONS ARE POSSIBLE 3WITCH 37 PROVIDES A DIRECT CONNECTION TO LOGIC WHEN CLOSED
  • 261. OR A WEAK PULL DOWN VIA RESISTOR 2 WHEN OPEN 3WITCH 37 AND 2 PROVIDE THE OPPOSITE POLARITY ! FURTHER ALTERNATIVE IS SHOWN BY SWITCH 37 AND 2
  • 262. WHERE A WEAK PULL UP OR PULL DOWN IS APPLIED 4HIS LATTER CIRCUIT MAY BE PREFERRED FOR A GENERAL EXPERIMENTATION ARRANGEMENT
  • 263. PARTICULARLY IF THERE IS ANY POSSIBIL ITY OF THE PORT BEING CONÚGURED AS AN OUTPUT
  • 264. SINCE IT AVOIDS THE POSSIBILITY OF AN EXCESSIVE OUTPUT CURRENT 7HY USE A K RESISTOR 7ELL THE PRE CISE VALUE IS NOT CRITICAL
  • 265. BUT OBSERVE THAT THE CURRENT ÛOWING THROUGH THE RESISTOR OF M! OR P! IS CONSID ERABLY LARGER THAN THE INPUT PORTmS LEAK AGE CURRENT OF AT MOST P!
  • 266. EFFECTIVELY OVERCOMING ANY INPUT PORT LOADING EFFECTS
  • 267. AND ENSURING THAT INPUT LOGIC LEVELS ARE CORRECTLY INTERPRETED 4HE USE OF AN APPROPRIATELY SIZED PULL UP PULL DOWN RESISTOR ALSO PREVENTS THE INPUT PORT FROM ACTING AS AN ANTENNA FOR STRAY ELECTROMAGNETIC INTERFERENCE
  • 268. THUS AVOIDING FALSE TRIGGERING OF INPUT CIRCUITS IGª-ETHODSªOFªCONNECTINGªINPUTªSWITCHES
  • 269. 4 Everyday Practical Electronics, March 2010 Teach-In 2010 • 4OTAL MAXIMUM POWER DISSIPA TION M7 AND THE METHOD OF CALCULATING THIS VALUE IS GIVEN IN THE DATA SHEET ! SECOND CONSIDERATION IS THE VOLTAGES INVOLVED
  • 271. ANDALSO THE ACTUAL WORST CASE VOLTAGES LIKELY TO APPEAR WHEN A LOGIC OR LOGIC IS BE ING OUTPUTTED STATED AS 6/( AND 6/, RESPECTIVELY IN THE 0)# DATA SHEET 4HE MINIMUM OUTPUT VOLTAGE FOR A LOGIC
  • 272. 6/(
  • 273. IS DEÚNED AS BEING 6$$ q 6
  • 274. WHICH FOR A 6 POWER SUPPLY
  • 275. WOULD BE IN THE RANGE 6 TO 6 3IMILARLY
  • 277. 6/,
  • 279. SO A LOGIC OUTPUT VOLTAGE WILL BE IN THE RANGE 6 TO 6 4HESE VOLTAGE LEVELS ARE STATED WITH OUTPUT CURRENTS CONSIDERABLY LESS THAN THE MAXIMUM OF M!
  • 280. SO SLIGHTLY WORSE ÚGURES MAY BE FOUND IN PRACTICE 4HIS GIVES US THE NECESSARY INFOR MATION TO DESIGN OUTPUT INTERFACE CIRCUITRY
  • 281. NOTING THAT THE 0)# MICROmS POWERFUL AND SYMMETRICAL OUTPUT DRIVE CIRCUITRY PROVIDES US WITH GREAT DESIGN ÛEXIBILITY )MAX M!
  • 282. BOTH AT LOGIC AND ALSO AT LOGIC $RIVINGª,%$S IRST
  • 283. LET US CONSIDER THE INTERFACING OPTIONS FOR DIRECTLY CONNECTED ,%$S
  • 284. AS SHOWN IN IG !S CAN BE SEEN
  • 285. THE SYMMETRICAL DRIVE CAPABILITY ALLOWS US TO CONNECT THE ,%$ EITHER WAY ROUND
  • 286. WITH $ BEING ILLUMINATED BY A LOGIC OUTPUT
  • 287. AND $ BY A LOGIC ! TYPICAL ,%$ FORWARD VOLTAGE OF 6 AND A MAXIMUM CURRENT OF M! IS ASSUMEDHERE
  • 289. WHILE THE MAXIMUM CURRENT CAPACITY WILL BE RELATED TO THE BRIGHTNESS OF THE ,%$ AND ITS POWER RATING OTH VOLTAGE AND CURRENT VALUES SHOULD BE OBTAINED FROM THE APPROPRIATE CATALOGUE OR DATA SHEET AND THEN USED TO CALCULATE THE VALUE OF THE CURRENT LIMITING RESISTOR 2 AND 2 4HE PREFERRED VALUE OF : SHOWN HEREWILLGIVEACURRENTOFAPPROXIMATELY M!
  • 290. ASSUMING THAT A VOLTAGE OF 6 APPEARSACROSSTHERESISTORTERMINALSqOR SLIGHTLY LESS IN THE EVENT OF WORST CASE OUTPUT VOLTAGES OF 6/( AND 6/, #ONTROLLINGªLARGERªCURRENTSª ANDªHIGHERªVOLTAGES 7HERE HIGHER VOLTAGES ANDOR HIGHER CURRENTS MUST BE CONTROLLED
  • 291. THEN A TRANSISTOR OUTPUT CIRCUIT IS A GOOD CHOICE 4RANSISTORS COME IN MANY FORMS
  • 292. INCLUDING BIPOLAR AND ÚELD EFFECT TYPES
  • 293. AND HIGH GAIN $ARLINGTON PAIR COMPOSITE DEVICES ARE ALSO AVAIL ABLE 4O KEEP THINGS SIMPLE
  • 294. A CIRCUIT BASED ON AN /1/ BIPOLAR TRANSISTOR WILL BE CONSIDERED HERE
  • 295. AS SHOWN IN IG 4HE /1/ BIPOLAR TRANSISTOR IS A THREE TERMINAL DEVICE
  • 296. WHICH IS USED HERE AS A CURRENT CONTROLLED SWITCH
  • 297. WITH A RELATIVELY SMALL CURRENT ÛOWING INTO THE BASE TERMINAL CONTROLLING A LARGER CURRENT ÛOWING INTO THE COL LECTOR TERMINAL # %SSENTIALLY
  • 298. EITHER CURRENT IS ALLOWED TO ÛOW INTO THE BASE TERMINAL AND THE TRANSISTOR TURNS ON AND HENCE THE LAMP LIGHTS
  • 299. OR NO CURRENT ÛOWS INTO THE BASE
  • 300. AND THE LAMP AND TRANSISTOR ARE BOTH OFF IGª,%$ªINTERFACINGªOPTIONS IGª#ONTROLLINGªAª6ªLAMPªBYªUSINGªAªTRANSISTORªSWITCHINGªCIRCUIT 4HETRANSISTORISENABLEDINTHECIRCUIT OF IG BY OUTPUTTING A LOGIC TO BIT OF 0ORT PIN
  • 301. WHICH IN TURN SUP PLIES A CURRENT OF APPROXIMATELY M! TO THE BASE TERMINAL OF THE TRANSISTOR
  • 302. VIA CURRENT LIMITING RESISTOR 2 4HIS SMALL CURRENT IS MULTIPLIED BY THE CURRENT GAIN OF THE TRANSISTOR REFERRED TO AS H% OR E IN DATA SHEETS AND EQUAL TO )#) TO BECOMEAMUCHLARGERCOLLECTORCURRENT 7HEN THE TRANSISTOR IS SWITCHED ON
  • 303. ALMOST ALL OF THE 6 SUPPLY APPEARS ACROSS THE LAMP TERMINALS
  • 304. WITH ONLY 6 TO 6 ACROSS THE COLLECTOR EMITTER % JUNCTION OF THE TRANSISTOR SO 6#% 6 TO 6
  • 305. AT WHICH POINT THE TRANSISTOR IS SAID TO BE lSATURATEDm 3TRANGE AS IT MAY SEEM
  • 306. THIS CIR CUIT IS BEST DESIGNED BY WORKING
  • 307. Everyday Practical Electronics, March 2010 4 Teach-In 2010 URTHERªTRANSISTORªSWITCHINGª APPLICATIONS 4HE PREVIOUS TRANSISTOR SWITCHING CIRCUIT IS CLEARLY USEFUL IN ITS OWN RIGHT
  • 308. ALLOWING LARGER CURRENT DEVICES TO BE CONTROLLED
  • 309. AND ALSO DEVICES WHICH HAVEHIGHEROPERATINGVOLTAGES%QUALLY IMPORTANTLY
  • 310. IT MAY BE EASILY ADAPTED TO CONTROL DEVICES SUCH AS SEGMENT DISPLAYS
  • 311. OR INDUCTIVE LOADS SUCH AS RELAYS
  • 312. SOLENOIDS OR EVEN MOTORS !S A ÚRST EXAMPLE
  • 313. IG SHOWS A PAIR OF TRANSISTORS USED TO ALTERNATELY ENABLE THE DIGITS OF A MULTIPLEXED SEGMENT COMMON CATHODE DISPLAY %ACH OF THE INDIVIDUAL SEGMENTS WITHIN THE SEGMENT DISPLAY IS A SEPARATE ,%$ WITH ITS POSITIVE ANODE ! CONNECTED VIA A CURRENT LIMITING RESISTOR TO AN OUTPUT PORT BIT 4HE NEGA TIVE CATHODES + ARE INTERNALLY LINKED AND BROUGHT OUT TO A TERMINAL AT THE LOWER END OF THE SEGMENT DISPLAY HENCE THIS IS REFERRED TO AS A lCOMMON CATHODEm SEGMENT DISPLAY )N A SINGLE DIGIT DISPLAY
  • 314. THE CATHODE CONNECTION MAY BE SIMPLY GROUNDED
  • 315. BUT IN A MULTIPLE DIGIT DISPLAY AS SHOWN IN IG
  • 316. EACH DISPLAY IS ENA BLED IN A RAPIDLY REPEATING SEQUENCE
  • 317. GIVING THE ILLUSION THAT ALL DIGITS ARE SIMULTANEOUSLY ILLUMINATED 4HIS lTIME DIVISION MULTIPLEXEDm ARRANGE MENT IS USED IN ORDER TO MINIMISE THE NUMBER OF OUTPUT PORTS BITS REQUIRED BY MULTIPLE DIGIT DISPLAYS #ALCULA TION OF THE VALUE OF THE CURRENT LIMITING RESISTORS IS SIMILAR TO THAT ALREADY SEEN FOR A SINGLE LIGHT EMITTING DIODE
  • 318. BUT THE BRIGHTNESS IS NORMALLY INCREASED
  • 319. SINCE EACH DIGIT IS ONLY ILLUMINATED FOR A FRACTION OF THE TIME 7E WILL REVISIT THIS APPLICATION NEXT MONTH
  • 320. WHEN CUSTOM MACROS WILL BE DEVELOPEDTODRIVESINGLE ANDMULTIPLE DIGIT SEGMENT DISPLAYS )NDUCTIVEªLOADS ! TRANSISTOR MAY ALSO BE USED TO EN ERGISE THE COIL OF A RELAY
  • 321. AS ILLUSTRATED BY IG )N THIS EXAMPLE
  • 322. THE RELAY IS SHOWN ENERGISING A 6 LAMP
  • 323. BUT A MORE ÛEXIBLE ARRANGEMENT WOULD BE TO BRING OUT THE RELAY CONTACTS TO EXTER NAL SCREW TERMINALS
  • 324. ALLOWING USERS TO MAKE THEIR OWN CONNECTIONS
  • 325. AS APPROPRIATE 4HE ADDITION OF A NOR MALLY REVERSE BIASED DIODE ACROSS THE RELAY COIL ENABLES THE ENERGY STORED IN THE MAGNETIC ÚELD OF THE COIL TO HARMLESSLY DISSIPATE WHEN IT IS DE ENERGISED
  • 326. lQUENCHINGm THE MO MENTARY HIGH VOLTAGE SPIKE WHICH WOULD OTHERWISE OCCUR 4HE SAME BASIC CIRCUIT MAY BE USED TO ENERGISE OTHER TYPES OF INDUCTIVE LOAD
  • 327. SUCH AS A $# MOTORS
  • 329. OR EVEN SOLENOIDS q WITH ELECTRONIC DOOR LOCKS AND PNEUMATIC BACK FROM THE OUTPUT TO THE INPUT
  • 330. BEGINNING WITH THE LAMP 4O TAKE AN EXAMPLE
  • 331. ASSUMING THE LAMP IS RATED AT 6 AND HAS A RESISTANCE OF : ! SIMPLE CALCULATION SHOWS THAT THE LAMP CURRENT WILL BE !
  • 332. SO OUR ÚRST DESIGN CONCLUSION IS THAT WE WILL NEED A TRANSISTOR WITH A 6#% MAN RATING GREATER THAN 6 AND )# IN EXCESS OF !
  • 333. WHICH IS QUITE STRAIGHTFORWARD .EXT
  • 334. THE MINIMUM H% IS IDENTIÚED FROM THE TRANSISTOR DATA SHEET AND THIS IS USED TO CALCULATE THE REQUIRED BASE CURRENT ) MAX )#H% MIN 3O FOR EXAMPLE
  • 335. IF H% MIN AND )# M!
  • 336. THEN THE REQUIRED BASE CURRENT WILL BE M! 2ECALL THAT WE NEED TO KEEP THIS BASE CURRENT UNDER M! IN ORDER TO COMPLY WITH THE 0)#mS MAXI MUM CURRENT RATING
  • 337. SO A VALUE OF M! ÛOWING OUT OF 0ORT BIT WILL BE ÚNE 4HE BASE EMITTER JUNCTION OF A CONDUCTING TRANSISTOR IS EFFECTIVELY A SILICON DIODE
  • 338. SO A VOLTAGE OF APPROXI MATELY 6 APPEARS ACROSS THE BASE EMITTER TERMINALS WHEN THE TRANSISTOR IS SWITCHED ON 'IVEN THAT THE REQUIRED BASE CURRENT IS M!
  • 339. A SIMPLE CALCULA TION PROVIDES US WITH THE VALUE OF THE CURRENT LIMITING BASE RESISTOR 2 62) 6/( q 6% ) ≈ : THE NEAREST PREFERRED VALUE IN THE % RESISTOR SERIES IGª!ªSIMPLEªMULTIPLEXEDª,%$ªDISPLAY
  • 340. Everyday Practical Electronics, March 2010 Teach-In 2010 VALVES BEING JUST TWO APPLICATIONS OF SOLENOIDS !LTHOUGH NOT CONSIDERED HERE
  • 341. IT IS ALSO POSSIBLE TO USE TRANSISTOR CIRCUITS TO PROVIDE BIDIRECTIONAL CONTROL OF MOTORS
  • 342. OR TO ENERGISE THE COILS OF A BIPOLAR STEPPER MOTOR WITH POSITIVE OR NEGATIVE POLARITY 3UCH A CIRCUIT WOULD USE TWO OUTPUT PORT BITS PER CONTROLLED DEVICE
  • 343. LINKED TO A l( BRIDGEm TRANSISTOR CIRCUIT
  • 344. WITH A SMALL $# MOTOR REQUIR ING ONE BRIDGE TWO PORT BITS PER MOTOR AND A TWO COIL STEPPER MOTOR BEING LINKED TO FOUR OUTPUT PORT BITS #USTOM SOFTWARE ROUTINES TO CONTROL STEPPER MOTORS WILL BE DEVELOPED NEXT MONTH
  • 345. IN ADDITION TO THE SEGMENT DISPLAYS ALREADY DISCUSSED )SOLATINGªHIGHªANDªLOWª VOLTAGES 4HE RELAY OUTPUT CIRCUIT CONSID ERED PREVIOUSLY HAS THE ADVANTAGE OF PROVIDING A DEGREE OF ELECTRICAL ISOLA TION BETWEEN THE LOW VOLTAGE CONTROL CIRCUIT
  • 346. AND THE POTENTIALLY HIGHER VOLTAGES CONNECTED TO THE SWITCH CONTACTS OF THE RELAY 4HIS SAME SAFETY PRINCIPLE MAY ALSO BE APPLIED TO IN PUT CIRCUITRY
  • 347. BUT THIS TIME BASED ON OPTOCOUPLER TECHNOLOGY
  • 348. AS ILLUSTRATED BY IG )N THIS EXAMPLE
  • 349. A 6 $# IN PUT IS CONNECTED VIA A SWITCH AND CURRENT LIMITING RESISTOR 37 AND 2 RESPECTIVELY TO THE ,%$ INSIDE THE OPTOCOUPLER #LOSING THE SWITCH CAUSES THE OPTOCOUPLER ,%$ TO LIGHT
  • 350. THUS ENABLING THE PHOTO TRANSISTOR CONNECTED TO THE OUTPUT 4HE TRANSISTOR WITHIN THE OPTO COUPLER IS WIRED AS AN EMITTER FOLLOWER
  • 351. WHICH CAUSES THE EMITTER TO BE PULLED UP TO ALMOST 6 EACH TIME THE INTERNAL ,%$ IS ILLUMINATED 4HIS ALSO ILLUMINATES THE EXTERNAL INDICATOR ,%$ VIA CURRENT LIMITING RESISTOR 2
  • 352. AT THE SAME TIME SUPPLYING A LOGIC INPUT TO THE 0)# MICROCONTROLLER AT PIN 2! 4HIS TYPE OF INPUT CIRCUITRY HAS TWO ADVANTAGES IRST
  • 353. IT ALLOWS CONNECTION OF HIGHER INPUT VOLTAGES
  • 354. AND SECOND IT PROVIDES ELECTRICAL ISOLATION OF POTEN TIALLY DANGEROUS INPUT VOLTAGES FROM THE RELATIVELY EXPENSIVE PROCESSOR CIRCUITRY EAR IN MIND THAT THE INPUT PROTEC TION CIRCUITRY OF AN ACTUAL 0,# IS LIKELY TO BE MORE COMPLEX THAN THAT SHOWN HERE
  • 355. OFFERING OVER VOLTAGE AND REVERSE POLARITY PROTECTION 0ROTEUSª63-ªSIMULATIONªTIPS /BSERVANT READERS MAY HAVE NOTICED THAT THE CIRCUITS OF IGS TO ARE BASED ON SCREENSHOTS PRODUCED BY 0ROTEUS 63- SOFTWARE FROM ,ABCENTER %LECTRONICS 4HE ANNOTATIONS FOR THE TRANSISTORS
  • 356. DIODES AND RELAY COIL HAVE BEEN ADDED 4HIS NEATLY DEMONSTRATES THE FEASIBILITY OF MIXED HARDWARE AND SOFTWARE SIMULATION )F YOU HAVE ACCESS TO THIS POWERFUL SOFTWARE APPLICATION
  • 357. THEN THE FOLLOW ING SIMULATION AND DEBUGGING TIPS MAY PROVE USEFUL OR SIMPLE APPLICATION AND VIEW ING OF LOGIC LEVELS
  • 358. THE lLOGICSTATEm AND lLOGICPROBEm COMPONENTS ALLOW LOGIC LOGIC INPUTS TO BE APPLIED AND DISPLAYED RESPECTIVELY ! MOMENTARY ACTION lLOGICTOGGLEm INPUT DEVICE IS ALSO AVAILABLE
  • 359. AND LOGIC PROBES ARE FOUND IN TWO DIFFERENT SIZES 4HE DEFAULT OSCILLATOR FREQUENCY OF -(Z SHOULD BE CHANGED TO -(Z ON EACH INSERTED MICROCONTROLLER
  • 360. THUS ENSURING THAT TIME CRITICAL PROGRAMS OPERATE AT THE DESIRED SPEED 0ROTEUS 63- PROVIDES A VA RIETY OF lANIMATEDm COMPONENTS
  • 361. WHICH MAY BE USED TO GIVE A VISUAL INDICATION OF CIRCUIT OPERATION DUR ING SIMULATION !NIMATED DEVICES INCLUDE SWITCHES
  • 362. ,%$S
  • 364. LAMPS
  • 365. RELAYS
  • 366. $# MOTORS AND STEPPER MOTORS 4HE lVIRTUAL INSTRUMENTSm FEATURE EMULATES COMMON MEASURING INSTRU MENTS SUCH AS THE AMMETER
  • 368. SIGNAL GENERATOR AND OSCILLOSCOPE IGª#ONTROLLINGªAªRELAYªUSINGªAªTRANSISTORªSWITCHINGªCIRCUIT IGª0ROVIDINGªINPUTªISOLATIONªBYªUSINGªANªOPTOCOUPLER
  • 369. Everyday Practical Electronics, March 2010 Teach-In 2010 !T THIS STAGE
  • 370. YOU SHOULD NOW HAVE A GOOD APPRECIATION OF THE HARDWARE FOUND IN A TYPICAL 0,#
  • 371. AND YOU SHOULD BE ABLE TO DESIGN SIMPLE LOW VOLT AGE 0)# INTERFACE CIRCUITRY FOR USE IN EMBEDDED CONTROL APPLICATIONS 4HE NEXT SECTION LOOKS AT THE BYTE PROCESS ING CAPABILITIES OF THE 0,# SOFTWARE
  • 372. WHICH WILL BE USED TO BUILD A DIGITAL COMPARATOR
  • 373. AND ALSO AN ADDERSUB TRACTER CIRCUIT 7ORKINGªWITHªBITSªANDªBYTES ,ADDER LOGIC EXCELS AT THE MANIPULA TION OF INDIVIDUAL BITS q FOR EXAMPLE READING INPUTS
  • 375. AND OUTPUTTING THE RESULTS #ERTAIN OTHER COMMANDS ALREADY CONSIDERED MAY BE REGARDED AS EITHER BIT ORIENTED OR BYTE ORIENTED
  • 376. DEPENDING ON THE APPLICATION 4HIS INCLUDES COUNTERS
  • 378. ALL OF WHICH MAKE USE OF A BYTE SIZED lWORKING REGISTERm
  • 379. WHICH MAY BE OPTIONALLY USED BY THE PROGRAMMER 2ECALL THAT COMMANDS HAVE ALSO BEEN INTRODUCED WHICH CAN LOAD A BYTE SIZED VALUE INTO A REGISTER
  • 380. OR COPY A BYTE FROM ONE REGISTER TO AN OTHER THE lPUTIm AND lPUTRm COMMANDS RESPECTIVELY
  • 381. ÚRST INTRODUCED IN 0ART 5SE OF BYTE ORIENTED COMMANDS CAN GREATLY SIMPLIFY THE WRITING OF CERTAIN PROGRAMS
  • 382. AND A FURTHER ADVANTAGE IS THEIR EFÚCIENT CODING AND HIGH SPEED OF EXECUTION4HEONLYPOTENTIALDOWNSIDE
  • 383. FOR THOSE NEW TO MICROELECTRONICS AT LEAST
  • 385. COM PARED WITH INDIVIDUAL BITS 4HIS MAY INCLUDE THE NEED TO WORK WITH A VARIETY OF NUMBERING SYSTEMS
  • 387. OCTAL
  • 389. INADDI TION TO THE REPRESENTATION OF SIGNED AND UNSIGNED NUMERIC VALUES mS COMPLE MENT ARITHMETIC FOR EXAMPLE 4HE 0,# SOFTWAREmS DEDICATED BYTE PROCESSING CAPABILITIES FALL INTO THE FOLLOWING CATEGORIES •YTE DATA TRANSFER q USING THE lPUTIm AND lPUTRm COMMANDS
  • 390. AS DISCUSSED ABOVE 0LEASE REFER BACK TO 0ART
  • 391. 4ABLE
  • 393. AND ASSOCIATED TEXT FOR MORE DETAILS •YTE LOGICAL COMMANDS q PERFORM ING COMBINATIONAL LOGIC OPERATIONS ON EACH BIT OF A REGISTER SIMULTANEOUSLY •YTE COMPARISON q COMPARING BYTE VALUES USING OPERATORS SUCH AS lLESS THANm
  • 397. AND THEIR COMBINATIONS •YTE ARITHMETIC q ADDING AND SUB TRACTING BYTE VALUES WITH SUBTRACTION USING mS COMPLEMENT ARITHMETIC YTEªLOGICALªCOMMANDS YTE LOGICAL COMMANDS PERFORM COMBINATIONAL LOGIC OPERATIONS SUCH AS !.$
  • 398. /2
  • 399. AND 8/2 ON EACH BIT OF A SOURCE REGISTER
  • 400. COMBINING THE SOURCE WITH A lMASKm TO PRODUCE A RESULT BYTE #AREFUL CHOICE OF LOGICAL OPERATION AND MASK BYTE ALLOWS A VARIETY OF OPERATIONS TO BE PERFORMED
  • 403. INVERTING OR COPYING SELECTED BITS %ACH COMMAND OFFERS A MATCHED PAIR OF OPERATIONS
  • 404. WHICH IS SELECTED BY THE VALUE OF THE MASK BIT • !.$ WITH TO COPY THE SOURCE BIT UNALTERED !.$ WITH TO CLEAR THE OUTPUT BIT TO ZERO • /2 WITH TO SET THE OUTPUT BIT TO /2 WITH TO COPY THE SOURCE BIT UNALTERED • 8/2 WITH TO INVERT THE SOURCE BIT 8/2 WITH TO COPY THE SOURCE BIT UNALTERED 4HESE POSSIBILITIES ARE ILLUSTRATED GRAPHICALLY BY THE EXAMPLE OF IG
  • 405. IN WHICH A BINARY SOURCE BYTE l m AT THE CENTRE OF THE ÚGURE IS COMBINED WITH A MASK BYTE OF l m TO PRODUCE THREE DIFFERENT RESULT BYTES BY USING !.$
  • 406. /2 AND 8/2 OP ERATIONS AT THE LEFT
  • 407. RIGHT AND BOTTOM RESPECTIVELY 4HE 0,# SOFTWARE OFFERS TWO DIF FERENT VERSIONS OF EACH COMMAND
  • 408. AS SHOWN IN 4ABLE !S USUAL
  • 409. COMMAND NAMES ARE SUPPLIED IN LOWER CASE AND REGISTER NAMES ARE UPPER CASE .OTICE THAT COM MAND NAMES ENDING WITH lRm REGISTER 2EFER BACK TO 0ART IG TO SEE THE lDIGITAL OSCILLOSCOPEm IN ACTION 9OU ALSO HAVE THE ABILITY TO PAUSE THE SIMULATION AND CLICK ON COMPO NENTS IN ORDER TO VIEW INSTANTANEOUS PARAMETERS
  • 411. CUR RENT AND POWER DISSIPATION q WHICH CAN OFTEN BE SIMPLER THAN PLACEMENT OF NUMEROUS MEASURING INSTRUMENTS $EDICATED MICROELECTRONICS INSTRU MENTS ARE ALSO AVAILABLE
  • 412. INCLUDING A MULTIPLE CHANNEL PATTERN GENERATOR AND A LOGIC ANALYSER 0ROTEUS PROVIDES A BUILT IN SOURCE CODE EDITOR
  • 413. PLUS A NUMBER OF BUILT IN ASSEMBLERS
  • 415. WHICH HAS BEEN USED THROUGHOUT THIS SERIES .OTE THAT THE -0!3- ASSEMBLER ALSO SUPPLIED WITH 0ROTEUS DOES NOT RECOGNISE 0)# SOURCE CODE ÚLES AT THE TIME OF WRIT ING
  • 416. ALTHOUGH THE -0!3-7). VERSION SEEMS TO HAVE NO SUCH PROBLEM ! VARIETY OF SOFTWARE DEBUGGING FEATURES ARE PROVIDED THROUGH A POW ERFUL INTEGRATED DEVELOPMENT ENVIRON MENT )$% 4HE lWATCH WINDOWm IS PARTICULARLYUSEFULFORDEBUGGINGLADDER LOGIC PROGRAMS
  • 417. ALLOWING THE CONTENT OF SELECTED INTERNAL REGISTERS TO BE VIEWED DURING RUN TIME 2EFER BACK TO 0ART
  • 421. PLUS REGISTER AND MEMORY VIEW WINDOWS )N GENERAL
  • 422. ) HAVE FOUND SIMULATION OF ANIMATED ELECTRONIC DEVICES TO BE TROUBLE FREE
  • 423. WITH A COUPLE OF MINOR EXCEPTIONS IRST
  • 424. THE CONNECTION OF ANIMATED $# MOTORS AND STEPPER MOTORS CAN GIVE lTIMESTEP TOO SMALLm ERRORS IN MIXED SIMULATIONS )F YOU ENCOUNTER THIS ERROR
  • 425. THEN ONE WORKA ROUND MIGHT BE TO REPLACE THE MOTOR WITH AN ANIMATED LAMP OF THE SAME RATING
  • 426. IN ORDER TO DEMONSTRATE CIRCUIT OPERATION 3ECOND
  • 427. YOU MAY OBSERVE TRANSIENT OSCILLATION OF OUTPUTS SUCH AS RELAY CONTACTS IN MORE COMPLEX SIMULATIONS 4HIS SEEMS TO RELATE TO THE METHOD USED BY THE 0)# MICROCONTROLLER TO UPDATE AN OUTPUT PORT
  • 428. IN WHICH THE OUTPUT PORT IS ÚRST READ IE IN PUTTED
  • 429. THEN UPDATED AND ÚNALLY RE OUTPUTTED 9OU CAN AVOID THIS UNWANTED FEEDBACK EFFECT BY TEM PORARILY PLACING lBUFFERm COMPO NENTS BETWEEN APPROPRIATE OUTPUT PORTS AND ANY EXTERNAL CIRCUITRY 6QWD[ DQG $GGUHVVLQJ 0RGH/RJLFDO 2SHUDWLRQ 5HJLVWHU ,PPHGLDWH
  • 430. ! 5HJLVWHU 5HJLVWHU 5HJLVWHU
  • 431. ! 5HJLVWHU $1' DQGL 65B5(* %7( '67B5(* DQGU 65B5(* 65B5(* '67B5(* 25 RUL 65B5(* %7( '67B5(* RUU 65B5(* 65B5(* '67B5(* ;25 [RUL 65B5(* %7( '67B5(* [RUU 65B5(* 65B5(* '67B5(* 4ABLEªªYTE ORIENTEDªLOGICªCOMMANDS
  • 432. Everyday Practical Electronics, March 2010 Teach-In 2010 COMBINE A PAIR OF REGISTERS
  • 433. WHILE AN lIm IMMEDIATE COMBINES AN IMMEDIATE VALUE WITH A REGISTER )N EACH CASE
  • 434. THE RESULT IS WRITTEN TO A SPECIÚED DESTINA TION REGISTER ! PRACTICAL APPLICATION WILL BE GIVEN IN THE NEXT SECTION WHEN BIT MASKING AND BYTE COMPARISON COM MANDS ARE COMBINED TO MAKE A DIGITAL COMPARATOR YTEªCOMPARISONªCOM MANDS !S THEIR TITLE SUGGESTS
  • 435. BYTE COMPARISON COMMANDS PER FORM NUMERICAL COMPARISONS BETWEEN TWO VALUES
  • 436. PRODUC ING A LOGIC VALUE IF THE COM PARISONISTRUE)NFACT
  • 438. MAKING USE OF THE lEQIm EQUAL IMMEDIATE COMMAND TO TEST AN IMMEDIATE VALUE AND A REGISTER
  • 439. AS PART OF THE LIGHT CHASER PROGRAM OF ,ISTING 4HE FULL RANGE OF BYTE COM PARISON COMMANDS AND OPTIONS ARE GIVEN IN 4ABLE !S AN EXAMPLE
  • 440. WE WILL DE SIGN A DIGITAL COMPARATOR WHICH WILL COMPARE TWO BIT NUM BERS
  • 441. REFERRED TO AS l!m AND lm
  • 443. l! m
  • 444. l! m AND l! m ! POSSIBLE PROGRAM IS GIVEN IN ,ISTING
  • 445. WRIT TEN FOR THE 0)# MICROCONTROLLER 4HE PROGRAM IS RELA TIVELY STRAIGHTFORWARD
  • 446. BEGINNINGBYMASKINGOFF THE UPPER BITS OF 0ORTS ! AND
  • 447. STORING THE RESULTS IN AUXILIARY REG ISTERS !58 AND !58 4HESE INTERMEDIATE VAL UES ARE THEN COMPARED
  • 448. WITH THE THREE POSSIBLE COMPARATOR RESULTS BEING WRITTEN IN ORDER TO BITS q OF 0ORT $ YTEªARITHMETICªINSTRUCTIONS 4HE 0,# SOFTWARE PROVIDES THE ABIL ITY TO PERFORM ADDITION AND SUBTRACTION OFBYTEVALUES
  • 449. WITHAVAILABLECOMMAND OPTIONS SHOWN IN 4ABLE 4HIS IS LIKELY TO BE ONE OF THE LESSER USED FEATURES
  • 450. AND ALSO ONE OF THE MORE CONCEPTUALLY DIFÚCULT
  • 451. DUE TO ITS USE OF mS COMPLEMENT ARITHMETIC (OWEVER
  • 452. POTENTIAL APPLICATIONS MIGHT INCLUDE CONTROL ORIENTED SYSTEMS IN WHICH A MEASURED PARAMETER SUCH AS TEMPERA TURE
  • 454. OR SPEED OF ROTATION IS COMPARED WITH A SET POINT
  • 455. WITH A SUBTRACTION COMMAND PRODUCING A DEVIATION VALUE 4HIS FEATURE MIGHT
  • 457. FORM PART OF A 0)$ PROPOR TIONAL
  • 459. DERIVATIVE CONTROLLER 4HE EXAMPLE OF ,ISTING PERFORMS ADDITION AND SUBTRACTION OF TWO BIT NUMBERS
  • 460. OUTPUTTING THE RESULTS TO TWO BIT REGISTERS 5NFORTUNATELY
  • 461. A FULL DISCUSSION OF mS COMPLEMENT ARITHMETIC IS BEYOND THE SCOPE OF THIS SERIES
  • 462. BUT NOTE THAT THE PROGRAM OF ,ISTING WILL DISPLAY ANY NEGATIVE SUBTRACTION RESULTS IN mS COMPLEMENT FORM ON 0ORT $ 4HE FOLLOWING INFORMATION MAY BE USEFUL WHEN INTERPRETING DISPLAYED RESULTS •)N AN BIT REPRESENTATION
  • 463. POSITIVE mS COMPLEMENT NUMBERS ARE ALLOWED IGªITªMASKINGªWITHªBYTEªLOGICALªCOMMANDS 6QWD[ DQG $GGUHVVLQJ 0RGHRPSDUH 2SHUDWLRQ 5HJLVWHU ,PPHGLDWH
  • 464. ! 5HJLVWHU 5HJLVWHU 5HJLVWHU
  • 465. ! 5HJLVWHU /HVV WKDQ OWL 65B5(* %7( '67B5(* OWU 65B5(* 65B5(* '67B5(* /HVV WKDQ RU HTXDO OWHL 65B5(* %7( '67B5(* OWHU 65B5(* 65B5(* '67B5(* (TXDO HTL 65B5(* %7( '67B5(* HTU 65B5(* 65B5(* '67B5(* 1RW HTXDO QHL 65B5(* %7( '67B5(* QHU 65B5(* 65B5(* '67B5(* *UHDWHU WKDQ JWL 65B5(* %7( '67B5(* JWU 65B5(* 65B5(* '67B5(* *UHDWHU WKDQ RU HTXDO JWHL 65B5(* %7( '67B5(* JWHU 65B5(* 65B5(* '67B5(* LQFOXGH )3/ 'HILQHV 3/ LQVWUXFWLRQV DQGL 3257$ E $8; 0DVN XSSHU ELWV RI 3RUW $ SODFLQJ UHVXOW LQ $8; QXPEHU $
  • 466. DQGL 3257% E $8; 0DVN XSSHU ELWV RI 3RUW % SODFLQJ UHVXOW LQ $8; QXPEHU %
  • 467. HTU $8; $8; 7HVW LI $ % RXW 3257' RXWSXWWLQJ UHVXOW WR ELW RI 3RUW ' JWU $8; $8; 7HVW LI $ ! % RXW 3257' RXWSXWWLQJ UHVXOW WR ELW RI 3RUW ' OWU $8; $8; 7HVW LI $ % RXW 3257' RXWSXWWLQJ UHVXOW WR ELW RI 3RUW ' HQGS 0DUNV HQG RI 3/ SURJUDP ,ISTINGªª!ª BITªCOMPARATORªPROGRAMª ,ST?ASM 4ABLEªªYTEªCOMPARISONªCOMMANDS 4ABLEªªYTEªARITHMETICªCOMMANDS TO BE IN THE DECIMAL RANGE TO
  • 468. AND NEGATIVE DECIMAL NUMBERS ARE BETWEEN AND 4HE MOST SIGNIÚCANT BIT OF THE SUBTRACTED RESULT INDICATES THE SIGN
  • 469. WITH ZERO INDICATING A POSITIVE RESULT AND ONE SHOWING A NEGATIVE mS COMPLEMENT VALUE •0OSITIVE BINARY NUMBERS ARE CONVERTED TO mS COMPLEMENT lNEGATIVEm FORM BY ÚRST INVERTING EACH BIT
  • 470. AND THEN ADDING TO THE 6QWD[ DQG $GGUHVVLQJ 0RGH$ULWKPHWLF 2SHUDWLRQ 5HJLVWHU ,PPHGLDWH
  • 471. ! 5HJLVWHU 5HJLVWHU 5HJLVWHU
  • 472. ! 5HJLVWHU $GG DGGL 65B5(* %7( '67B5(* DGGU 65B5(* 65B5(* '67B5(* 6XEWUDFW VXEL 65B5(* %7( '67B5(* VXEU 65B5(* 65B5(* '67B5(*
  • 473. Everyday Practical Electronics, March 2010 Teach-In 2010 RESULT 4HE INVERSE PROCESS OF SUBTRACTING AND THEN INVERTING EACH BIT CONVERTS A NEGATIVE NUMBER BACK TO POSITIVE FORM 4HE NEXT AND ÚNAL SEC TION INTRODUCES THE SE QUENCER FEATURE
  • 474. WHICH EXTENDS THE CONCEPT OF BYTE PROCESSING TO INCORPORATE SIMPLE STATE BASED SYSTEMS 3EQUENCER BASEDª SYSTEMS 4HE BUILT IN SEQUENCER FACILITY MAKES IT EASY TO CREATE COMPLEX ANIMATED SEQUENCES
  • 475. WITHUSER DEÚNED DATA IN %%02/- MEMORY BEINGSENTATREGULARINTERVALS TOTHECHOSENDESTINATIONREG ISTER3INGLE SHOTORREPEATING SEQUENCES MAY BE PRODUCED WITHUPTOSTEPS
  • 476. DEPEND ING ON THE CAPACITY OF THE %%02/- MEMORY WITHIN THE CHOSEN MICROCONTROLLER 4YPICAL APPLICATIONS OF THE SEQUENCER INCLUDE TOYS
  • 480. AND MANY MORE BESIDES .OTE THAT THE ! AND ! MICROCON TROLLERS HAVE BYTES OF BUILT IN %%02/-
  • 482. AND OFFER BYTES 0LEASE REFER BACK TO 0ART
  • 483. 4ABLE FOR A DETAILED LIST OF MICROCON TROLLER FEATURES 7RITING SEQUENCER BASED PROGRAMS IS A LITTLE DIFFERENT TO THAT SEEN SO FAR
  • 484. SINCE THE USERmSPROGRAMISEFFECTIVELY MERGEDWITHSEQUENCERDATA CONTAINED WITHIN THE 0,# HEADER ÚLEDURINGASSEMBLY 4HE ÚRST STEP IS NORMALLY TO CREATE A SEPARATE FOLDER TO HOLD BOTH THE CUSTOM HEADER ÚLE AND THE SOURCE CODE ÚLE FOR THE SEQUENCER PROJECT.EXT
  • 485. THEHEADERÚLE IS EDITED SO THAT IT CONTAINS THEREQUIREDSEQUENCERDATA INALLY
  • 486. A SUITABLE LADDER LOGIC PROGRAM IS WRITTEN AND ASSEMBLED IN THE NOR MAL WAY OR THE SAKE OF SIMPLIC ITY
  • 487. SAMPLE SEQUENCER DATA LQFOXGH )3/ 'HILQHV 3/ LQVWUXFWLRQV DQGL 3257$ E $8; 0DVN XSSHU ELWV RI 3RUW $ SODFLQJ UHVXOW LQ $8; QXPEHU $
  • 488. DQGL 3257% E $8; 0DVN XSSHU ELWV RI 3RUW % SODFLQJ UHVXOW LQ $8; QXPEHU %
  • 489. DGGU $8; $8; 3257 6HQG UHVXOW $ % WR 3RUW VXEU $8; $8; 3257' 6HQG UHVXOW $ % WR 3RUW ' HQGS 0DUNV HQG RI 3/ SURJUDP ,ISTINGªª!DDITIONªANDªSUBTRACTIONªOFªTWOª BITªNUMBERSª ,ST?ASM LQFOXGH )3/ 'HILQHV 3/ LQVWUXFWLRQV DQG VHTXHQFHU GDWD KHOG LQ ((3520 VHH RUJ + VHFWLRQ OG 3257$ (QDEOH LQSXW VLQJOHVKRW VHTXHQFH VHT G 26/ 6HTXHQFHU ZLWK VWHSV
  • 490. +] FORFN LQSXW 7 PV
  • 491. SXWU 6(4 3257% RS VHTXHQFHU YDOXH WR 3RUW % HQGS 0DUNV HQG RI 3/ SURJUDP ,ISTINGªª0RODUCINGªAªSINGLE SHOTªSEQUENCEªWITHªDEFAULTªDATAª ,ST?ASM LQFOXGH )3/ 'HILQHV 3/ LQVWUXFWLRQV DQG VHTXHQFHU GDWD KHOG LQ ((3520 VHH RUJ + VHFWLRQ OGBQRW 6(4),1 (QDEOH LQSXW FRQWLQXRXVO UXQQLQJ VHT G 26/ 6HTXHQFHU ZLWK VWHSV
  • 492. +] FORFN LQSXW 7 PV
  • 493. SXWU 6(4 3257% RS VHTXHQFHU YDOXH WR 3RUW % HQGS 0DUNV HQG RI 3/ SURJUDP ,ISTINGªª0RODUCINGªAªREPEATINGªDISPLAYª ,ST?ASM 7KLV VHFWLRQ LQLWLDOLVHV ((3520 GDWD RUJ + 3XW ((3520 GDWD KHUH IRU XVH E WKH VHT VHTXHQFHU
  • 494. FRPPDQG 8S WR EWHV DUH DYDLODEOH ZLWK WKH 3,) 7UDIILF OLJKW GDWD LV VKRZQ EHORZ GH % 6WHS 5HG GH % 6WHS 5HG $PEHU GH % 6WHS *UHHQ RI
  • 495. GH % 6WHS *UHHQ RI
  • 496. GH % 6WHS *UHHQ RI
  • 497. GH % 6WHS *UHHQ RI
  • 498. GH % 6WHS *UHHQ RI
  • 499. GH % 6WHS ± $PEHU ,ISTINGªª#USTOMªTRAFlCªLIGHTªSEQUENCERªDATA LQFOXGH )B/3/ 'HILQHV 3/ LQVWUXFWLRQV DQG VHTXHQFHU GDWD KHOG LQ ((3520 VHH 25* + VHFWLRQ OGBQRW 6(4),1 (QDEOH FRQWLQXRXV RSHUDWLRQ DQG 3257$ ZLWK D VHSDUDWH HQDEOH LQSXW VHT G 26/ 6HTXHQFHU ZLWK VWHSV
  • 500. +] FORFN LQSXW SXWU 6(4 3257% RS VHTXHQFHU YDOXH WR 3RUW % HQGS 0DUNV HQG RI 3/ SURJUDP ,ISTINGªª4HEªTRAFlCªLIGHTªPROGRAMª 6?ILES,ST?ASM
  • 501. 4 Everyday Practical Electronics, March 2010 Teach-In 2010 FOR A RUNNING LIGHT DISPLAY HAS ALREADY BEEN PLACED INTO THE HEADER ÚLES SUP PLIED WITH 0ART OF THE SERIES 4HE ONLY REMAINING STEP IS TO WRITE A SHORT SEQUENCER PROGRAM
  • 502. WITH A SIMPLE EXAMPLE SHOWN IN ,ISTING 4HIS PROGRAM PRODUCES A NON REPEAT ING OUTPUT SEQUENCE ON 0ORT
  • 503. WHICH IS TRIGGERED BY AN ACTIVE HIGH ENABLE INPUT CONNECTED TO BIT OF 0ORT ! 4HIS ENABLEINPUTMUSTBEHELDCONTINUOUSLY HIGH DURING THE SEQUENCE
  • 504. CAUSING THE SEQUENCER TO BE RESET WHEN IT GOES LOW 4HE SEQUENCER ITSELF IS DEÚNED US ING THE lSEQm COMMAND
  • 505. WHICH IN THIS CASE HAS STEPS IN THE SEQUENCE TO MATCH THE DATA DEÚNED IN THE HEADER ÚLE SUPPLIED WITH 0ART OF THE SERIES /UTPUT DATA FROM THE CURRENT STEP IN THE SEQUENCE IS HELD IN THE 3%1 REGIS TER
  • 506. WHICH IS DISPLAYED ON OUTPUT PORT BY THE lPUTRm COMMAND )T IS QUITE SIMPLE TO ADAPT THIS PRO GRAM IN ORDER TO CREATE A CONTINUOUSLY RUNNING SEQUENCE
  • 507. AS SHOWN IN ,ISTING )NTHISCASE
  • 509. l3%1).
  • 510. m IS ÚRST INVERTED AND THEN USED AS THE ENABLE INPUT TO THE SEQUENCER !T ÚRST
  • 511. THE SEQUENCER IS ENABLED BECAUSE IT IS NOT YET ÚNISHED
  • 513. CAUSING THE SEQUENCER TO RESTART 4HE SEQUENCER FEATURE IS BEST SUITED TO APPLICATIONS NOT REQUIRING ANY GREAT DECISION MAKING CAPACITY
  • 514. WHERE A ÚXED OUTPUT SEQUENCE IS TO BE GENERATED AT REGULAR INTERVALS )F A MORE ÛEXIBLE SYSTEM IS REQUIRED THEN A lÚNITE STATE MACHINEm MAY BE A BETTER CHOICE
  • 515. AND THIS TYPE OF SYSTEM WILL BE EXPLORED AS A CUSTOMISATION TOPIC IN THE ÚNAL PART OF THE SERIES #REATINGªAªCUSTOMªSEQUENCE (AVING MASTERED THE SEQUENCER PRO GRAMMING SIDE OF THINGS
  • 516. THE NEXT STEP IS TO CREATE OUR OWN CUSTOM SEQUENCER DATA ! SIMPLE TRAFÚC LIGHT DISPLAY WILL BE USED AS AN EXAMPLE TO ILLUSTRATE THE PROCESS INVOLVED )F YOU HAVE NOT ALREADY DONE SO
  • 517. YOU SHOULD DOWNLOAD THE ÚLE CONTAINING ZIPPED PROGRAM LISTINGS FOR 0ART OF THE SERIES AS USUAL
  • 518. EXTRACTING THESE TO THE SAME FOLDER USED FOR OTHER PARTS 9OU SHOULD NOTICE THAT A SUB FOLDER CALLED l6?ILESm HAS BEEN CREATED 4HIS FOLDER CONTAINS AN UPDATED SET OF HEADER ÚLES
  • 519. WHICH HAVE BEEN MODIÚED TO INCLUDE THE TRAFÚC LIGHT SEQUENCER DATA
  • 520. WITH THE RELEVANT SEQUENCER CONTENT FOR THE 0)# MICROCON TROLLER BEING SHOWN IN ,ISTING .OTICETHAT%%02/-DATAISSPECIÚED ASASERIESOFDATABYTES
  • 521. STARTINGATHEXA DECIMAL MEMORY LOCATION 4HE ACTUAL SEQUENCER DATA CONSISTS OF EIGHT STEPS
  • 523. AMBER AND GREEN TRAFÚC LIGHTS ASSUMED TO BE CONNECTED TO THE RIGHTMOST SEQUENCER OUTPUT BITS !SSUMING THAT EACH STEP LASTS FOR ONE SECOND
  • 524. THEN WE CAN SEE THAT THE GREEN OUTPUT WILL BE ACTIVE FOR ÚVE SECONDS
  • 525. WITH ALL OTHER STATES LASTING ONE SECOND EACH 4HE SEQUENCER WILL OPERATE IN CONTINUOUS MODE
  • 526. AUTOMATICALLY RE TURNING TO STATE AFTER THE ÚNAL STATE
  • 527. THUS GIVING AN AMBER TO RED TRANSITION ! SUITABLE TRAFÚC LIGHT PROGRAM IS GIVEN IN ,ISTING
  • 528. THIS TIME WRITTEN FOR THE 0)# WITH LOW VOLTAGE PROGRAMMING ENABLED .OTICE THAT CONTINUOUS OPERATION HAS BEEN ENABLED
  • 529. AND AN ADDITIONAL ENABLE INPUT HAS BEEN ADDED
  • 530. LINKED TO BIT OF 0ORT ! 4HE UPDATED SOFTWARE SUPPLIED IN 6ERSION TURNS OFF THE SEQUENCER OUTPUT WHEN IT IS DISABLED
  • 531. AND MAKES OTHER MINOR CORRECTIONS
  • 532. AS DETAILED IN THE RELEASE NOTES 2EADERS WITH 0ROTEUS 63- SIMULA TION SOFTWARE MAY OPTIONALLY CONNECT A lTRAFÚC LIGHTSm COMPONENT TO THE OUTPUT PORT
  • 533. AS SHOWN IN IG OR OTHERS
  • 534. THE PROGRAM MAY EASILY BE ADAPTED TO RUN ON SUPPORTED HARD WARE PLATFORMS
  • 535. IN WHICH CASE THE COLOUR OF THE TRAFÚC LIGHT ,%$S MAY NEED TO BE IMAGINEDØ !N INTERESTING EXERCISE FOR THE READER WOULD BE TO EXTEND THE ABOVE SYSTEM TO CONTROL A PAIR OF TRAFÚC LIGHTS AT A CROSSROADS NORTH SOUTH AND EAST WEST OPERATION 9OU MAY ALSO LIKE TO THINK OF OTHER APPLI CATIONS OF SEQUENCERS
  • 536. INCLUDING ELECTRONIC TOYS AND DECORATIONS $EVELOPMENT OF NEW SYSTEMS AND APPLICATIONS CAN BE BOTH INTERESTING AND CREATIVE
  • 537. AND WILL ALSO GIVE YOU PLENTY OF OPPORTUNITIES TO PRACTISE YOUR HARDWARE DESIGN SKILLS 3UMMARY 7E HAVE COVERED A LOT OF GROUND THIS MONTH
  • 538. RANGING FROM HARDWARE DESIGN AND THE USE OF COMPUTER BASED SIMULA TION
  • 540. AND EVEN SIMPLE SEQUENCER BASED SYSTEMS 3EVERAL OF THESE TOPICS WILL BE EXPANDED IN THE NEXT AND ÚNAL PART OF THE SERIES
  • 541. WHICH WILL FOCUS ON CUS TOMISATION OF THE SOFTWARE .EXTª-ONTH )N THE ÚNAL PART OF THE SERIES WE WILL ADD A NUMBER OF CUSTOM EXTENSIONS TO THE 0,# SOFTWARE
  • 542. CREATING AN UP DATED VERSION IN THE PROCESS 4HIS WILL GREATLY EXTEND THE RANGE OF POTENTIAL APPLICATIONS OF THE SOFTWARE 4OPICS CONSIDERED WILL INCLUDE • #ONÚGURING DEVICE OPTIONS PORT DIRECTIONS
  • 544. OPTION AND CONÚGURATION REGISTER SETTINGS •#ONDITIONAL SUBROUTINES q EXECUT ING A BLOCK OF CODE IF A CONDITION IS TRUE •5SING LOOKUP TABLES FOR CODE CON VERSION q CONVERTING BINARY CODES TO AND FROM OTHER FORMATS A TECHNIQUE WITH A SURPRISINGLY LARGE RANGE OF PO TENTIAL APPLICATIONS • INITE STATE MACHINE q CREATION OF POWERFUL AND ÛEXIBLE STATE BASED SYSTEMS 4HESE EXTENSIONS WILL ENABLE US TO CONTROL DEVICES
  • 546. $# MOTORS AND STEP PER MOTORS
  • 547. WITH THE POSSIBILITY OF DIGITAL POSITION MEASUREMENT USING 'RAY CODE 7E WILL ALSO REVISIT THE TRAFÚC LIGHT APPLICATION ONE LAST TIME
  • 548. DEMONSTRAT ING THAT A ÚNITE STATE MACHINE APPROACH OFFERS INCREASED ÛEXIBILITY COMPARED TO THE SEQUENCER BASED METHOD CON SIDERED ABOVE IGª#ONNECTINGª AªTRAFlCªLIGHTªª COMPONENTªINªª 0ROTEUSª63-
  • 549. HandsOn Technology http://www.handsontec.com Low Cost 8051C Starter Kit/ Development Board HT-MC-02 HT-MC-02 is an ideal platform for small to medium scale embedded systems development and quick 8051 embedded design prototyping. HT-MC-02 can be used as stand-alone 8051C Flash programmer or as a development, prototyping and educational platform Main Features:  8051 Central Processing Unit.  On-chip Flash Program Memory with In-System Programming (ISP) and In Application Programming (IAP) capability.  Boot ROM contains low level Flash programming routines for downloading code via the RS232.  Flash memory reliably stores program code even after 10,000 erase and program cycles.  10-year minimum data retention.  Programmable security for the code in the Flash. The security feature protects against software piracy and prevents the contents of the Flash from being read.  4 level priority interrupt 7 interrupt sources.  32 general purpose I/O pins connected to 10pins header connectors for easy I/O pins access.  Full-duplex enhanced UART – Framing error detection Automatic address recognition.  Programmable Counter Array (PCA) Pulse Width Modulation (PWM).  Three 16-bits timer/event counters.  AC/DC (9~12V) power supply – easily available from wall socket power adapter.  On board stabilized +5Vdc for other external interface circuit power supply.  Included 8x LEDs and pushbuttons test board (free with HT-MC-02 while stock last) for fast simple code testing.  Industrial popular window Keil C compiler and assembler included (Eval. version).  Free Flash Magic Windows software for easy program code down loading. PLEASE READ HT-MC-02 GETTING STARTED MANUAL BEFORE OPERATE THIS BOARD INSTALL ACROBAT READER (AcrobatReader705 Application) TO OPEN AND PRINT ALL DOCUMENTS
  • 550. Everyday Practical Electronics, April 2010 45 Teach-In 2010 By Walter Ditch Part 6: Customising and Extending the Software T HE ÚRST ÚVE PARTS OF THIS SERIES FOCUSED ON USING THE 0,# SOFT- WARE IN ITS SUPPLIED FORM
  • 551. WITH EACH INSTALMENT CONCENTRATING ON A DIFFERENT ASPECT OF LADDER LOGIC BASED DESIGN )F YOU HAVE BEEN FOLLOWING THE SERIES
  • 552. THEN BY NOW YOU SHOULD HAVE A GOOD UNDERSTANDING OF THE CONCEPTS INVOLVED
  • 553. AND BE COMFORTABLE WRITING SIMPLE LADDER LOGIC BASED 0)# PRO- GRAMS OF YOUR OWN 9OU MAY SOON ÚND YOURSELF WANTING TO MODIFY AND EXTEND THE SOFTWARE TO SUIT THE REQUIREMENTS OF NEW APPLICA- TIONS AND SCENARIOS 4HIS BECOMES PARTICULARLY TRUE IN EMBEDDED CONTROL APPLICATIONS
  • 554. WHERE 0)# MICROS MAY BE DEPLOYED IN SITUATIONS GREATLY DIFFERENT TO THOSE ENCOUNTERED BY A TYPICAL 0,# 7ITH THIS IN MIND
  • 555. THIS ÚNAL INSTAL- MENT LOOKS AT A VARIETY OF OPTIONS FOR RECONÚGURING
  • 557. AND EXTEND- ING THE SOFTWARE 4OPICS CONSIDERED HERE ARE GROUPED INTO THE FOLLOWING THREE MAIN AREAS 5NDERSTANDING AND MODIFYING DEFAULT SETTINGS /PTIMISING PROGRAM CODE %XTENDING THE 0,# SOFTWARE 4HE GOOD NEWS IS THAT THE 0,# SOFTWARE IS EASY TO CUSTOMISE OR EVEN EXTEND
  • 558. AS WE WILL SEE SHORTLY !LL REQUIRED PROGRAM ÚLES FOR THIS SERIES ARE AVAILABLE FROM THE ,IBRARY 4UTORIALS SECTION OF THE Everyday Practical Electronics WEBSITE www. epemag.com/ 4HE :)0 ÚLE SUPPLIED WITH THIS ÚNAL PART OF THE SERIES IS RATHER SPECIAL
  • 559. SINCE IT INCLUDES A NEW VERSION OF THE 0,# SOFTWARE 6ERSION
  • 560. WHICH INCORPORATES ALL CUSTOMI- SATION EXTENSIONS DISCUSSED HERE
  • 561. PLUS ALL PROGRAM LISTINGS AND OTHER SUPPLIED ÚLES FROM THE ENTIRE SERIES /NCE THIS ÚLE IS INSTALLED
  • 562. YOU WILL BE ABLE TO TRY OUT THE EXAMPLES FROM 0ARTS TO
  • 563. EVEN IF YOU HAVE NOT PREVIOUSLY DOWNLOADED FILES ASSOCIATED WITH EARLIER PARTS OF THE SERIES !S DISCUSSED PREVIOUSLY
  • 564. YOU SHOULD USE THE FREELY AVAILABLE -0,! )$% SOFTWARE TO ASSEMBLE THE PROGRAM EXAMPLES 4HIS MAY BE DOWNLOADED FROM THE -ICROCHIP WEBSITE www. microchip.com/mplab/ )N ORDER TO RUN THE PROGRAMS
  • 565. YOU WILL NEED A SUITABLE 0)# DEVELOPMENT BOARD
  • 566. ÚT- TED WITH ONE OF THE SUPPORTED 0)# MICROCONTROLLER TYPES
  • 567. OR SIMULATION SOFTWARE SUCH AS 0ROTEUS 63- FROM ,ABCENTER %LECTRONICS Changing default settings 9OU MAY WANT TO REVIEW AND CHANGE DEFAULT SETTINGS
  • 568. EITHER TO SUIT AVAILABLE 0)# BASED HARDWARE
  • 569. OR TO MEET THE REQUIREMENTS OF A NEW DESIGN )F YOU ARE HAPPY WITH THE DEFAULT SETTINGS
  • 570. AS SUPPLIED WITH THE SOFTWARE
  • 571. THEN YOU MAY PREFER TO SKIP THIS SECTION AND COME BACK TO IT LATER %ACH0,#HEADERÚLEISPRECONÚGURED WITHAVARIETYOFSENSIBLEDEFAULTS
  • 572. WHICH ALLOWS YOU TO GET YOUR PROGRAMS UP AND RUNNING WITH THE MINIMUM OFFUSS9OU CANREVIEWANDCHANGETHESEDEFAULTSET- TINGS BY LOADING THE APPROPRIATE HEADER ÚLE INTO A TEXT EDITOR SUCH AS -ICROSOFT .OTEPAD -AJOR CONÚGURATION OPTIONS INCLUDEINPUTOUTPUTPORTDIRECTION
  • 574. PLUS CONÚGURATION AND OPTION REGISTER SETTINGS 3HOULDYOUDECIDETOMODIFYANYSET- TINGS
  • 575. THE ÚRST STEP IS TO ENSURE YOU HAVE ABACKUPCOPYOFTHEORIGINALHEADERÚLE
  • 576. ALLOWING YOU TO REVERT BACK IF REQUIRED 9OU MIGHT
  • 578. CREATE A SUB FOLDER TO CONTAIN YOUR CUSTOM PROJECT
  • 579. PLACING A COPY OF THE ORIGINAL HEADER ÚLE INTO YOUR NEW FOLDER !NY ASSEMBLY LANGUAGE ÚLES PLACED IN THIS NEW FOLDER WILL MAKE USE OF THE CUSTOM HEADER ÚLE
  • 580. WHEN ASSEMBLED Reviewing input/output port settings !LL SUPPORTED 0)# MICROCONTROLLERS
  • 582. ARE CONÚGURED TO USE 0ORT ! AS AN INPUT PORT AND 0ORT AS AN OUTPUT (IGHER ORDER BITS OF 0ORT ! ARE ALLOCATED FOR USE BY THE -#,2 MASTER CLEAR OR EXTERNAL RESET PIN
  • 583. AND BY AN OPTIONAL EXTERNAL OSCILLATOR 4HIS GIVES US A MAXIMUM TEACH-IN 2010 LADDER LOGIC PROGRAMMING FOR THE PIC MICRO
  • 584. 46 Everyday Practical Electronics, April 2010 Teach-In 2010 PIC16F627A, PIC16F628A, PIC- ! q CONÚGURATION WORD
  • 586. ).4#/.
  • 587. 0)% AND #-#/. REGISTERS 0)# q CONÚGURATION WORDS AND
  • 588. /04)/.
  • 589. ).4#/.
  • 591. 330#/.
  • 592. #-#/.
  • 593. !.3%, AND !$#/. REGISTERS 0)# q CONÚGURATION WORDS AND
  • 594. /04)/.
  • 595. ).4#/.
  • 596. 0)%
  • 597. #-#/.
  • 598. 0#/.
  • 599. !.3%,
  • 600. 705 AND )/# REGISTERS !DVANCED USERS MAY WISH TO RE- VIEW AND CHANGE THESE OPTIONS
  • 601. BUT THE DEFAULTS SHOULD SUIT THE MAJORITY OF READERS 4HE MAIN AIM IS TO ENSURE CONSISTENT SETTINGS ACROSS ALL SUP- PORTED MICROCONTROLLERS
  • 602. AS ORIGINALLY SUMMARISED IN 4ABLE 0ART 4HIS INCLUDES OSCILLATOR
  • 603. TIMER AND INTER- RUPT CONÚGURATION
  • 605. SOFTWARE PORTABILITY BE- TWEEN MICROCONTROLLERS HAS BEEN PRIORITISED OVER THE ENABLING OF DEVICE SPECIÚC OPTIONS
  • 609. THIS IS ALSO A POTENTIAL AREA FOR FUTURE EXPERIMENTATIONØ )N THE EVENT THAT YOUR PROGRAMS FAIL TO OPERATE ON AVAILABLE HARD- WARE
  • 610. THEN OSCILLATOR CONÚGURATION MIGHT BE A PRIME SUSPECT
  • 611. AS SET IN THE CONÚGURATION REGISTER AREA 4HESE REGISTER SETTINGS ARE ALSO A KEY AREA FOR REVIEW
  • 612. SHOULD YOU WISH TO ADAPT THE SOFTWARE TO RUN ON A DIFFERENT 0)# MICROCONTROLLER 4HIS FIRST SECTION HAS FOCUSED ON UNDERSTANDING AND MODIFYING DEFAULT CONFIGURATION SETTINGS 4HE NEXT PART INTRODUCES A NUMBER OF SIMPLE TECHNIQUES WHICH MAY BE USED TO MAKE YOUR PROGRAMS SMALLER
  • 613. FASTER AND MORE EFFECTIVE 4HE THIRD AND FINAL SECTION WILL CONCLUDE THE SERIES BY LOOKING AT THE DEVELOP- MENT OF CUSTOM EXTENSIONS TO THE 0,# SOFTWARE Optimising program code 4HIS SECTION CONSIDERS SOME RELA- TIVELY STRAIGHTFORWARD WAYS TO OPTI- MISE YOUR PROGRAMS
  • 614. INCLUDING 2EDUCING PROGRAM SIZE #REATING USER DEÚNED VARIABLES -IXING ASSEMBLY LANGUAGE AND LADDER LOGIC OF ÚVE INPUT BITS AND EIGHT OUTPUT BITS FOR INTERFACING TO EXTERNAL HARDWARE 3HOULD THIS BE INADEQUATE
  • 615. THEN ONE OPTION WOULD BE TO USE A 0)# MICROCONTROLLER
  • 616. WHICH IS CONÚGURED BY DEFAULT WITH INPUT BITS 0ORTS !
  • 617. AND %
  • 618. PLUS A FURTHER OUTPUT BITS 0ORTS # AND $ )F THE ALLOCATION BETWEEN INPUTS AND OUTPUTS BE INAP- PROPRIATE
  • 619. THEN AN ALTERNATIVE MIGHT BE TO EDIT THE PORT CONÚGURATION SECTION OF THE APPROPRIATE HEADER ÚLE
  • 620. AS WE WILL DISCUSS SHORTLY 7HICHEVER 0)# IS CHOSEN
  • 621. THE DIREC- TIONOFTHEPORTISDEÚNEDBYÚRSTWRITING A CONÚGURATION BYTE TO THE APPROPRIATE lTRISTATEmREGISTER 42)3!
  • 622. 42)3
  • 623. 42)3#
  • 624. 42)3$
  • 626. WITH THE ÚNAL LETTER INDICATING THE PORT NAME 0LACING A lm INTO AN APPROPRIATE BIT OF THE TRISTATE REGISTER CONÚGURES THE SAME BIT OF THE ASSOCIATED PORT AS AN INPUT
  • 628. ,ISTING SHOWS A SLIGHTLY SIMPLIÚED EXTRACT OF THE PORT CONÚGURATION SECTION OF THE 0)# HEADER ÚLE CALLED MANY TIMES PER SECOND
  • 629. THUS PREVENTING AN AUTOMATED SYSTEM RESET )N THE EVENT OF A CRASH
  • 630. THEN THE MAIN PROGRAM LOOP STOPS RUNNING
  • 631. THE 7$4 EXPIRES AND THE SYSTEM IS AUTOMATI- CALLY RESTARTED 2EFER BACK TO IG 0T .OV m AND ASSOCIATED TEXT FOR MORE INFORMATION REGARDING THE SCAN LOOP AND PROGRAM EXECUTION 9OU DONmT NEED TO DO ANYTHING IN ORDER TO USE THE 7$4 FEATURE
  • 632. AS THIS HAS BEEN ENABLED WITHIN THE HEADER ÚLE BY SETTING THE APPROPRIATE CONÚGURA- TION REGISTER BIT 4HE ÚRST INSTRUCTION IN THE SCAN LOOP IS A CLEAR WATCHDOG TIMER COMMAND
  • 633. WHICH PREVENTS AN AUTOMATIC RESET AS LONG AS THE SCAN LOOP IS RUNNING 7$4 CONFIGURATION SETTINGS ARE FAIRLY BASIC
  • 634. BEING LARGELY THE PROCES- SOR DEFAULTS 4HE NOMINAL TIMEOUT WITH THE 0)#!
  • 636. IS MS WITH NO PRESCALER
  • 637. SO THERE SHOULD NOT BE A PROBLEM AS LONG AS THE TIME FOR ONE SCAN LOOP IS LESS THAN THIS !S A CHECK
  • 638. ASSUMING KB setports movlw 0x1f ; Set bits 0-4 as inputs (1 = input, 0 = output) movwf TRISA ; Set TRISA register (Port A = all inputs) movlw 0x00 ; Set bits 0-7 as outputs movwf TRISB ; Set TRISB register (Port B = all outputs) ,ISTINGªª#ONlGURINGª0)#ªPORTªDIRECTIONS 4HE APPROPRIATE SECTION OF THE ÚLE MAY EASILY BE FOUND BY SEARCHING FOR THE lSETPORTSm LABEL #LEARLY
  • 639. IT IS NOT TOO DIFÚCULT TO CHANGE THE DEFAULT PORT SETTINGS r SIMPLY CHANGE THE VALUES WRITTEN INTO THE APPROPRIATE TRISTATE REGISTERS
  • 641. YOU SHOULD ÚRST CHECK THE APPROPRIATE DATA SHEET
  • 642. JUST TO MAKE SURE THAT THE AFFECTED PORT BITS HAVE NO SPECIAL )/ RESTRICTIONS IT 2% ON THE 0)#
  • 644. CANNOT BE CONÚGURED AS A GENERAL PURPOSE OUTPUT Using the watchdog timer -ICROCONTROLLERS MAY OFTEN BE USED IN ELECTRICALLY NOISY ENVIRONMENTS
  • 645. LEADING TO THE POSSIBILITY OF A SOFTWARE lCRASHm #LEARLY
  • 646. THE MAIN DEFENCE AGAINST ELECTRICAL NOISE SHOULD BE GOOD ELECTRICAL DESIGN (OWEVER
  • 647. THE WATCH- DOG TIMER 7$4 FEATURE PROVIDES A USEFUL BACKUP
  • 648. CAUSING THE MICROCON- TROLLER TO BE AUTOMATICALLY RESTARTED IF IT FAILS TO RESPOND IN A PREDETERMINED TIME PERIOD 4HE BASIC IDEA IS THAT THE MAIN PRO- GRAM SCAN LOOP SHOULD CONTAIN A lCLEAR WATCHDOG TIMERm COMMAND
  • 649. WHICH IS OF PROGRAM MEMORY AND A -(Z OS- CILLATOR µS PER TYPICAL INSTRUCTION
  • 650. THEN THE MAXIMUM TIME FOR ONE SCAN LOOP WOULD BE AROUND MS 5SER CONÚGURATION OPTIONS INCLUDE DISABLING THE 7$4
  • 651. BY CLEARING THE APPROPRIATE CONFIGURATION REGISTER BIT
  • 652. OR CHANGING 7$4 DEFAULTS )T IS WELL WORTH REVIEWING THE DATASHEET FOR 7$4 OPTIONS
  • 653. AS SOME MICRO- CONTROLLERS HAVE A DEDICATED 7$4 CONÚGURATION REGISTER (OWEVER
  • 654. ON A CAUTIONARY NOTE YOU SHOULD GENERALLY AVOID ALLOCATING A PRE SCALER TO THE 7$4
  • 655. AS THIS MAY AFFECT OPERATION OF THE 0,# SOFTWAREmS HIGH SPEED OSCILLA- TOR REGISTER /3#( Modifying device CONlGURATIONªOPTIONS %ACH HEADER ÚLE CONTAINS A RANGE OF DEFAULT CONÚGURATION SETTINGS
  • 656. WHICH HAVE BEEN SELECTED TO SUIT THE MAJOR- ITY OF USERS 4HE EXACT OPTIONS AVAIL- ABLE VARY FROM ONE MICROCONTROLLER TO ANOTHER
  • 657. BUT TYPICALLY INVOLVE ONE OR MORE lCONÚGURATION WORDSm
  • 659. PLUS OTHER MISCELLANE- OUS REGISTERS 2EGISTER BASED SETTINGS CONÚGURED VIA HEADER ÚLES INCLUDE
  • 660. Everyday Practical Electronics, April 2010 4 Teach-In 2010 Methods of reducing program size Even the simplest of lad- der logic programs is likely to use 130 to 180 program words when assembled, due mainly to the over- head introduced by the HEADER ÚLE 4HIS SHOULD not be a problem in most scenarios, since supported PIC microcontrollers are available with program memory sizes in the range TO KWORDS 2EFER BACK TO 4ABLE FOR DETAILS OF PROGRAM MEMORY SIZES A simple way to keep track of program memory usage is to read the summary information at the end of the ASSEMBLER lLISTINGm ÚLE THE ÚLE HAVING A lLSTm ÚLE EXTENSION !N EXAMPLE is shown below for the PIC16F887 MICROCONTROLLER Program Memory Words Used: 181 Program Memory Words Free: 8011 While it is vital to keep track of the size of your assembled machine code program, it is equally impor- tant to keep your source code files CONCISE AND YET EASY TO UNDERSTAND It is always a good idea to make liberal use of comments, in order TO EXPLAIN THE OPERATION OF YOUR PROGRAM 4HESE COMMENTS WILL HELP others to understand your programs, and in any case will be removed at ASSEMBLY TIME 4HE LARGE NUMBER OF MACRO DEÚNI- TIONS IN THE HEADER ÚLE WILL NOT HAVE any effect on the program size, as these will only be assembled if they are actu- ALLY USED (OWEVER
  • 661. IT IS WORTH NOTING that additional customisation features INTRODUCED WITH 6ERSION OF THE SOFTWARE HAVE ADDED APPROXIMATELY 80 program words to the minimum program size, due mainly to the use of lookup tables FOR CODE CONVERSION MORE ON THIS LATER One possibility for code SIMPLIÚCATION MIGHT BE the use of a single byte-ori- ented command in place of several bit-oriented COMMANDS ! SINGLE lPUTIm or ‘putr’ command, for EXAMPLE
  • 662. MIGHT PERFORM the same task as several ‘ld’ and ‘out’ instructions UP TO EIGHT OF EACH !S AN EXAMPLE
  • 663. ,ISTING SHOWS TWO alternative ways to transfer data from AN INPUT PORT TO AN OUTPUT PORT Another possibility for moderate CODE SIMPLIÚCATION IS TO MAKE DIRECT use of the output produced by a previ- OUS COMMAND AS THE INPUT TO THE NEXT 4HIS APPROACH IS USED ROUTINELY IN LAD- der logic programs, but can also offer an alternative to manually reading the STATUSBITVALUEOFAPREVIOUSCOMMAND 4HE KEY TO UNDERSTANDING THIS AP- proach is to realise that the majority of commands leave their result, or their STATUS BIT
  • 664. IN THE 7ORKING REGISTER 7 OF THE 0)# MICRO 4HIS VALUE IS EITHER USED IMMEDIATELY BY THE NEXT PROGRAM STATEMENT
  • 665. OR IT IS OVERWRITTEN !N OB- VIOUS EXAMPLE OF THIS APPROACH IS THE ‘ld’ command, which simply leaves its INPUTTED VALUE IN THE LEAST SIGNIÚCANT BIT OF THE 7 REGISTER ! CORRESPONDING ‘out’ command takes this value from the W register, sending it to the speci- ÚED DESTINATION ,ESS OBVIOUSLY
  • 666. OTHER commands such as counters, timers and shift registers all offer similar functionality, giving the possibility of SIMPLIÚCATION
  • 667. WITH CAREFUL ORDERING OF COMMANDS 2ECALL
  • 669. THAT ,ISTING *AN m USED THIS TECHNIQUE TO LINK OR ‘chain’ multiple shift registers, with the data shifted out by a previous command being left in the W regis- ter, automatically becoming the data SHIFTED IN BY THE NEXT COMMAND ! SIMILAR APPROACH WAS USED IN ,ISTING EB m
  • 670. WHERE MULTIPLE COUNTERS were cascaded to create a custom COUNTERTIMER A potential disadvantage of this technique is the possibility of making program operation rather cryptic, so it should perhaps be used sparingly, AND WITH APPROPRIATE EXPLANATION IN THE FORM OF COMMENTS #REATINGªUSER DElNEDªVARIABLES )N A COMPLEX PROGRAMMING SCE- nario, the software’s default alloca- TION OF EIGHT AUXILIARY REGISTERS !58 TO !58 TOTALLING BITS MIGHT BE INSUFÚCIENT ORTUNATELY
  • 672. SHOULD THE NEED ARISE Currently, allocated general purpose REGISTERS ARE DEÚNED TOWARD THE START OF THE APPROPRIATE HEADER ÚLE
  • 673. WITH MEMORY LOCATIONS $q# HEXADECI- MAL BEING UNALLOCATED
  • 674. AS OF 6ERSION 3IMPLY ADD ANY REQUIRED VARI- ABLE DEÚNITIONS IN THIS SECTION OF THE APPROPRIATE HEADER ÚLE
  • 675. BEING CAREFUL include 16F887.PLC ; Defines PLC instructions putr PORTA, PORTC ; Transfer Port A to Port C ld PORTB, 0 ; Read Port B bit 0 out PORTD, 0 ; Output to Port D bit 0 ld PORTB, 1 ; Read Port B bit 1 out PORTD, 1 ; Output to Port D bit 1 ld PORTB, 2 ; Read Port B bit 2 out PORTD, 2 ; Output to Port D bit2 ; etc. endp ; End of PLC program ,ISTINGªª#OMPARINGªBITªANDªBYTEªORIENTEDªPROBLEMªSOLUTIONSª ,ST?ASM ª ; Unused Ram locations 6DH – 74H TEMP0 EQU H'75' ; Block of eight user defined variables (start) TEMP1 EQU H'76' TEMP2 EQU H'77' TEMP3 EQU H'78' TEMP4 EQU H'79' TEMP5 EQU H'7A' TEMP6 EQU H'7B' TEMP7 EQU H'7C' ; Block of eight user defined variables (end) STEMP EQU H'7D' ; Stores Status register value during an Interrupt ; Service Routine (ISR) WTEMP EQU H'7E' ; Stores W register value during an ISR LOGIC EQU H'7F' LASTRAM EQU H'7F' Defining a block of eight user defined variables.,ISTINGªª$ElNINGªAªBLOCKªOFªEIGHTªUSERªDElNEDªVARIABLES
  • 676. 4 Everyday Practical Electronics, April 2010 Teach-In 2010 be ‘nested’ up to eight levels deep. (However, bear in mind that the PLC software makes use of inter- rupts, hence using the stack to hold return addresses from interrupt service routines. This means that you should not nest subroutines more than seven levels deep with the PLC software.) The subroutine is called from the main program, with the subrou- TINE IDENTIÚED BY A LABEL WHICH IS placed in the left margin next to the ÚRST INSTRUCTION 4HE RETURN STATE- ment causes execution of the main program to resume at the program line immediately following the call statement. It is necessary to place the subrou- TINE DEÚNITIONS OUTSIDE OF THE MAIN scan loop, in order to avoid a soft- WARE CRASH DUE TO STACK lUNDERÛOWm (trying to return from a subroutine which hasn’t actually been called in the proper way). This is achieved by placing a ‘goto loop’ statement after the main program, but before the sub- ROUTINE DEÚNITIONS 4HE ÚNAL PROGRAM statement must still be the ‘endp’ macro statement, which contains an additional ‘goto loop’ statement, plus the required ‘END’ of program assem- bler directive. While this example does dem- onstrate the possibilities of mixing assembly language and ladder logic, it is structurally rather clumsy. The following section on customisation will answer this potential criticism, beginning by developing a custom extension facility for conditional and unconditional subroutine execution. This will provide us with enhanced structured programming, plus the ability to make ‘if…then…else’ style decisions. Adding custom extensions to the software This section will con- sider three different cus- tomisation scenarios, each of which will add a sig- nificant new capability to the software. Topics considered will be: Conditional program execution Code conversion Finite state machine. (Recall from the introduction that these new features are included with the updated version of the PLC soft- WARE SUPPLIED WITH THIS ÚNAL PART OF the series.) Scenario 1 – conditional code execution In the previous section, we saw just how easy it is to add subroutines to our ladder logic programs. The ‘call’ and ‘return’ assembly language state- ments, when used appropriately, allow the use of subroutines within ladder logic programs. On the downside, we had the added complexity of ‘labels’ in the left margin, plus the need to add a ‘jp loop’ statement at the end of the main program, and before the SUBROUTINE DEÚNITIONS The addition of two new macros will cure these issues, while also offering the capability to call a subroutine either unconditionally, or only if a test condition is true. These new macro DEÚNITIONS ARE SHOWN IN ,ISTING At this stage, you may like to refer back to Fig.2.7 and associated text FROM 0ART
  • 677. WHICH ÚRST INTRODUCED THE macro text substitution feature of the assembler. The essential point to un- derstand is that custom macros allow us to create our own new commands, WHICH ARE ÚRST TRANSLATED INTO ASSEM- bly language, and then converted to machine code by the assembler. As its name suggests, the ‘subdef’ COMMAND IS USED TO DEÚNE A SUB- routine, which may then be called in the normal way. The macro accepts a single parameter, which is the name of the subroutine. Notice that this argu- ment is automatically placed into the left margin by text substitution, thus eliminating the need to place your own labels. The second feature of the NOT TO USE ANY PREVIOUSLY DEÚNED VARI- ABLE NAMES 4HE EXAMPLE OF ,ISTING creates an additional eight auxiliary registers called TEMP0–TEMP7, hence increasing the number of available AUXILIARY RELAYS FROM TO On a cautionary note, there is no guarantee that these locations will not be allocated by future versions of the software. With this in mind, it is A GOOD IDEA TO PLACE ANY USER DEÚNED variables at the top end of available memory, since locations are generally allocated from low to high. Mixing assembly language and ladder logic It is quite permissible to mix assem- bly language statements and ladder logic in a single source code program, provided that the actions performed are themselves compatible. A simple but useful example would be the use of subroutine ‘call’ and ‘return’ instructions, which would allow a more structured approach to program DESIGN ,ISTING SHOWS A SIMPLE example. The program may be seen to contain three assembly language statements which are, in order ‘call’, ‘goto’ and ‘re- turn’, plus two ladder logic statements ‘puti’ and ‘endp’. There is also the ‘include’ assembler directive, plus the l35m LABEL
  • 678. WHICH HAS BEEN PLACED in the left margin in order to identify THE START OF THE SUBROUTINE DEÚNITION Subroutines may be thought of as small self-contained sub-programs, which are called from the main pro- gram, optionally returning a result in the W register. Return addresses are stored in a dedicated area of memory called the stack. Supported PIC micros have an eight-level-deep stack, allowing subroutine calls to include 16F627.PLC ; Defines PLC instructions ; Start of main program call SUB1 ; Call subroutine 1 unconditionall goto loop ; Go to start of scan loop ; Put subroutine definitions after main ; program, but before 'endp' statement. ; Subroutine 1 (called al a s) SUB1 puti b'00110011', PORTB ; Displa 33H on Port B return ; Return to main program endp ; End of PLC program Listing 6.4. Mixing assembly language and ladder logic (Lst6_4.asm)
  • 679. Everyday Practical Electronics, April 2010 4 Teach-In 2010 macro is a ‘jp loop’ command, which is automatically placed at the start of each subroutine, hence forcing the SUBROUTINE DEÚNITIONS TO BE OUTSIDE of the main scan loop. Thus, we have eliminated both of the previously mentioned subroutine issues, by use of an extremely simple macro. The second ‘ccall’ macro provides a conditional subroutine call feature, which is an alternative to the uncon- ditional subroutine call discussed previously. The idea is that the result of a previous command, such as a ‘ld’ or ‘ld_not’, is tested by the ccall statement, with the subroutine being called, only if the command returns a true result (as indicated by a logic IN THE LEAST SIGNIÚCANT BIT OF THE 7 register). The example of Listing 6.6 illus- TRATES THE USE OF OUR NEWLY DEÚNED ‘ccall’ and ‘subdef’ macros, plus pre- viously considered ‘call’ and ‘return’ assembly language commands, to implement conditional and uncondi- tional subroutines. .OTICE THAT THE PROGRAM DEÚNES three subroutines, SUB1, SUB2 and SUB3, which are placed after the main PROGRAM
  • 680. BUT BEFORE THE ÚNAL lENDPm statement. The main program consists OF JUST THREE LINES
  • 681. THE ÚRST BEING AN UNCONDITIONAL CALL TO THE ÚRST SUBROU- tine, followed by conditional calls to subroutines two and three. Notice that the conditional calls are complemen- tary, based on the state of bit 0 of Port A, so only one conditional subroutine call will be made in a single scan loop. This logical structure is important, as will now be discussed. Tips for using subroutines with ladder logic In a typical high level programming language, subroutines are de- signed to be called many times from the main program, thus offering a reusable li- brary of pre-tested code. The purpose is slightly different in our ladder logic implementation, with subroutines offering a more structured program layout, plus the ability to conditionally execute a block of code if a tested condition is true. In general, some care is needed when designing subroutine-based ladder logic programs, to ensure that individual register bits, such as inputs and outputs, are only updated once per scan cycle. For example, if an output is set to 1 at the start of the scan loop and later set to 0, the output will appear to oscillate as the scan cycle repeatedly executes. Thus, any ‘complemen- tary’ actions contained within subroutines should be called by mutually ex- clusive test conditions, as found in an if…then…else program structure. Available subroutine related com- mands are summarised in Table 6.1. Scenario 2 – code conversion The ‘retlw’ assembly language in- struction may be used as an alternative to the ‘return’ statement seen earlier, offering the facility to place a literal VALUE IN THE 7 REGISTER ON RETURNING from a subroutine. This feature com- monly allows subroutines to return a result to the calling program, or pos- sibly a success/failure result code. However, with some clever coding, the retlw command may be persuaded to perform code conversion, transform- ing binary values into a variety of other ; The 'subdef' macro defines a subroutine ; ( hich should end ith a 'return' statement) subdef macro subdef arg1 goto loop ; Go to start of scan loop subdef arg1 ; Put label in left margin for call instruction endm ; End of subroutine definition macro ; The 'ccall' macro conditionall calls a ; subroutine, but onl if the previous command ; returns a 1 in the LSB of the W register ccall macro ccall arg1 andl 0 01 ; Test least significant bit of W reg. btfss STATUS, ; Skip subroutine if LSB is clear call ccall arg1 ; Call subroutine endm ; End of macro ,ISTINGªª#ONDITIONALªSUBROUTINEªMACROªDElNITIONS include 16F887.PLC ; Defines PLC instructions ; Start of main program call SUB1 ; Call subroutine 1 unconditionall ld PORTA, 0 ccall SUB2 ; Call subroutine 2 if bit 0 of Port A 1 ld not PORTA, 0 ccall SUB3 ; Call subroutine 3 if bit 0 of Port A 0 ; End of main program ; Put subroutine definitions after main ; program, but before 'endp' statement. subdef SUB1 ; Subroutine 1 is called al a s puti b'00110011', PORTC ; Displa 0 33 on Port C return ; Return to main program subdef SUB2 ; Subroutine 2 is called if PORTA,0 1 puti b'00001111', PORTD ; Displa 0 0F on Port D return ; Return to main program subdef SUB3 ; Subroutine 3 is called if PORTA,0 0 puti b'11110000', PORTD ; Displa 0 F0 on Port D return ; Return to main program endp ; End of PLC program Listing 6.6. A simple conditional subroutine program (Lst6_6.asm)
  • 682. Everyday Practical Electronics, April 2010 Teach-In 2010 upper four bits of the binary value to zero, thus prevent- ing a potential table overflow. One slightly un- desirable feature of this technique is that the lookup table subroutine becomes a permanent feature of the assembled program, even if the associated macro is not used. This inevitably leads to a small increase in the minimum size of assembled machine code programs, but this should not be A SIGNIÚCANT ISSUE
  • 683. given that up to 8k of program memory is available in sup- ported PIC micro- controllers. It should also be noted that any lookup table subroutines must be placed in the first 256 locations of program memory, in order to prevent memory page errors when the W register is added to the lower byte of the program counter. Fig.6.1 shows a potential application of this technique to drive a single 7-seg- ment display, with the associated pro- gram shown in Listing 6.8. As can be seen, the resulting binary to 7-segment display program is re- markably simple, from a programming perspective at least, consisting of a single line of code. The real complex- ity is hidden in the lookup table and ASSOCIATED MACRO DEÚNITION Clearly, the method used here with 7-segment displays may easily be applied to other code conversion scenarios. With this in mind, a diverse selection of code conversion macros has been developed, covering topics including position measurement (Gray code), stepper motor control, plus bi- nary encoders and decoders, as given in Table 6.2. Command Function call SUBROUTINE Call a named subroutine unconditionally (assembly language statement). return Return to the main program, at the line following the subroutine call (assembly language statement). ccall SUBROUTINE Call a named subroutine conditionally, if the previous command returns a true result (in least significant bit of W register). subdef SUBROUTINE Define a named subroutine. Table 6.1. Subroutine-related commands representations. This is an extremely powerful technique, with potential applications including: 7-segment displays Gray code (position measurement) Stepper motor control Binary encoders and decoders. The basic idea is to create a sub- routine which contains a lookup table consisting of a series of retlw statements, each of which will re- turn a particular value to the calling program. We then place our initial binary value (to be converted) into the W register prior to calling the subroutine. The subroutine begins by adding the value contained in the W register to the program counter register, which causes the PIC micro to jump forwards in program memory BY THE NUMBER OF LOCATIONS SPECIÚED
  • 684. hence returning the converted value in the W register. The example of Listing 6.7 shows a subroutine used to convert a 4-bit binary value to a format capable of driving a directly connected 7-segment display, plus the associated macro DEÚNITION This example creates a new ‘bin- 27seg’ (binary to seven segment) macro definition, which in turn calls the ‘bin27seg_sub1’ subroutine to perform the actual code conver- sion. Notice the use of bit masking at the start of the subroutine as a data validation check, forcing the ; The 'bin27seg' macro calls the follo ing subroutine hich must be placed in ; the first 256 locations of program memor ; 7 segment displa look up table ; subroutine bin27seg sub1 andl 0 0f ; Mask off upper 4 bits of W to prevent table ; overflo add f PCL ; Add W to LSB of program counter and return ; ith look up value in W retl b'00111111' ; Displa '0' retl b'00000110' ; Displa '1' retl b'01011011' ; Displa '2' retl b'01001111' ; Displa '3' retl b'01100110' ; Displa '4' retl b'01101101' ; Displa '5' retl b'01111101' ; Displa '6' retl b'00000111' ; Displa '7' retl b'01111111' ; Displa '8' retl b'01100111' ; Displa '9' retl b'01110111' ; Displa 'A' retl b'01111100' ; Displa 'B' retl b'00111001' ; Displa 'C' retl b'01011110' ; Displa 'D' retl b'01111001' ; Displa 'E' retl b'01110001' ; Displa 'F' ; Macro definition for binar to segment displa conversion. bin27seg macro bin27seg arg1, bin27seg arg2 movf bin27seg arg1, W ; Put binar value into W call bin27seg sub1 ; Call lookup subroutine mov f bin27seg arg2 ; Put result in destination register endm ; End of Binar to 7 segment ; displa converter macro Listing 6.7. inary to seven segment display subroutine and macro.Listing 6.7. Binary-to-7-segment display subroutine and macro
  • 685. Everyday Practical Electronics, April 2010 Teach-In 2010 First, the priority encoder (pencode) macro provides the inverse opera- tion to the decoder command, and is implemented as a series of bit tests, rather than as a lookup table. Second, the swap nibbles (swap) macro is provided mainly for use with 7-segment displays, since it allows the upper nibble of a display buffer register to be swapped, prior to outputting to a connected 7-seg- ment display. The latter command allows ‘packed’ binary values to be used with 7-segment displays, as illustrated by the example program of Listing 6.9. Multiplexed 7-segment display The main problem with the program OF ,ISTING IS ITS INEFÚCIENT USE OF output port bits, since it requires two 8-bit output ports, just to drive a pair of 7-segment dis- plays. A multiplexed 7-segment display is MUCH MORE EFÚCIENT in its use of output port bits, as illus- trated by Fig.6.2. Unfortunately, increased I/O effi- ciency comes at the price of increased complexity of the software. As dis- cussed last month, a multiplexed display operates by briefly activating each digit inarapidlyrepeating sequence,thusgiving the illusion that all digits are simultane- ously illuminated. A suitable control program is shown in Listing 6.10. Don’t worry if this seems complex, since the program can be broken down into a number of smaller sub-sections, each of which is relatively simple to understand. First, registers AUX0 and AUX1 are used as a display buffer, holding the four digits in packed binary form. Bit 0 of Port A acts as a display en- able input, causing the output to be Command Function bin27seg SRC_REG, DST_REG Use a 4-bit binary value to drive a directly connected seven segment display. bin2gray SRC_REG, DST_REG Convert a 1–4 bit binary value to Gray code. gray2bin SRC_REG, DST_REG Convert a 1–4 bit Gray code value to binary. decode SRC_REG, DST_REG Use a 1–3 bit binary code to set a single output bit (0–7). pencode SRC_REG, DST_REG Produce a priority encoded 3-bit binary value, equivalent to the highest set input bit (0–7). step SRC_REG, DST_REG Use a 2-bit binary value to drive a 2-pole stepper motor in full step mode. hstep SRC_REG, DST_REG Use a 3-bit binary value to drive a 2-pole stepper motor in half step mode. swap SRC_REG, DST_REG Swap nibbles between source and destination registers. Table 6.2. Available code conversation macros and related commands include 16F627.PLC ; Defines PLC instructions bin27seg PORTA, PORTB ; Displa binar code from PORTA bits 0 3 ; on 7 segment displa connected to ; Port B bits 0 6 (bit 7 is unused) endp ; End of PLC program Listing 6.8. A simple binary-to-7-segment display program (Lst6_8.asm) include 16F887.PLC ; Defines PLC instructions puti 0 AB, AU 0 ; Packed digit displa buffer bin27seg AU 0, PORTC ; Displa lo er nibble on Port C s ap AU 0, AU 1 ; S ap nibbles from displa buffer bin27seg AU 1, PORTD ; Displa upper nibble on Port D endp ; End of PLC program Listing 6.9. Using packed binary values with 7-segment displays (Lst6_9.asm) Fig.6.1. Displaying a binary value on a 7-segment display Most of these new commands make the same use of lookup tables as the bin27seg command, differing mainly in the number of input bits allowed, and the binary values returned. You can review details of their implemen- tation by viewing the appropriate HEADER ÚLE IN A TEXT EDITOR (OWEVER
  • 686. note that a couple of these new mac- ros are coded slightly differently:
  • 687. Everyday Practical Electronics, April 2010 Teach-In 2010 ; Multiple ed LED Displa include 16F887.PLC ; Defines PLC instructions ; AU 0 AU 1 hold 4 digits to be displa ed puti 0 12, AU 0 ; AU 0 L.H. 2 digits of displa puti 0 34, AU 1 ; AU 1 R.H. 2 digits of displa ; AU 2 bits 0 1 aveforms are decoded to produce ; digit scan pulses (see also 'SCA ROW' subroutine) ld OSCH, 4 ; Read 8 ms aveform out AU 2, 0 ; Send to bit 0 of register AU 2 ld OSCH, 5 ; Read 16 ms aveform out AU 2, 1 ; Send to bit 1 of register AU 2 ; Conditional subroutine calls ld PORTA, 0 ccall SCA ROW ; Scan ro s if bit 0 of Port A 1 ld not PORTA, 0 ccall BLA ED ; Disable ro scan if bit 0 of Port A 0 ld PORTD, 0 ccall DIGIT1 ; Displa digit 1 if enabled ld PORTD, 1 ccall DIGIT2 ; Displa digit 2 if enabled ld PORTD, 2 ccall DIGIT3 ; Displa digit 3 if enabled ld PORTD, 3 ccall DIGIT4 ; Displa digit 4 if enabled ; Subroutine definitions subdef SCA ROW decode AU 2, PORTD ; Send digit enable pulses to Port D return subdef BLA ED ; Turn off displa driver transistors puti 0 00, PORTD ; Blank 7 segment displa return subdef DIGIT1 ; Displa digit 1 subroutine s ap AU 0, AU 3 ; S ap nibbles of AU 0 into AU 3 bin27seg AU 3, PORTC ; Send to 7 segment displa return ; Return from subroutine subdef DIGIT2 ; Displa digit 2 subroutine bin27seg AU 0, PORTC ; Send to 7 segment displa return ; Return from subroutine subdef DIGIT3 ; Displa digit 3 subroutine s ap AU 1, AU 3 ; S ap nibbles of AU 1 into AU 3 bin27seg AU 3, PORTC ; Send to 7 segment displa return ; Return from subroutine subdef DIGIT4 ; Displa digit 4 subroutine bin27seg AU 1, PORTC ; Send to 7 segment displa return ; Return from subroutine endp ; End of PLC program Listing 6.10. A multiplexed 7-segment display driver program with blanking control blanked when it is low, or enabled when high. The next section of the program cop- ies two of the higher order oscillator bits to register AUX2, which will be used to enable the four display digits in a repeating sequence. These oscilla- tor bits produce a two-bit binary count (00, 01, 10, 11, 00, ...) which repeats more than 50 times per second. This count is ‘decoded’ by the SCANROW subroutine, to enable each of the four display driver transistors, one after another, but note that the SCANROW sub- routine is only called if the display is ena- bled – as controlled by bit 0 of Port A. When the enable input is zero, then a display blanking subroutine is called instead, which turns off the four tran- sistors (Fig.6.2), thus disabling the display. During normal operation, the ‘de- code’ macro within the SCANROW sub- routine enables each transistor in turn by sending the repeating sequence 0001, 0010, 0100, 1000, 0001 … to Port D. In addition to enabling the display driver transistors, the outputbitsofPortDare also used to condition- ally call a further four subroutines (DIGIT1, DIGIT2, DIGIT3 and DIGIT4), which en- sures that the correct binary digit is output to Port C. (Notice also that the display driver subroutines make use of the ‘bin27seg’ and ‘swap’ macros consid- ered earlier.) Controlling stepper motors Two new macros have been provided to control two-pole stepper motors, in either full-step or half -step mode. The ‘step’ command takes a two- bit binary input, us- ing it to output the sequence 0011, 0110, 1100, 1001. Similarly, the ‘hstep’ macro uses a three-bit input code to generate the sequence 0001, 0011, 0010, 0110, 0100, 1100, 1001. As its name suggests, half-step mode uses intermediate states, causing the motor to move in smaller angular increments.
  • 688. Everyday Practical Electronics, April 2010 Teach-In 2010 with suitable opto- coupler hardware. Gray code uses a spe- cial binary counting sequence,suchthatonly one bit changes at any time as the disc rotates. This property elimi- nates the potential for unwanted intermediate states as the disc rotates. The latest version of the PLC software provides two new com- mands related to Gray code. The ‘bin2gray’ command generates a Gray code value based on a binary input, while the correspond- ing ‘gray2bin’ routine generates a binary code based on a Gray-coded input. It is this latter command which is used to measure the position of an output shaft, as illustrated by the example of Listing 6.13. In this case, a four-bit Gray code on Port A is converted to binary, before being output as a binary value on Port B. Bit masking techniques may option- ally be used to reduce the number of input bits, if required. 3CENARIOªªnªlNITEªSTATEª machine You may recall from Part 5, last month, that a simple sequencer was used to generate one-off or repeat- ing output sequences. This feature was seen to be ideal for generation of timed output sequences, such as those IGª!ªMULTIPLEXEDª SEGMENTªDISPLAY include 16F627.PLC ; Defines PLC instructions s ap OSCL, AU 0 ; S ap nibbles from OSCL to AU 0 step AU 0, PORTB ; Send step se uence to bits 0 3 of Port B endp ; Marks end of PLC program ,ISTINGªªASICªCONTROLªOFªAªSTEPPERªMOTORª ,ST?ASM A simple full-step program is shown in Listing 6.11. 4HE ÚRST LINE PLACES THE LOWEST FRE- quency half of oscillator register OSCL into register AUX0, prior to using this value to drive the stepper motor. (It is also possible to use register OSCL directly to drive the stepper motor, but the speed of operation is then consider- ably faster.) A more sophisticated control pro- gram is shown in Listing 6.12, with the output of an up/down counter used to provide forward and reverse control, combined with position con- trol based on the running count value. Hardware connections to inputs and outputs are shown in Fig.6.3. (Users of Proteus VSM may wish to add a Watch window variable for include 16F627.PLC ; Defines PLC instructions ld PORTA, 0 ; Read Port A bit 0 (Count do n input) or PORTA,1 ; OR ith Port A bit 1 (Count up input) and OSCL,1 ; Clock input to up do n counter ctr ud 0, d'7', PORTA, 1, PORTA, 2 ; Up do n counter 0, final value 7 ; Direction Port A bit 1 ; Reset Port A bit 2 ; Up do n counter orking register CUD0 hstep CUD0, PORTB ; Send half step se uence to bits 0 3 of Port B endp ; Marks end of PLC program ,ISTINGªªI DIRECTIONALªCONTROLªOFªAªSTEPPERªMOTORª ,ST?ASM register CUD0 (address 0x5C), which will allow the desired position of the stepper motor to be observed in real time.) $IGITALªPOSITIONªMEASUREMENTª 'RAYªCODE The example of Listing 6.12 illustrat- ed the possibility of open loop position control of a stepper motor. However, stepper motors can easily slip due to their low output torque, so the desired position and the actual position are not always the same thing. The only way to really be sure of the actual shaft posi- tion is to measure it, and Gray code is ideally suited to this purpose. Fig.6.4 shows a 3-bit Gray-coded disc, which may be used to measure rotary shaft position, when combined
  • 689. 4 Everyday Practical Electronics, April 2010 Teach-In 2010 generated by electronic toys, displays, OR EVEN SIMPLE TRAFÚC LIGHTS (OWEVER
  • 690. THE SEQUENCER METHOD IS LESS SUITED TO CONTROL ORIENTED SYSTEMS
  • 691. WHERE THE EXACT TIMING MAY BE IMPOS SIBLE TO PREDICT IN ADVANCE
  • 692. OR WHERE PROGRESSION FROM ONE OUTPUT STATE TO THE NEXT IS BASED ON THE OCCURRENCE OF AN EVENT
  • 693. WHICH IS NOT NECESSARILY A SIMPLE TIME DELAY )N THIS CASE
  • 694. A ÚNITE STATE MACHINE MAY BE THE BEST CHOICE
  • 695. AS WILL BE ILLUSTRATED HERE !S ITS NAME SUGGESTS
  • 696. A ÚNITE STATE MACHINE IS BASED ON THE CONCEPT OF STEPPING FROM ONE lSTATEm TO ANOTHER
  • 697. WITH EACH TRANSITION BEING TRIGGERED BY AN lEVENTm
  • 701. OR AN EXTERNALLY GENERATED SIGNAL INITE STATE MACHINES ARE COMMONLY DESIGNED IN GRAPHICAL OR TABULAR FORM
  • 702. BY USING EITHER STATE DIAGRAMS
  • 704. A STATE TABLE FOR A SIMPLE TRAFÚC LIGHT SEQUENCE IS SHOWN IN 4ABLE !S YOU MIGHT HAVE GUESSED
  • 705. WE CAN EASILY ADD SUCH A CAPABILITY BY CREAT ING A NEW lSTATEm MACRO
  • 706. AS ILLUSTRATED BY ,ISTING 4HE MACRO ACCEPTS FOUR PARAMETERS WHICH ARE q JUST TO MAKE IT EASY q TAKEN DIRECTLY FROM OUR STATE TABLE 4HESE ARE THE CURRENT STATE NUMBER
  • 709. AND ÚNALLY THE ACTION TO BE PERFORMED 4HE TRANSITION CONDITION IS TYPICALLY EITHER AN INPUT BIT
  • 711. WHICH Fig.6.3. Using an up/down counter to control the position of a stepper motor MUST BE SET TO TO CAUSE A TRANSITION TO THE NEXT STATE
  • 712. OR A TIMER STATUS BIT
  • 713. WHICH WILL BECOME SET ON COMPLETION OF AN ASSOCIATED TIME DELAY )N ORDER TO KEEP THE PROGRAM REASONABLY STRUC TURED
  • 714. THE ÚNAL PARAMETER IS GIVEN AS A SUBROUTINENAME
  • 715. WHICHISCALLEDWHEN THE STATE IS ACTIVE 4HE VALUE OF THE CURRENT STATE IS AVAIL ABLE FROM THE 34!4% REGISTER
  • 716. WHICH IS SPECIÚED IN UPPER CASE
  • 717. TO DISTINGUISH IT FROM THE lSTATEm MACRO NAME LOWER CASE 4HE SYSTEM INITIALLY POWERS UP IN STATE
  • 718. SO AN AUTOMATIC TRANSITION IS TYPICALLY MADE FROM THE POWER UP STATE TO THE ÚRST ACTUAL STEP IN THE SEQUENCE 4HE ACTUAL CODING OF OUR TRAFÚC LIGHT ÚNITE STATE MACHINE IS SHOWN IN ,ISTING
  • 719. THIS TIME WRITTEN FOR THE MICROCONTROLLER 4HE PROGRAM IS LOGI CALLY DIVIDED INTO THREE SECTIONS
  • 720. WITH THE ÚRST BEING THE STATE TABLE include 16F627.PLC ; Defines PLC instructions gra 2bin PORTA, PORTB ; Read a 4 bit Gra coded disc connected to ; Port A, outputting the position to Port B endp ; Marks end of PLC program Listing 6.13. Measuring shaft position with a Gray coded disc (Lst6_13.asm) Fig.6.4. Using a Gray-coded disc to measure rotary position nt tat t tat an ition nt ut ut 0 1 utomatic (power up state) ll outputs off 1 2 2 second delay ed 2 3 1 second delay ed mber 3 4 10 second delay Green 4 1 1 second delay mber 4ABLEªª!ªSTATEªTABLEªREPRESENTINGªAªSIMPLEªTRAFlCªLIGHTªSEQUENCE
  • 721. Everyday Practical Electronics, April 2010 Teach-In 2010 state macro state arg1, state arg2, state arg3, state arg4, state arg5 movl state arg1 ; Move state number to W or f STATE, W ; OR ith current state ( ero result ; if the are e ual) btfss STATUS, ; Check if state arg1 current state goto st v(state arg1) ; o, so goto end call state arg5 ; es, so call subroutine btfss state arg3, state arg4 ; check if state transition condition ; is true (1) goto st v(state arg1) ; o so goto end movl state arg2 ; Cop ne t state to STATE register mov f STATE st v(state arg1) endm ; End of Finite state machine macro ,ISTINGªª4HEªCUSTOMª@STATE ªMACROªUSEDªBYªTHEªlNITEªSTATEªMACHINE itself. Notice that a LOGIC, 1 value causes an auto- matic transition from state 0tostate1,withtimedelay status bits causing all sub- sequent state transitions. The second section uses ‘eqi’ comparison opera- tors to enable each timer once the STATE register is equal to the tested value. The timer output bit be- comes set on completion of the active time delay, causing a transition to the next state, at which point the next timer is enabled, and the previous timer is cleared. 4HE THIRD AND ÚNAL SEC- tion contains the subrou- TINE DEÚNITIONS
  • 722. WHICH IN THIS CASE OUTPUT THE TRAFÚC light values to Port B. !NDªlNALLY The main aims of this series have been to make microcontroller program- ming accessible to the widest possible audience, and to make it a rewarding experience in the process. I hope I have encouraged you to experiment and to learn more about micro- electronics. The ladder logic soft- ware used in the series has been placed into the public domain by the author, so you are free to USE IT AS YOU SEE ÚT
  • 723. AND to extend it to suit new applications. Although it has been carefully tested, likeanycomplexprogram, you should be aware that the software may contain undetected faults. With this in mind, you should always test your programs carefully, and make sure they perform as required! I trust that you have enjoyed working along with this series as much as I have in writing it, and I also hope to contribute further articles and con- struction projects to EPE in the future. EPE ; Traffic Lights Finite State Machine include 16F88 L.PLC ; Defines PLC instructions ; First section Define state se uence state 0, 1, LOGIC, 1, ERO ; Automatic transition from state 0 1 ; after po er up state 1, 2, TIML, 0, O E ; Red state 2, 3, TIML, 1, TWO ; Red Amber state 3, 4, TIML, 2, THREE ; Green state 4, 1, TIML, 3, FOUR ; Amber (then back to Red) ; Second Section State transitions e i STATE, 1 ; 2 second timeout state 1 2 timl 0, 2 e i STATE, 2 ; 1 second timeout state 2 3 timl 1, 1 e i STATE, 3 ; 10 second timeout state 3 4 timl 2, d'10' e i STATE, 4 ; 1 second timeout state 4 1 timl 3, 1 ; Third section Actions performed subdef ERO ; All lights off after po er up puti b'00000000', PORTB return subdef O E ; Displa Red puti b'00000001', PORTB return subdef TWO ; Displa Red Amber puti b'00000011', PORTB return subdef THREE ; Displa Green puti b'00000100', PORTB return subdef FOUR ; Displa Amber puti b'00000010', PORTB return endp ; End of PLC program Listing 6.1 . A simple traffic light finite state machine.,ISTINGªª!ªSIMPLEªTRAFlCªLIGHTªlNITEªSTATEªMACHINEª ,ST?ASM
  • 724. 50 http://www.handsontec.com www.handsontec.com LCD+Keyboard Shield 10-Segments LED Bar Display Ethernet Module Arduino Uno MicroSD Breakout Board WiFi Module 20x4 LCD Display Module Stepper Motor Driver PWM Motor Speed Controller Breakout Board Modules Integrated Circuits Discrete Parts Assembled Kits Connectors