Teach-In 2010
TEACH-IN 2010
LADDER LOGIC PROGRAMMING FOR THE PIC MICRO Part 1: Getting Started – Working with Inputs and Outputs By Walter Ditch
T
HIS
! " ! ! #
"
" $ ! %
" " & ' $ ( '
$ "
# " $ #
50
! %
'
% ' ! % " %" # " "
"
" ) " $
* s ) " $ + , s # s % + ., s ) $ " % ( %"
" " $ % " # " "
" +0121345 134( 0121365136( 012176 01266
012664, " 5 * 0 8 96:76
; <
" " 3 #. 3 = " ; <
" . +www.microchipdirect.com, > . . 8 > . ? = <
" Everyday Practical Electronics +EPE, @ ) 7 8). ! " ; +www.labcenter.co.uk, A
" " " ) " " ' " " B
Comparing PLCs and microcontrollers # " !
Everyday Practical Electronics, November 2009
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 being connected via opto-isolators, and digital output types including transistor, thyristor, triac and relay. This allows the PLC to directly control high power devices, such as motors, pneumatic actuators and the like. A typical
This added complexity is avoided here by the pre-configuration of default settings, such as port directions, in the supplied PLC header +2 012134 ( " input, while Port B is an output.) You can, of course, change these settings, simply by editing the relevant section
"
Fig.1.1. A typical industrial PLC commercially available PLC is shown in Fig.1.1, with input connections shown at the top and outputs at the bottom. While the I/O connections of a microcontroller 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 memory (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, such as EEPROM, is retained.) The allocation of connections as inputs or outputs is, of course, pre-determined by the PLC manufacturer, since this is a pre-requisite for the connection of specialised interface circuitry. Not so in the microcontroller world, where the assembly language programmer normally has to decide on port directions, settings, prior to actually getting the microcontroller to do something useful.
designed to work straight out of the " tion â&#x20AC;&#x201C; just like a real PLC. So, having established that PLCs and microcontrollers have a lot in
implement combinational and sequential logic functions in electrical control circuits, and it is in part this electrical basis which makes it easy for electrical engineers to understand â&#x20AC;&#x201C; even those without a computing background. Consider, for example, a simple electrical circuit consisting of a switch and a lamp, and also its representation 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 â&#x20AC;&#x2DC;rungsâ&#x20AC;&#x2122;. (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 connect 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 operated 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 represented 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.
Fig.1.2. A simple switch and lamp circuit (left) and its equivalent ladder diagram (right) common, letâ&#x20AC;&#x2122;s turn our attention to lad offer in terms of software development.
Ladder diagrams and ladder logic Ladder logic owes its origin to the use of switches and relays to
Everyday Practical Electronics, November 2009
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 created by converting each input contact
51
Teach-In 2010 ld out
SWITCH LAMP
required software, which will then enable us to create and test an executable program.
; Read state of Switch ; Output to Lamp
Listing 1.1. A notional section of a PLC program based on the circuit and ladder diagram of Fig.1.2 and output coil of the systemâ&#x20AC;&#x2122;s ladder diagram into a series of equivalent program statements. Execution of the program is then a continuously operating sequence of: s Reading inputs s Performing logic-based calculations s Controlling outputs This repeating process is known as the scan cycle, and is shown graphically 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 consists of a continuously operating program loop (a repeating scan cycle), 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 " frequency. Slightly less obviously: 3. An externally applied input signal " time to guarantee it being â&#x20AC;&#x2DC;seenâ&#x20AC;&#x2122; by the input phase of the scanning loop. 4. The average time taken to react to a changing input is related 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 calculations â&#x20AC;&#x2DC;ripple-thoughâ&#x20AC;&#x2122;. In practice, you der logic solutions are Fig.1.3. The repeating scan cycle of a PLC executing suitable in the majority a ladder logic program of logic-based control statement forces program execution to scenarios, since the computer is typi " cally operating at much higher speed rung (Step 3), causing the program to than the system being controlled. run continuously. This program might Now that the basic principles of be coded using statements such as ladder logic programming have been those given in Listing 1.2. covered, the next step is to obtain the ld out
SWITCH_A LAMP_A
; Read state of Switch A ; Output to Lamp A
ld out
SWITCH_B LAMP_B
; Read state of Switch 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
52
Obtaining the software The ladder logic software is designed to work with the MPLAB Integrated Development Environment (IDE), which is freely available for download from the Microchip website (www.microchip. com), or on CD-Rom . All that is required is to include a link to the appropriate " 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: s PIC16F627/PIC16F627A (head &012134 ! ', s PIC16F628/PIC16F628A (head &012136 ! ', s 012176 + &012176 PLCâ&#x20AC;&#x2122;) s PIC16F88 (header files â&#x20AC;&#x2DC;16F88_L.PLCâ&#x20AC;&#x2122; and â&#x20AC;&#x2DC;16F88_H.PLCâ&#x20AC;&#x2122; offer low voltage and high voltage program versions respectively) s 012664 + &012664 PLCâ&#x20AC;&#x2122;) are all 18-pin ICs, differing mainly in $ ~ %" memory, static RAM, or EEPROMbased 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 process 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.
Everyday Practical Electronics, November 2009
Teach-In 2010 Device
Program (kWords)
RAM (bytes)
EEPROM (bytes)
Max I/O (bits)
Other Features
PIC16F627
1
224
128
16
2 comparators
Assembling and executing simple PLC-style programs
In this section you will see just how easy it is to create and assemble simple programs and PIC16F88 4 368 256 16 2 comparators then run them on a variety of 7-channel ADC different PIC-based systems. I PIC16F887 8 368 256 35 2 comparators recommend that you try these 14-channel ADC activities out for yourself, if at all possible. Table 1.1. Major features of supported PIC microcontrollers Begin by extracting the entire  Device Inputs Outputs Other Features venient folder and then use the PIC16F627 / 628 Port A (5 bits) Port B (8 bits) Comparators disabled, pull-ups disabled MPLAB IDEâ&#x20AC;&#x2122;s File > Open menu / 648 4MHz external crystal oscillator selected
&! 0Â&#x201A;> Timer 0 configured for use by PLC software asmâ&#x20AC;&#x2122;, the content of which is MCLR enabled, Watchdog timer enabled ! 0 > PIC16F88 Port A (5 bits) Port B (8 bits) Comparators disabled, pull-ups disabled Â&#x192; 4MHz external crystal oscillator selected ally identical to the code snippet Timer 0 configured for use by PLC software ! 0 0 MCLR enabled, Watchdog timer enabled ADC disabled " " 012664 microcontroller. It is suitable PIC16F887 Port A (8 bits) Port C (8 bits) Comparators disabled, pull-ups disabled Port B (8 bits) Port D (8 bits) 4MHz internal oscillator selected for use either with the PICkit 2 Port E (4 bits) Timer 0 configured for use by PLC software Debug Express board, or with MCLR disabled, Watchdog timer enabled Proteus VSM electronic simuADC disabled lation software. (Note that the PICkit 2 board has a single input " ) 0 Filename Description bit of Port B, plus eight LEDs connected to Port D â&#x20AC;&#x201C; which 16F627.PLC PLC header file for the PIC16F627/627A microcontroller explains the choice of inputs
! 0 > 16F628.PLC PLC header file for the PIC16F628/628A microcontroller Having displayed the source 16F648.PLC PLC header file for the PIC16F648A microcontroller + , . !(< step is to assemble it, in order PLC header file for the PIC16F88 microcontroller â&#x20AC;&#x201C; low voltage 16F88_L.PLC to create a machine code (.hex) programming enabled on pin RB3 " PLC header file for the PIC16F88 microcontroller â&#x20AC;&#x201C; high voltage 16F88_H.PLC loaded and programmed. The programming enabled, pin RB3 available for general I/O
16F887.PLC PLC header file for the PIC16F887 microcontroller quired microcontroller type by selecting the
PIC16F627.DSN Proteus VSM simulation â&#x20AC;&#x201C; PIC16F627A based Digital I/O Board Device menu option, and then PIC16F88.DSN Proteus VSM simulation â&#x20AC;&#x201C; PIC16F88 based Digital I/O Board selecting the PIC16F887 from PIC16F887.DSN Proteus VSM simulation â&#x20AC;&#x201C; PIC16F887A based Digital I/O Board the Device drop-down list. Next click on the blue title bar of the Lst1_3.asm Source code file for Listing 1.3 Lst1_4.asm Source code file for Listing 1.4 highlighted and then assemble Lst1_5.asm " Project Source code file for Listing 1.5 > Quickbuild Lst1_3.asm menu Lst1_6.asm Source code file for Listing 1.6 option. If everything has gone ~ Table 1.3. File contents of â&#x20AC;&#x2DC;PLC1.zipâ&#x20AC;&#x2122;
" &< include "16F887.PLC" ; Defines PLC instructions Succeededâ&#x20AC;&#x2122; message, displayed in the Build tab of the Output window. ld PORTB, 0 ; Read Port B bit 0 The MPLAB IDE has now done its out PORTD, 0 ; Output to Port D bit 0 Â&#x2020; " ! 0Â&#x201A;> been created in the same directory endp ; End of PLC program
" Listing 1.3. Reading a switch and outputting to an LED (Lst1_3.asm) programmed. PIC16F628
2
224
128
16
2 comparators
PIC16F648
4
256
256
16
2 comparators
Everyday Practical Electronics, November 2009
53
Teach-In 2010 Syntax
Function
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)
Ladder Diagram Symbol
Table 1.4. Bit input/output commands
under the VDD PICkit 2 label at the upper right. Pressing Switch 1 will now cause the LED connected 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. Examining 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
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 + ,
54
created earlier. Next, click the Write button to program the PIC16F887 microcontroller. 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
pressed. The required logic of our program may be easily restored by replacing the â&#x20AC;&#x2DC;ldâ&#x20AC;&#x2122; instruction with its negative logic â&#x20AC;&#x2DC;ld_notâ&#x20AC;&#x2122; 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
Teach-In 2010 (out_not) is available. Thus, we can create a logical inversion either by using â&#x20AC;&#x2DC;ld_notâ&#x20AC;&#x2122; followed by â&#x20AC;&#x2DC;outâ&#x20AC;&#x2122;, or â&#x20AC;&#x2DC;ldâ&#x20AC;&#x2122; followed by â&#x20AC;&#x2DC;out_notâ&#x20AC;&#x2122;. 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 Fig.1.4.
Controlling multiple inputs and outputs To take a slightly more complex example, suppose we wanted to control several inputs and outputs. This could be achieved as illustrated by Listing 1.4, shown for a PIC16F627based system. Assuming you have a suitable PIC programmer and experimentation board, such as the Velleman K8048, the . !(< =; + " ing of course to set the device type to either the PIC16F627 or PIC16F627A, as appropriate). Next, connect the
include "16F627.PLC"
; Defines PLC instructions
ld out
PORTA, 0 PORTB, 0
; Read Port A bit 0 ; Output to Port B bit 0
ld out
PORTA, 1 PORTB, 1
; Read Port A bit 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)
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 " &! 0Â&#x201A;> ' Close the dialog and then click the Play button at the lower left of the Proteus window to run the simulation. Youâ&#x20AC;&#x2122;ll then be able to click on the input connected to bit 0 of Port B, which should cause the corresponding bit of Port D to change (as illustrated by Fig.1.4).
programmer to your PC via the supplied serial cable and then download and execute the program. When the program is executed, pressing a switch " 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 â&#x20AC;&#x2DC;PIC16F627.DSNâ&#x20AC;&#x2122; 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 â&#x20AC;&#x2DC;black boxâ&#x20AC;&#x2122; to the PIC16F887 PCB. When not being used to download programs, the Logic tool allows inputs RE3, RB7
include "16F887.PLC"
; Defines PLC instructions
ld out
PORTE, 3 PORTD, 3
; Read Port E bit 3 (ICSP pin 1) ; Output to Port D bit 3
ld out
PORTB, 7 PORTD, 2
; Read Port B bit 7 (ICSP pin 4) ; Output to Port D bit 2
ld out
PORTB, 6 PORTD, 1
; Read Port B bit 6 (ICSP pin 5) ; Output to Port D bit 1
ld_not PORTB, 0 out PORTD, 0
; Read Port B bit 0 inverted (SW1) ; 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)
Fig.1.5. The output produced by Listing 1.4, running on a Velleman K8048 board
Everyday Practical Electronics, November 2009
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 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
55
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 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 #
at in this installment is the Version 3 PICmicro MCU Development board, as shown in Fig.1.7. This comprehensive board is available from the EPE Readersâ&#x20AC;&#x2122; 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 four times faster than the 4MHz default used by the PLC software. If you are PLC software, Iâ&#x20AC;&#x2122;d recommend replacing this with a 4MHz crystal â&#x20AC;&#x201C; which will ensure that time-dependent programs covered in later parts of the series run at the correct speed. + !
56
" 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 accommodate 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 â&#x20AC;&#x2DC;low ' 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 microcontroller.) # are provided, supporting low voltage or high voltage programming (â&#x20AC;&#x2DC;PIC16F88_L.PLCâ&#x20AC;&#x2122; and â&#x20AC;&#x2DC;PIC16F88_H. PLCâ&#x20AC;&#x2122; 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. # " the normal way, by using the MPLAB IDE. A supplied PIC programming
+ ,
" A 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 â&#x20AC;&#x201C; see Fig.1.4 and associated text for details.
Troubleshooting tips While operation should be mostly trouble free, the following troubleshooting tips will help you to resolve
$ " * 1. The MPASM assembler used by the MPLAB IDE is case sensitive and it is a requirement that all PLC commands should be entered in lower case, and any parameters # listing for typographical errors.
Fig.1.7. Running a simple bit input/output program on the PICmicro MCU development board
Everyday Practical Electronics, November 2009
Teach-In 2010 include "16F88_L.PLC" ; Defines PLC instructions ; (Low voltage programming version ; with RB3 used as the LVP pin) ld out
PORTA, 0 PORTB, 2
; Read Port A bit 0 ; Output to Port B bit 2
ld_not out
PORTA, 1 PORTB, 5
; Read Port A bit 1 (inverted) ; Output to Port B bit 5
ld PORTA, 2 out_not PORTB, 6
; Read Port A bit 2 ; Output to Port B bit 6 (inverted)
ld_not PORTA, 3 out_not PORTB, 7
; Read Port A bit 3 (inverted) ; Output to Port B bit 7 (inverted)
endp
; End of PLC program
Listing 1.6. Controlling normal and inverted signals with the PIC16F88 (Lst1_6.asm) 2. Ensure that the relevant include
"
" " " > . !(< =; " 7 # " "
+ ,
+ , Â&#x2039; # ) . (). " Â&#x152; 13
1 " Â&#x152; "
" " 4 2 " + '
,
Final thoughts ' <
"
' "
' "
" "
# " " " " <
(Â?= Â&#x192;@ ;Â&#x192;@ + %Â&#x192;@, ' $ " $
' " Â&#x2020;
" " " 2
5 !;=
COOL COMPONENTS
Established in 2004, Cool Components supplies interesting, useful and powerful electronic components at excellent prices. Arduino Boards + Shields
Plug-In Media Player Modules
Fast Update GPS Modules
Serial Controlled OLED Displays
Olimex PIC, AVR + ARM Boards
Iron-On PCB Fabrication
Serial Bluetooth Adaptors
Servos + Servo Controllers
We work with manufacturers including Sparkfun, Olimex, Arduino and many others to bring you the best from the cutting edge of new electronic technology.
WWW.COOLCOMPONENTS.CO.UK Follow product news on: twitter.com/coolcomponents
0871 288 7685 Everyday Practical Electronics, November 2009
57
TEACH-IN 2010
LADDER LOGIC PROGRAMMING FOR THE PIC MICRO Part 2: Working with Combinational and Sequential Logic By Walter Ditch
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 executable machine code programs for the PIC micro by using commands such as: â&#x20AC;&#x2DC;ldâ&#x20AC;&#x2122; (read an input bit); â&#x20AC;&#x2DC;outâ&#x20AC;&#x2122; (send result to an output bit); plus their negative logic counterparts â&#x20AC;&#x2DC;ld_notâ&#x20AC;&#x2122; and â&#x20AC;&#x2DC;out_notâ&#x20AC;&#x2122; respectively. We saw that a PLC-style program executes by following a repeating cycle of reading inputs, performing calculations and controlling outputs, known as the scan cycle. The PLC software itself consisted of number of common PIC microcontrollers, including the 16F627A, 16F628A, 16F648, PIC16F88 and PIC16F887. By including the appropriate header were able to use the freely available
MPLAB Integrated Development Environment (IDE) to assemble our ladder logic programs into executable machine code programs, which could then be downloaded to a variety of commonly available PIC development boards. Hardware demonstrated in Part 1 included the Velleman K8048 board, Microchip Directâ&#x20AC;&#x2122;s PICkit 2 Debug Express board, Matrix Multimediaâ&#x20AC;&#x2122;s PICmicro MCU Development board, plus Proteus VSM electronic circuit simulation software from Labcenter Electronics.
Moving on In this second instalment, weâ&#x20AC;&#x2122;ll continue our tour of ladder logic by looking at: s Creation of repeating waveforms by using â&#x20AC;&#x2DC;oscillatorsâ&#x20AC;&#x2122; s Combining inputs using simple combinational logic operators (AND and OR) s Availability of other logical functions (NOT, NAND, NOR, XOR, and XNOR) s Using internal memory locations (auxiliary relays) to hold intermediate results and to solve complex logic networks s Creation of latched (stored) outputs to capture momentary input signals, including the provision of set and reset inputs outputs.
Everyday Practical Electronics, December 2009
Weâ&#x20AC;&#x2122;ll then use these concepts to develop 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 â&#x20AC;&#x2DC;system armedâ&#x20AC;&#x2122; 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â&#x20AC;&#x2122;s internal operation in a little more detail. This knowledge will prove useful when debugging your 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/ from Part 1 â&#x20AC;&#x201C; particularly the various !"# $ " % Also, make sure you have installed
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 development 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.
Listing 2.1. Creating a 2Hz pulsed output (Lst2_1.asm)
Waveform production & ' this section explains how the oscillator 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 software assumes an oscillator frequency of 4MHz. This signal is used to generate a number of other waveforms, includ-
26&+ +LJK )UHTXHQF\ 2VFLOODWRUV
26&/ /RZ )UHTXHQF\ 2VFLOODWRUV
%LW SRVLWLRQ
3HULRGLF 7LPH )UHTXHQF\
%LW 3RVLWLRQ
3HULRGLF 7LPH )UHTXHQF\
0 1 3 6 7
Č?
0 1 3 6 7
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 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 wide range of devices commonly available. You can easily adapt any of the programs in this series to work with other supported PIC mi $ * line to load the appropriate header 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â&#x20AC;&#x2122;ll see how oscillators may be usefully combined with simple Boolean logic functions, predetermined condition is true.
ing four non-overlapping (quadrature) 1MHz waveforms (Q1, Q2, Q3, Q4) and also a basic 1MHz square waveform, appropriate PIC data sheet. The PLC software uses this 1MHz square wave signal to continuously increment an 8-bit timer register (Timer0, also referred 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 repeatedly 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 increment 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 directly in user programs. However, it
is important to also be aware that they are also used internally as time references by several other PLC commands yet to be considered, including timers and PWM (pulse width modulated) outputs. For this reason, the use of a different clock frequency to the assumed value of 4MHz is likely to cause timecritical programs to run correspondingly 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 creates 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 arrangement, with one or more closed contacts creating a route for the power 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: s â&#x20AC;&#x2DC;LAMP = A AND Bâ&#x20AC;&#x2122;, (switches in series), and s â&#x20AC;&#x2DC;LAMP = A OR Bâ&#x20AC;&#x2122; (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 operators in order to increase the number of inputs. Also, note that NAND or NOR operators may easily be created by replacing the â&#x20AC;&#x2DC;outâ&#x20AC;&#x2122; instruction with its negative logic equivalent â&#x20AC;&#x2DC;out_notâ&#x20AC;&#x2122;. A simple application which combines oscillators with logic functions
Everyday Practical Electronics, December 2009
be â&#x20AC;&#x2DC;seenâ&#x20AC;&#x2122; by the PLC software until its next pass through the scan cycle.)
Other logical operations
Fig.2.1. Switch-based and ladder logic versions of Boolean logic functions
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 logical 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 â&#x20AC;&#x2DC;The output is true if (A is true and B is false) OR (A is false and B is true)â&#x20AC;&#x2122;. 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 normallyopen or normally-closed input contacts, is shown in Table 2.2.
Using internal memory to hold intermediate results
Listing 2.2. Simple logical functions (Lst2_2.asm) would be to enable a pulsed output only when a key is pressed. A simple example is shown in Listing 2.3 â&#x20AC;&#x201C; 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 periodic time of 530Ps, obtained using the
1
Listing 2.3. Generating waveforms using oscillators and simple logic (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 the changing oscillator bit will not
Everyday Practical Electronics, December 2009
While the above methods may be used to solve simple Boolean logic circuits, more complex logical problems may require an alternative technique. Consider for example the ladder diagram of Fig.2.3. The trick in this case is to use standard logical operators to solve each horizontal â&#x20AC;&#x2DC;rungâ&#x20AC;&#x2122; of the ladder 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 AUX0 to hold the intermediate result cally combined with the result from output on bit 0 of Port B. You should now have a good understanding of the â&#x20AC;&#x2DC;single bitâ&#x20AC;&#x2122; combinational logic capabilities of the PLC software. For future reference, it is worth mentioning that a number of â&#x20AC;&#x2DC;byte orientedâ&#x20AC;&#x2122; logical commands are also available, which will be discussed later in the series. The next section demonstrates how the application of feedback from output to input may be used to create a simple latch, which is, of course, the basis of sequential logic.
Fig.2.3. A complex logic circuit requiring a two-stage approach
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)
2.6, which is suitable for use with the PIC16F88 microcontroller. The PLC software also includes a dedicated latch command, which provides 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 +9&<< microcontroller While the use of the latch command does reduce the source code by a couple of lines, the actual machine code generated is identical in either case. Which approach to use is therefore a matter of personal preference.
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 momentary 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 output 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 Reset 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
Table 2.2. Single-bit Boolean logic commands
Everyday Practical Electronics, December 2009
Fig.2.4. Creation of a latched output by using standard ladder logic commands
Fig.2.5. Using a dedicated latch, rather than separate ladder logic commands
Fig.2.6. Ladder diagram for a simple alarm with three sensors
Building simple systems
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 access to this software), or by using the
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 >?@ !GJZ[ 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 > \ ] Possible enhancements would include a pulsed alarm output, and the provision of a â&#x20AC;&#x2DC;system armedâ&#x20AC;&#x2122; indicator, 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.
To bring together some of the concepts discussed, letâ&#x20AC;&#x2122;s begin by creating >?@ be found in the â&#x20AC;&#x2DC;system armedâ&#x20AC;&#x2122; output of an immobiliser circuit. Weâ&#x20AC;&#x2122;ll use a latch to arm or disarm the circuit,
Listing 2.5. Using internal relays to solve complex logic circuits (Lst2_5.asm) instance to an auxiliary relay. When enabled, the output will be made to ^}@ +~% tor signal, and the pulse width will ^}@ several higher frequency oscillator > \ < !"#+9&<< microcontroller. " > \ < ! [ 9 Set and Reset inputs, with the latch output being sent initially to auxiliary relay AUX bit 0. The latched signal +~% ^}@ with low frequency oscillator register GÂ&#x20AC;#> Â >?@ ! @ Â&#x201A; Z ^}@
!"#Â&#x192; \ @ ?| " latter case, recall from Part 1 of the se !"#Â&#x192; \ > Tool to set and reset the bistable. Pin 5 ! [ 9 Â&#x20AC; ! Â&#x201E; {! [ acts as Reset. (Slightly confusingly, > Z are used to drive the corresponding !"# G | 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 triggered, and remain in this state until the alarm is manually cancelled. The ladder diagram for the alarm is shown in Fig.2.6.
Everyday Practical Electronics, December 2009
Internal operation of the PLC software A more detailed understanding of !># software is useful at this stage, not only for curiosityâ&#x20AC;&#x2122;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. ^ `!>^[ " @ ? {"@? |
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)
Listing 2.9. A simple alarm program (Lst2_9.asm)
executable machine code program. This powerful software has a macro facility, which allows a text string to be automatically replaced by a section of Â&#x2020; | Z 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 assembler, prior to conversion to machine code. Consider the implementation of the â&#x20AC;&#x2DC;ldâ&#x20AC;&#x2122; instruction as an example, as shown in Fig.2.7. As can be seen, the â&#x20AC;&#x2DC;ldâ&#x20AC;&#x2122; macro accepts two arguments, 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 Notice that the above section of code results in the logic level present on the input port being placed of the (LSB) Working register (W), which is actually a general feature of the PLC software. The corresponding â&#x20AC;&#x2DC;outâ&#x20AC;&#x2122; instruction, for example, simply takes >Â&#x20AC;[ of the W register and sends it to the selected output by examining the appro | editor such as Windows Notepad. An interesting observation at this stage relates to the â&#x20AC;&#x2DC;endpâ&#x20AC;&#x2122; or end program PLC instruction, which is of course, yet another macro. An examination of the header a jump instruction, which forces the PLC program to run
Everyday Practical Electronics, December 2009
Fig.2.7. Macro substitution, as used by the PLC softwareâ&#x20AC;&#x2122;s â&#x20AC;&#x2DC;ldâ&#x20AC;&#x2122; instruction
Summary and next steps
continuously â&#x20AC;&#x201C; this being the basis of the PLCâ&#x20AC;&#x2122;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 ess, rather than reduction in code size.
This second part of the series began outputs of a wide range of frequencies by using oscillator bits. We also looked at single-bit combinational logic functions, including AND, OR and Exclusive-OR, and discussed the potential incorporation of inverted inputs and outputs (NAND and NOR for example). More
â&#x20AC;&#x153;
Atlas DCA - Model DCA55
â&#x20AC;&#x153;
Christmas gift ideas...
...and if you change your mind after Christmas then no worries, you can have an exchange or refund without question.
electronic design ltd
The New Atlas ESR Plus, Model ESR70 ÂŁ89
This new model of the famous Atlas ESR offers all the great features of the ESR60 but with extended measurement range and audible alerts. This is the Atlas ESR Plus!
VAT inc
NEW MODEL
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.
Atlas SCR - Model SCR100
Atlas LCR - Model LCR40
Atlas ESR - Model ESR60
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.
Passive component analyser. Automatically identify and measure inductors, capacitors and resistors. Auto frequency selection. Removable probes.
Special Offer!
1uH - 10H 1pF - 10,000uF 1 Ohms - 2M
Reduced Price! was ÂŁ97
ÂŁ79 inc VAT
ÂŁ79 inc VAT
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 ing â&#x20AC;&#x2DC;system armedâ&#x20AC;&#x2122; warning light and an alarm circuit. We also discussed the macro substitution method used by the PLC software, program will be considerably larger than the source code would suggest. Hopefully, the power of ladder logic as a design tool has been in part demonstrated by the fact that a simple burglar alarm system could be created in ap | (as seen in Listing 2.9), and without any need to delve into the internal architecture of the chosen PIC microcontroller. The next part of the series will continue the tour of the sequential logic capabilities of the PLC software, by looking at timers and shift registers. The use of timers will enable an action to be performed for a given period of time, while shift registers will make it easy to create simple running light displays.
Measure capacitance and ESR! Capacitance from 1uF to 22,000uF ESR from 0.01 ohms to 20 ohms Battery included + Gold plated croc clips
nc 5i
The famous Peak Atlas, now with ÂŁ55 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. Darlingtons MOSFETs Diodes Transistors LEDs and more...
inc
VAT
Look! New Probes.
Atlas Star Pack (LCR/DCA)
Ideal Gift and Money Saving too! This pack saves you ÂŁ20 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â&#x20AC;&#x2122;re ready to go!
ÂŁ125 inc
VAT
T VA
ÂŁ7
was ÂŁ87
Peak Electronic Design Ltd, West Road House, West Road, Please add ÂŁ2.75 p&p per order. Prices include UK VAT. See website for overseas prices. Buxton, Derbyshire, SK17 6HF. tel. 01298 70012 www.peakelec.co.uk sales@peakelec.co.uk Special Offer prices for limited period or while stocks last.
Everyday Practical Electronics, December 2009
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…
Teach-In 2010
TEACH-IN 2010
LADDER LOGIC PROGRAMMING FOR THE PIC MICRO Part 3: Timers and Shift Registers By Walter Ditch
P
ART three of this series on ladder logic (PLC-style) programming 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 delay timer) or performing a task for a given period of time (a pulsed timer output). Timer applications 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â&#x20AC;&#x2122;s use of internal memory (registers). This knowledge may be required when writing programs, and often proves useful when debugging ladder logic software applications. For
42
example, the internal state of a timer or counter is normally only visible to the
value is also available as a byte value â&#x20AC;&#x201C; if you know where to look. In passing, a few of the PLC softwareâ&#x20AC;&#x2122;s byte processing commands will be introduced, these being used to simplify 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â&#x20AC;&#x2122;ll also make use of a byte comparison command to simplify the coding of a rudimentary â&#x20AC;&#x2DC;KnightRiderâ&#x20AC;&#x2122; style display. Coverage of the sequential logic capabilities of the PLC software will continue next month with the introduction of counters and pulse-widthmodulated (PWM) signals. As discussed previously, all program listings for this article are available from the Library > Project Code section of the Everyday Practical Electronics website (www.epemag. com). It is suggested that you copy into a single folder on your computer, which will ensure you have 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 actually 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 ! input and output port assignments to suit those available with the chosen microcontroller.
Using low speed timers So far, most of the programs considered have either produced an output instant (combinational logic), or have latched a momentary input signal (simple sequential logic). This has allowed the development of some useful applications, 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. ! " # " " a timer with a simple alarm circuit. The PLC software provides up to 16 built-in timers, eight of which are â&#x20AC;&#x2DC;low speedâ&#x20AC;&#x2122;, with the remainder
Everyday Practical Electronics, January 2010
Teach-In 2010 Begin counting
Fig.3.1. Using a low-speed timer to
An enable signal derived from Port A bit 0 causes the timer to begin !
" ' 255, which allows time delays of up to 255 seconds to be achieved. The timerâ&#x20AC;&#x2122;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) * ! + ' = 1)
An important difference between a timer and a latch is that the enable input needs to be continuously applied, in order to â&#x20AC;&#x2DC;enableâ&#x20AC;&#x2122; the timer to count. If a momentary enable input is required, then this should be used " 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 $ % &
is given in Listing 3.2, based on the PIC16F627/627A microcontroller. Considering the program operation, it can be seen that Port A bits 0-2 act as three separate input sensors. The combined sensor status is stored temporarily in auxiliary relay
being â&#x20AC;&#x2DC;high speedâ&#x20AC;&#x2122;. For time delays in the range 4ms to 1 include "16F88_L.PLC" ; Defines PLC instructions second, you can use a ; (Low voltage programming enabled) high-speed timer, while longer delays, in the ld PORTA, 0 ; Read Enable input range 1 to 255 seconds, timl 0, 05H ; Low Speed Timer 0, final value = 5 seconds may be achieved with a low-speed timer. (Even ld TIML, 0 ; Read low speed timer 0 status bit longer delays are posout PORTB, 0 ; Output timer 0 status to Port B bit 1 sible by using â&#x20AC;&#x2DC;custom timerâ&#x20AC;&#x2122; circuits, as will be endp ; Marks end of PLC program seen in Part 4.) The creation of a sim; I/O Schedule ple time delay using ; Sensors = Port A bits 0-2 (1 = active) a low-speed timer is ; Armed/Reset = Port A bit 3 shown in the ladder ; (1 = armed / 0 = reset) diagram of Fig.3.1 above. ; Output = Port B bit 0 (1 = triggered) This example provides include "16F627.PLC" ; Defines PLC instructions (an on-delay timer), with the timerâ&#x20AC;&#x2122;s output bit ld PORTA, 0 ; Load Sensor 1 TIML bit 0, going high or PORTA, 1 ; Or with Sensor 2 five seconds after the or PORTA, 2 ; Or with Sensor 3 input bit PORTA bit 0. out AUX0, 0 ; Output Alarm Sensor Status to AUX0, 0 An equivalent program, based on the PIC16F88 ld AUX0, 0 ; Read Alarm Sensor status (Set input) microcontroller, is given latch AUX0, 1, AUX0, 2 ; Latched Alarm Status to AUX0 bit 1 in Listing 3.1 ; Reset = AUX0 bit 2 ! plied to the low-speed ld AUX0, 1 ; Read Latched Alarm status 0, 0x05 ; Low Speed Timer 0 with 5 second timeout timer command â&#x20AC;&#x2DC;timlâ&#x20AC;&#x2122; is timl the timer number, which is TIML, 0 ; Read Alarm Timeout (1 = timeout reached) in the range 0 to 7. The cor- ld ; Don't reset if active (* optional *) responding bit of register and_not AUX0, 0 or_not PORTA, 3 ; OR with inverted Arm/Disarm input TIML (0-7) holds the status ; (0 = disabled) bit for for the selected lowAUX0, 2 ; Output Reset Alarm signal speed timer. (Thus, TIML out bit 0 holds the status bit for AUX0, 1 ; Read Latched Alarm signal low-speed timer 0, and so ld ; Disable if timed out (* optional *) on). Recall also from Part 1, and_not TIML, 0 out PORTB, 0 ; Alarm output to buzzer / indicator that PLC command names are lower case (timl), while endp ; Marks end of PLC program register names are upper ! case (TIML).
Everyday Practical Electronics, January 2010
43
Teach-In 2010 AUX0 bit 0, which in turn is used as from the appropriate bit of the TIMH closed, but with the time for the contacts the Set input to a latch circuit. The register, with a value of â&#x20AC;&#x2DC;1â&#x20AC;&#x2122; indicat to settle being measured in milliseconds. Q output of the latch is sent to bit 1 ; Contact bounce can be particularly of register AUX0, while bit 2 of the that low speed timers use the TIML troublesome where an input switch is directly connected to a counter, with a same register provides the Reset input register.) 3. The timerâ&#x20AC;&#x2122;s internal count value single switch press causing the counter signal to the latch. Next, the latch output becomes the increments once every four millisec to increment multiple times. A useful high speed timer applica " onds, giving possible time delays from tion would be a switch debounce cir timer output being used to reset the 4ms to approximately one second. " '? $? Note: As you may have already
" being typically suitable. The output of but a longer time delay would, of timers are actually implemented as course, be used in practice). Finally, counters, with the input to the coun as the debounced input signal. Listing an audible or visible alarm output is ter being derived from an appropriate 3.3 gives a simple example, written this time for the PIC16F887 microcon generated by copying the latch output oscillator bit. This knowledge will state to an appropriate output port bit prove useful in Part 4, when we build troller, and making use of a repeating input waveform being derived from an (Port B bit 0 in this example). a custom timer. oscillator bit. Notice that two of the program lines are marked as â&#x20AC;&#x2DC;optionalâ&#x20AC;&#x2122; in the On the bounce Pulsed outputs comments at the right. Try adding and One problem often encountered The timers considered so far have all removing these lines to see the differ when dealing with input switches is ent behaviours of the alarm, following that of contact bounce. This mechani : # @ a timeout. With both lines removed, cal effect is analogous to dropping a possible to produce a pulse output by the alarm will automatically reset after tennis ball onto a hard surface, and G then watching it bounce several times to the program. The trick in this case is to realise that during the timer period (suitable for a retail exit barrier alarm, before settling. Exactly the same effect occurs when the enable input will be high, while for example). However, this behaviour might cause the mechanical contacts of a switch are at the same time the status bit will be annoyance in a residential include "16F887.PLC" ; Defines PLC instructions burglar alarm, where a faulty sensor could cause ld OSCH, 7 ; Read a 15.26 HZ waveform (T = 65.54 ms) out PORTD, 0 ; Send waveform to Port D bit 0
out. In the latter case, ld PORTD, 0 ; Read Port D bit 0 adding the two optional ; (15.26 Hz waveform = Enable input) timh 0, 03H ; High Speed Timer 0, final value = 3 preventing a reset while ; (T = 3 x 4 ms = 12 ms) a sensor remains active, and second, cancelling ld TIMH, 0 ; Read timer status bit the output if the alarm has out PORTD, 1 ; Output debounced signal timed out. endp ; Marks end of PLC program
High-speed timer applications
Operation of the eight most identical to that al
" " timers, but with three given below. ' ! : # speed timer) command is used in place of â&#x20AC;&#x2DC;timlâ&#x20AC;&#x2122;. & " " ers, remaining command arguments are the timer number (0 to 7) followed the range 1 to 255. 2. The high speed tim erâ&#x20AC;&#x2122;s status bit is available
44
Listing 3.3. A switch debounce circuit based on a high speed timer (Lst3_3.asm) include "16F887.PLC"
; Defines PLC instructions
ld out
OSCH, 7 PORTD, 0
; Read a 15.26 HZ waveform (T = 65.54 ms) ; Send waveform to Port D bit 0
ld
PORTD, 0
timh
0, 03H
; ; ; ;
ld out
TIMH, 0 PORTD, 1
ld OSCH, 7 and_not TIMH, 0 out PORTD, 2
Read Port D bit 0 (15.26 Hz waveform = Enable input) High Speed Timer 0, final value = 3 (T = 3 x 4 ms = 12 ms)
; Load timer status bit ; Output debounced (on-delay) signal ; Read high speed timer Enable input ; AND with inverted Status bit ; Output pulse waveform to Port D bit 2
endp ; Marks end of PLC program Listing 3.4. Creation on-delay and pulse outputwaveforms waveforms(Lst3_4.asm). (Lst3_4.asm) Creation of of on-delay and pulse output
Everyday Practical Electronics, January 2010
Teach-In 2010
Fig.3.3. Debugging with the aid of the Watch window in Proteus VSM software 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
introduced, can be viewed by opening J editor. Listing 3.5 shows a short (and V J Considering the timers discussed in the previous section, each of the low and high frequency timers uses a dedicated register to hold its internal 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 â&#x20AC;&#x201C; after, of course,
Available debugging options related to the display of internal registers include:
An understanding of the PLC softwareâ&#x20AC;&#x2122;s use of internal memory is useful when debugging programs, and may in some cases be required when actually writing Fig. 3.2.Output waveforms viewed using an programs (as will be seen in the oscilloscope next section). The PLC software uses a variety of low. Listing 3.4 shows the creation of PIC registers to hold its internal state, both on-delay and pulsed outputs, once some of which have already been again using a repeating oscillator bit as introduced. Each of these registers the input. (around 100 in total) holds a single Resulting waveforms are shown in byte of data. Addresses associated with Fig.3.2, which was produced with the 1. Adding one or more â&#x20AC;&#x2DC;watchâ&#x20AC;&#x2122; comthese registers, and others yet to be mands in an Integrated Development program of Listing 3.4 running on a PICkit 2 Debug Express development OSCH E H 01 ; High fre uency oscillator register board, and viewed using a Tektronix A 0 E H 20 ; Internal relay outputs TDS2004B fourA 1 E H 21 channel digital storA 2 E H 22 A 3 E H 23 age oscilloscope. A 4 E H 24 In this case, the A 5 E H 25 original waveA 6 E H 26 form is shown in A 7 E H 27 ; (8 bytes x 8 bits = 64 internal relays) orange, while the blue and magenta OSCL E H 28 ; Low fre uency oscillator register traces give the onListing 3.5. A small selection of internal memory used by the PLC software delay and pulse
Everyday Practical Electronics, January 2010
4
Teach-In 2010 puti TE, RE ISTER Loads an immediate byte value into a destination register (puti = put passing along a proimmediate). ! 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 " G putr A 0, PORT ; Copy A 0 register to Port z G endp ; Marks end of PLC program Listing 3.6. Transferring data bytes between registers (Lst3_6.asm)
" Â&#x201A; " z @`zV " Notice that the above listing uses :?Z#
J
J
" J ! V "
V " " " " V & $ Â&#x192; [\] ^ * * J V ! ] &_ " " @`z ] &\]V - ` " " J - J V
z` | V Â&#x192; J Byte transfer " & " - ? |V " Â&#x201E; ^ J " " [\] " " #?'?'?'?'# V #?{|# " G ! V #$}}# V # # G : " J V " - # Â&#x201E; " ` " Â&#x201A; J
" G " " " ~ " {Â & @ _ & V z : #
"
-
J z \ ] &\] #
" "
J
G ; ` :?Z# J V " # & Â&#x201E; Â&#x20AC; ^ * * " " J " " G " - " " " " ?
G Â&#x20AC; !@] ?V - G z` ! J
* ' " Â&#x2020; \ " @`z - Shift registers " shift NUMBER[0-7], \ " CLOCK_REG, CLOCK_BIT[0-7],
RESET_REG, RESET_BIT[0-7],
_ @ ~ Â&#x20AC; DIRECTION_REG, DIRECTION_
BIT[0-7] V ! * ' J " ! Â&#x20AC; G " : # : # ! J * { Â&#x2021; " Fig.3.4. A simple shift register
Syntax
4
Function
Everyday Practical Electronics, January 2010
Teach-In 2010
Fig.3.6. Animating a simple â&#x20AC;&#x2DC;KnightRiderâ&#x20AC;&#x2122; display
Fig.3.5. Ladder diagram for a simple shift register program
The trick in this case is to understand 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 statements is a useful strategy when debugging 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 SHIFT0SHIFT2 make use of memory locations 0x47-0x49.)
Light chaser ! J 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 graphically in Fig.3.6. A latch is used to control the direction of the shift register, with the latch being automatically set and reset as the illuminated bit â&#x20AC;&#x2DC;bouncesâ&#x20AC;&#x2122; off each side of the output register. Changing the direction of the shift register is achieved in software by linking the latchâ&#x20AC;&#x2122;s Q output to the
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 include "16F627.PLC" ; Defines PLC instructions data input to a shift register, with the clock ld OSCL, 5 ; Read OSCL bit 5 (Data input) being driven by a 1Hz shift 0, OSCL, 3, PORTA, 0, PORTA, 1 signal. This creates an ; Shift register 0 alternating pattern of ; clock = OSCL bit 3, two ones, followed ; Reset = Port A bit 0, by two zeros, since ; Direction = Port A bit 1 the clock frequency is putr SHIFT0, PORT ; Copy SHIFT0 working register to Port four times faster than that of the data input. endp ; Marks end of PLC program A visible output is ListingListing 3.7. A3.7. simple shiftshift register program (Lst3_7.asm) A simple register program (Lst3_7.asm) produced by the â&#x20AC;&#x2DC;putrâ&#x20AC;&#x2122; command, which include "16F887.PLC" ; Defines PLC instructions copies the shift registerâ&#x20AC;&#x2122;s output register ld OSCL, 7 ; Read OSCL bit 7 (Data input) (SHIFT0) across to Port shift 0, OSCL, 3, PORTA, 0, PORTA, 1 B. The equivalent pro; Shift register 0 gram is given in Listing ; Data in = OSCL bit 7 ; Clock = OSCL bit 3 3.7, in this case based ; Reset = Port A bit 0 on the PIC16F627 mi; Direction = Port A bit 1 crocontroller. shift 1, OSCL, 3, PORTA, 0 , PORTA, 1 It is also straight; Chained shift register 1 forward to link or shift 2, OSCL, 3, PORTA, 0 , PORTA, 1 â&#x20AC;&#x2DC;chainâ&#x20AC;&#x2122; multiple shift ; Chained shift register 2 registers, as shown in putr SHIFT0, PORTD ; Copy SHIFT0 working register to Port D the example of Listing 3.8, this time written endp ; Marks end of PLC program for the PIC16F887 Listing 3.8. Chaining multiple shift registers (Lst3_8.asm). microcontroller. Listing 3.8. Chaining multiple shift registers (Lst3_8.asm)
Everyday Practical Electronics, January 2010
4
Teach-In 2010 include "16F627.PLC"
ld latch e i shift
putr endp
; Marks end of PLC program
Listing 3.9. A simple light chaser program shift registerâ&#x20AC;&#x2122;s direction input and then using the state of the left and right bits of the shift registerâ&#x20AC;&#x2122;s output register to set and reset the latch, respectively. If a single illuminated bit can somehow be â&#x20AC;&#x2DC;injectedâ&#x20AC;&#x2122; 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
In comparison One answer would be to design a combinational logic circuit that would detect the binary pattern â&#x20AC;&#x2DC;0000 0000â&#x20AC;&#x2122; 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 register 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. Available byte comparison types include: s Greater than (immediate and register-based â&#x20AC;&#x201C; gti and gtr commands) s Greater than or equal (immediate and register-based â&#x20AC;&#x201C; gtei and gter commands) s Equal (immediate and registerbased â&#x20AC;&#x201C; eqi and eqr commands) s Not equal (immediate and registerbased â&#x20AC;&#x201C; nei and ner commands) s Less than (immediate and registerbased â&#x20AC;&#x201C; lti and ltr commands) s Less than or equal (immediate and register-based â&#x20AC;&#x201C; ltei and lter commands). Thus, we can use the â&#x20AC;&#x2DC;eqiâ&#x20AC;&#x2122; (equal to an immediate value) command
4
5. Optionally allowing the display to be blanked by resetting the shift register. ! standing of the programâ&#x20AC;&#x2122;s operation, you should ensure that you can match each of the above descriptive points to the actual section of code performing that task. Note that weâ&#x20AC;&#x2122;ll be using a sequencer command later in the series to create much more
" Â&#x2039; J plays than those seen so far â&#x20AC;&#x201C; and the associated programs will be even shorter!
; Defines PLC instructions ; Latch controls shift direction ; (direction changes when 1 reaches end) SHIFT0, 7 ; MSb of working register = Set input A 0, 0, SHIFT0, 0 ; A 0, 0 = output ; LSb of working register = Reset input PORT , 0x00 ; Input a logic-1 if Port = 00000000 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 SHIFT0, PORT ; Copy SHIFT0 working register to Port
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 " ally enable and disable the output display. If you want to run the shift register continuously then it is possible 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 reference to PORTA, 0 with a reference which always returns a â&#x20AC;&#x2DC;0â&#x20AC;&#x2122;. To this end, the PLC software provides a register with the name â&#x20AC;&#x2DC;LOGICâ&#x20AC;&#x2122;, with bit 1 of this register preprogrammed to a value of â&#x20AC;&#x2DC;1â&#x20AC;&#x2122; and bit 0 of the same register containing â&#x20AC;&#x2DC;0â&#x20AC;&#x2122;. Thus, replacing the reference to â&#x20AC;&#x2DC;PORTA, 0â&#x20AC;&#x2122; in Listing 3.9 with â&#x20AC;&#x2DC;LOGIC, 0â&#x20AC;&#x2122; will permanently disable the reset function. This is clearly a remarkably compact program, considering the complexity 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â&#x20AC;&#x2122;s working register, respectively. 3. Injecting a logic 1 into the shift register if the working register is empty. 4. Copying the shift registerâ&#x20AC;&#x2122;s working register to an output port, in order to make it visible.
Summary Part 3 of the series has continued the tour of the PLC softwareâ&#x20AC;&#x2122;s sequential logic capabilities, focusing on timers and shift registers. Low-speed and high-speed timers have been introduced, offering time delays ranging from four milliseconds to approximately 255 seconds. ! pulse output timers has been discussed, and these have been applied in applications as diverse as alarms and switch debounce circuits. A range of shift register applications has also been developed. This has included the use of single and chained shift registers, repeating pattern displays based on oscillator bit inputs, and even a simple KnightRider-style display. We have looked at the use of internal 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 instructions to programs. A number of byte processing instruction categories has also been introduced and used to simplify the coding of programs (selected byte transfer and byte comparison commands were used).
Next month The next part of the series will introduce further sequential logic capabilities of the PLC software, including counters and the creation of pulsewidth-modulated (PWM) signals.
Everyday Practical Electronics, January 2010
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?
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...
http://www.handsontec.com
Teach-In 2010
TEACH-IN 2010
LADDER LOGIC PROGRAMMING FOR THE PIC MICRO Part 4: Counters and PulseWidth-Modulated Waveforms By Walter Ditch
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 generation of pulse-width-modulated (PWM) waveforms. (Recall that previous instalments have covered topics including inputs and outputs, combinational logic, oscillators, latches, timers, shift registers, byte transfer and byte comparison commands.) These building blocks have been used to construct a number of simple systems, using a programming approach called ladder logic, which has close parallels to the design and construction of electronic circuits. Thus, the designer (thatâ&#x20AC;&#x2122;s you!) simply uses ladder logic program statements 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 assemblerâ&#x20AC;&#x2122;s macro substitution feature. This process has close parallels with the use of a compiler to convert a high level language program (such as BASIC, Pascal or C) into machine code â&#x20AC;&#x201C; including, of course, the inevitable increase in 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 easy to write ladder-logic-style programs, and the source code programs are normally very concise. I hope that you will use the techniques 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, performing tasks exactly as you intended!
Software As explained previously, all program listings for this series are available from the Library > Project Code section of the Everyday Practical Electronics website (www.epemag.com). Youâ&#x20AC;&#x2122;ll also need which should be â&#x20AC;&#x2DC;unzippedâ&#x20AC;&#x2122; into a single folder, together with the sample 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 PIC microcontroller types, or simulation software such as Proteus VSM from Labcenter Electronics.
Everyday Practical Electronics, February 2010
Counter applications As their name suggests, counters are used when you need to keep track of the number of times an event has occurred. In its most basic application, the counter simply provides a signal when the predetermined number of input signals has been detected â&#x20AC;&#x201C; as in a simple unidirectional counter. Counters are also available which can count up or down â&#x20AC;&#x201C; a bidirectional counter. Both types of counter maintain a running total of the number of inputs received, in addition to the output. Counters may be used as building blocks in a wide variety of more complex designs, with motor control being a typical application. For example, 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 â&#x20AC;&#x2DC;soft startâ&#x20AC;&#x2122; 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.
49
Teach-In 2010 Unidirectional counters The PLC software provides up to eight unidirectional (up only) counters, plus a further eight bidirectional counters. Operation of a basic unidirectional counter is quite similar to that already seen with timers, which should come as no surprise, since a timer is little more than a counter with an oscillator hard-wired to its input. A simple unidirectional counter application is illustrated by the example of Fig.4.1.
Fig.4.1. A simple counter circuit, shown in ladder diagram form
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 required in simple counter programs, so $ %& ' * %& ' +* / count values are available, if required, from registers CTR0-CTR7 respectively, and this running total may be used in more advanced applications. (An internal count value will be used later as part of a motor speed controller system, 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 voltage 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
on a simulator, such as Proteus VSM, compared to a real PIC development board â&#x20AC;&#x201C; and the difference is no fault of the simulator. Switch bounce is an unwanted 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 having a delay of 12ms. The output of the on-delay timer (bit 0 of register TIMH) in turn becomes the input to the counter, with the remainder of the second useful exercise is to load the programs of Listings 4.1 and 4.2 on to a suitable development board, comparing the actual number of switch presses required to set the counterâ&#x20AC;&#x2122;s Status bit â&#x20AC;&#x201C; the exactly ten switch presses every time. As mentioned earlier, it is easy to create a custom timer by combining an oscillator waveform and a unidirectional counter. Referring back to Part 2, Table 2.1, it can be seen that a variety
The previous input value provides the clock input to the counter, which is typically the result of a include "16F88_L.PLC" ; Defines PLC instructions â&#x20AC;&#x2DC;ldâ&#x20AC;&#x2122; or â&#x20AC;&#x2DC;ld_notâ&#x20AC;&#x2122; instruc; (Low voltage programming enabled) " ld PORTA, 0 ; Read Port A bit 0 (clock input) eter actually supplied ctr 0, 0AH, PORTA, 1 ; Counter 0 to the â&#x20AC;&#x2DC;ctrâ&#x20AC;&#x2122; command ; Final value = 10 (0AH), is the counter number, ; Reset = Port A bit 1 which must be in the range 0-7. Remaining ld CTR, 0 ; Read counter 0 status bit (1 = finished) out PORTB, 0 ; Output counter 0 status to Port B bit 0 value (1-255), followed endp ; Marks end of PLC program by the reset register and reset bit (0-7). Listing 4.1. Counting pulses using a unidirectional counter (Lst4_1.asm) Each rising edge of include "16F88_L.PLC" ; Defines PLC instructions the Clock input causes ; (Low voltage programming enabled) the internal counter ld PORTA, 0 ; Read Port A bit 0 (Count input) register to increment. The counterâ&#x20AC;&#x2122;s Status timh 0, 03H ; High Speed Timer 0, final value = 3 bit becomes set when ; (T = 3 x 4 ms = 12 ms) the counter reaches its ld TIMH, 0 ; Read timer status bit (debounced input) # ctr 0, 0AH, PORTA, 1 ; Counter 0, final value = 10 (0AH), value, which is in the ; Reset = Port A bit 1 range 1-255 (a final ld CTR, 0 ; Read counter 0 status bit (1 = finished) out PORTB, 0 ; Output counter 0 status to Port B bit 0 value of 10 is shown in the example of Fig.4.1). endp ; Marks end of PLC program The counterâ&#x20AC;&#x2122;s status bit is available from the Listing 4.2. Adding a debounced switch input to the simple counter application (Lst4_2.asm)
50
Everyday Practical Electronics, February 2010
Teach-In 2010 where it is necessary to count values which ld OSCL, 6 ; 8.389 s periodic time clock input may either increase or ctr 0, d'143', PORTA, 1 ; Counter 0, final value = 143 decrease. Consider as ; Reset = Port A bit 1 an example, a system ld CTR, 0 ; Read counter 0 status bit (1 = finished) designed to control out PORTB, 0 ; Output counter 0 status to Port B bit 0 entry to a car park, based on the number endp ; Marks end of PLC program of spaces available. In Listing 4.3. Using a custom timer to create a 20 minute delay (Lst4_3.asm) this case, the number of spaces available would of oscillator frequencies are available status output â&#x20AC;&#x2DC;directlyâ&#x20AC;&#x2122; as the count from registers OSCH and OSCL, with input to the next stage, at the same decrease as cars enter the car park, but period times ranging from 512Ps to time using it to reset the current stage would rise as cars leave. Coding of the bi-directional counter 16.77 seconds. Combining these inputs ; with the ability to count from 1-255 previous counter will then cause the command is similar to its unidirecinput cycles gives an incredibly wide next stage to increment, before reset- tional counterpart, but with the addirange of potential time delays, ranging ting the current stage back to zero. As tion of a direction control input. The from a few milliseconds up to a maxian example, Listing 4.4 shows a two- ctr_ud command has the following mum of 255 Ă&#x2014; 16.77 seconds, or 4,276 stage custom timer, this time written syntax: seconds (approximately 71 minutes). for the PIC16F887 microcontroller. ctr_ud CTR_NUMBER[0-7], A repeating 1Hz oscillator waveform As an example, letâ&#x20AC;&#x2122;s assume that a FINAL_VALUE[1-255], time delay of 20 minutes (1200 seconds) DIRECTION_REGISTER, + < is required â&#x20AC;&#x201C; for a burglar alarm timeDIRECTION_BIT[0-7], that the counter uses its own status bit out perhaps. A quick calculation shows RESET_REGISTER, to reset itself back to zero. The output that 1200 seconds á 255 would require RESET_BIT[0-7] a period time of 4.7 seconds, which comes the input to the next counter unfortunately is not directly available (or may be manually read from bit 0 from the OSCL or OSCH registers. A further difference is the provision of the CTR register), causing the secHowever, from Table 2.1, the next of two status bits, compared to the one ond counter to be cascaded from the higher period time is 8.389 seconds, used by the unidirectional counter. = which is available from bit 6 of the OSCL The upper threshold is set when the of six, and once again using its own register. A quick calculation shows that status bit as a reset signal. The state a count value of 143, combined with a one by the initial value. These status period time of 8.389 seconds would give registers PORTC and PORTD, allowing bits may be read from the appropria calculated time delay of 1199.627 secdirect viewing on LEDs assumed to be ate bits of registers CUP (count up onds, which is very close to our required connected to these ports. (Listing 4.4 * @G< % * time delay value. Listing 4.3 shows how is particularly suitable for use with respectively. (So, for example, the upthis might be coded for the PIC16F627 the Proteus VSM 16F887 simulation per and lower status bits for up/down microcontroller. supplied with Part 1.) Donâ&#x20AC;&#x2122;t expect this program to do @J K @G< K * The next section considers bidirecanything too exciting â&#x20AC;&#x201C; it takes 20 Applying a 1 to the Reset input clears tional or up/down counters, which minutes just to turn on a single the internal count value, at the same tend to be more versatile than their LED! However, it might be useful unidirectional counterparts, although time setting the appropriate bit of the to combine this custom timer with quite similar from a programming @G< % the burglar alarm program previnow contains zero). perspective. ously seen in Listing 3.2, in order to provide a more practical time-out Bi-directional (up/down) Current count value period. (This is left as an exercise counters If you need to know the current for the reader.) Eight bi-directional counters are count value, then this information available, and suitable for applications is available from registers CUD0â&#x20AC;&#x201C; Longer delays include "16F627.PLC"
If even longer delays are required, then it is possible 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â&#x20AC;&#x2122;s
; Defines PLC instructions
include "16F887.PLC"
; Defines PLC instructions
ld ctr ctr
OSCL, 3 0, d'10', CTR, 0 1, d'6', CTR, 1
; Count 1 second pulses ; Count to 10 then reset ; Count to 6 then reset
putr putr
CTR0, PORTC CTR1, PORTD
; Copy low byte to Port C ; Copy high byte to Port D
endp ; Marks end of program Listing 4.4. Creating a multiple-byte custom counter/timer (Lst4_4.asm)
Everyday Practical Electronics, February 2010
5
Teach-In 2010 @JGZ register name is determined by the counter number. (To use the car park spaces analogy again, the ctr_ud com [ 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, @J @G< status bits would indicate that the car park was either full or empty, respectively.) The example of Listing 4.5 shows an up to ten pulses on Port A bit 0, with bits available from Port C, bits 1 and 0 respectively. The program counts pulses applied to bit 0 of Port A, displaying the cur \]G
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 hexadecimal numbers. Finally, suitable hardware interfacing would be required, including entry/exit sensors, time delays, and switch debounce logic. In cases like this, where the PLC software doesnâ&#x20AC;&#x2122;t quite do what you might require, then one approach is to consider extending the PLC instruction set by Fig.4.2. Repeating pulse waveforms and their associated parameters
As can be seen, the mark-to-space ratio is ld PORTA, 0 ; Read Port A bit 0 ; (clock input to up down counter) tion of time the wavectr_ud 0, 0x0A, PORTA, 1, PORTA, 2 form is high, relative to ; Up down counter 0, the time the waveform ; Final value = 0x0A (10) is low. The duty cycle ; Direction = Port A bit 1 (1 = Up, 0 = Down) measures the time the ; Reset = Port A bit 2 (1 = Reset) waveform is high, relative to the period (time) ld CUP, 0 ; Load Up Down Counter 0 count-up status bit of the waveform. out PORTC, 1 ; Output final value reached status The â&#x20AC;&#x2DC;duty cycleâ&#x20AC;&#x2122; approach is used by the ld CDN, 0 ; Load Up Down Counter 0 count-down status bit PLC software, with out PORTC, 0 ; Output initial value reached status pulse width and period putr CUD0, PORTD ; Copy current count value to Port D in multiples of 1/500th of a second (ie 2ms). endp ; Marks end of PLC program PWM signals may be Listing 4.5. Using a bidirectional counter (Lst4_5.asm) created, based either
G ^ adding custom macros of your own. %N following a reset applied to Port A bit For example, the addition of a custom ateâ&#x20AC;&#x2122; values), or based on the content 2, the internal count value will be zero, decade counter macro with up, down, of internal registers â&#x20AC;&#x201C; with the latter @G< + carry and borrow connections, and ca- method being more suited to dynamic set (as seen from Port C bit 0). Assuming pable of being cascaded, would make it # J easy to display the number of spaces as a four PWM outputs of each type may be created. up, by applying a logic1 to Port A bit decimal number. Weâ&#x20AC;&#x2122;ll look at advanced The â&#x20AC;&#x2DC;pwmiâ&#x20AC;&#x2122; command produces 1, then the counter will increment after programming concepts, including cus $ tomisation of the software, in the sixth Q % * PWM waveforms. The repeating pulse @J + waveform is driven by an internal set (linked to bit 1 of Port C). clock, which is linked to a 500Hz Bear in mind that the above car park Creating repeating pulses The PLC software makes it easy to signal (taken internally from OSCH, scenario is used purely as an analogy, and the program would certainly create repeating pulse waveforms of 2). The three command arguments are not be suitable in its current form to - the register number (0-3); the number control a real car park for a number of 2ms time periods the waveform of reasons! To begin with, a display of of their frequency and either their should be high (1-255); followed by the number of spaces available would mark-to-space ratio or duty cycle, as the total number of time periods in the waveform period (1-255). Output be more useful than the number of illustrated by Fig.4.2. include "16F887.PLC"
5
; Defines PLC instructions
Everyday Practical Electronics, February 2010
Teach-In 2010 waveforms are available by reading the appropriate bits of the PWMI register. (Thus, for example, the output waveform for the â&#x20AC;&#x2DC;pwmi, 2â&#x20AC;&#x2122; command may be read from bit 2 of the PWMI register.)
The â&#x20AC;&#x2DC;pwmrâ&#x20AC;&#x2122; command produces up to four â&#x20AC;&#x2DC;variableâ&#x20AC;&#x2122; or register-based PWM waveforms. The three arguments supplied to the pwmr comExample of pwmi command mand are the regisAs an example of the pwmi com- ter_number (0-3), the mand, the program Listing 4.6 creates register containing Q `{ the number of pulses with duty cycles of 20%, 40%, 60% the waveform should and 80%, and with a base frequency be high (0-255), folof 50Hz. lowed by the regis]Q ter holding the total waveform in detail, notice that the number of pulses pwmi, 0 command is supplied with in the waveform (1a pulse width of 2 Ă&#x2014; 2ms (2 Ă&#x2014; 1/500th 255). of a second), while the period time is A simple example + ~ " is given in Listing 4.7, is high for 4ms out of every 20ms, giving a 20% duty cycle and a base desired duty cycle frequency of 50Hz. The waveform is parameter values into made visible by copying the output a pair of registers, and bit from PWMI, 0 to bit 0 of Port D. then uses the pwmr Fig.4.3 shows the output produced command to create by the program, running on a PICkit a 20% duty cycle 2 Debug Express unit. waveform. Q The real power of duty cycle waveforms, the ability this method is the & ' * #+ 6 7 8 " 9 ;
capacity to modify the content of the include "16F887.PLC" ; Defines PLC instructions registers used by the pwmr command pwmi 0, d'02', d'10' ; 20 duty cycle on P MI, 0 at run-time, hence allowing real time pwmi 1, d'04', d'10' ; 40 duty cycle on P MI, 1 control of the pulse width and period pwmi 2, d'06', d'10' ; 60 duty cycle on P MI, 2 time respectively. As an example of pwmi 3, d'08', d'10' ; 80 duty cycle on P MI, 3 this technique, Listing 4.8 shows the running count value of an up/down ld P MI, 0 ; Load P MI, 0 waveform (20 ) counter, being used to control the out PORTD, 0 ; Output to Port D bit 0 pulse width of a PWM waveform. Operation of the program is logically ld P MI, 1 ; Load P MI, 1 waveform (40 ) divided into three sections, with the out PORTD, 1 ; Output to Port D bit 1 `{ ld P MI, 2 ; Load P MI, 2 waveform (60 ) nal, and the third actually making the out PORTD, 2 ; Output to Port D bit 2 waveform visible on an output port. Section 1: Applying an input to eild P MI, 3 ; Load P MI, 3 waveform (80 ) ther bit 0 or bit 1 of Port A will enable out PORTD, 3 ; Output to Port D bit 3 the counter, but Port A bit 1 also serves to control the direction of the counter endp ; Marks end of PLC program (1 = up/0 = down). Thus the former causes the counter to decrement, while to dynamically vary include "16F627.PLC" ; Defines PLC instructions the duty cycle at run puti d'02', AU 0 ; Put 2 into register AU 0 time can be more useputi d'10', AU 1 ; Put 10 into register AU 1 ful when developing pwmr 0, AU 0, AU 1 ; Create P M waveform based on AU 0 AU 1 applications â&#x20AC;&#x201C; with potential scenarios ld P MR, 0 ; Load P MR, 0 output bit including DC motor out PORTB, 0 ; Send P M signal to Port B bit 0 speed control, lamp dimmer circuits, or endp ; Marks end of PLC program servo-based position !" #$% control systems.
Everyday Practical Electronics, February 2010
5
Teach-In 2010 include "16F627.PLC"
ld or and ctr_ud
the generation of PWM waveforms. A wide variety of systems may now be developed, ranging from burglar alarms to motor speed controllers â&#x20AC;&#x201C; and using only a few lines of code in each case.
; Defines PLC instructions
; First section configure up down counter PORTA, 0 ; Read Port A bit 0 (Slower input) PORTA,1 ; OR with Port A bit 1 (Faster input) OSCL,1 ; Clock input to up down counter 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
Next Month
While the development of software using ; Second section configure P M signal a ladder logic approach puti d'32', AU 1 ; Put 32 into register AU 1 (= period) is clearly useful with pwmr 0, CUD0, AU 1 ; Create P M waveform based on CUD0 and AU 1 microcontrollers, any practical system is likely ; Third section display P M waveform to contain a combination ld P MR, 0 ; Load P M status bit of hardware and software. out PORTB, 0 ; Output waveform to bit 0 of Port B Essential concepts related to hardware interfacing endp ; Marks end of PLC program techniques will, thereListing 4.8. Varying pulse width by using a bidirectional counter (Lst4_8.asm) fore, be considered in the the latter makes it increment, with the Linking an up/down counter to an- next and penultimate part, allowing the rate of change controlled by ANDing other electronic sub-system (a PWM PIC micro to be linked to a wide variety the combined signal with OSCL, 1 (a waveform generator in this case) is a of hardware, including switches, LEDs, 4Hz square wave signal). powerful technique, and may be used transistors, relays, motors, solenoids as a building block in a wide variety of and opto-couplers. Section 2: The up/down counter is Further byte-oriented capabilities Q electronic systems. This concept will be explored further in Part 6, where a of the software will be discussed, value of 31, with the running count number of custom macros will be de- including the (surprisingly powerful) stored in register CUD 0. This value is then used by the pwmr command as the veloped, based on the general theme of sequencer command. Byte-oriented pulse width value of a variable PWM â&#x20AC;&#x2DC;code conversionâ&#x20AC;&#x2122;, allowing direct con- logical and arithmetic capabilities will Q %Â&#x201A; nection of counters to devices includ- also be introduced, while other bytepulses) obtained from register AUX1. ing stepper motors, Gray-coded discs ; Thus, the maximum duty cycle will be recapped, including byte comparison and seven-segment displays. Â&#x201A; Â&#x201A; Â&#x201E;Â&#x2020; Â&#x201E;Â&#x2021; and byte transfer commands. Â&#x2020;Â&#x2C6; %Â&#x201A; ~ * Summary These concepts will enable us to explore a range of new applications, includSection 3: The PWM status bit is Part 4 of the series has continued the read from bit 0 of register PWMR and tour of sequential logic features of the ing LED-based animated displays, digital copied to bit 0 of output Port B. PLC software, introducing counters and comparators and motor controllers.
CD FRE -R E OM
ERS OF
PIC MIC USINGcal introduction
rstand M aid unde are on CDRO ect proj softw Free programmer e ware pl ft m so Si t ki PIC Tool Free eed
I MIX
S PIICCprNacâ&#x20AC;&#x2122; tical PLUA ho st of ost os g and
n ing you Everyth u started to get yo
0 2.
0 601 D1
ICs C FOR Pers guide
20 09
Mi cro
A beginn the C g to usin ming me m progra to program ge langua rocontrollers PIC mic
an
un
t ri es
IC sP dd
.Š
PIC B,
ÂŽIDE ! PIC ICÂŽDig LAB ! dsP ! MP PS V2.32 k ns ! MA t Treelin Solutio ns !bLatestor Control ded Solutio ns ! Mo it Embed Solutio & !b16-b Tools ar r co er 16-bit eg !
othe ist d ere an dt rad SA em eU arks n th of M ed i icrochip porat Technology Incor
Issu Tech nology I rved. nc. All rights rese
C MC e 1.
Š
chip
s Te a c h- In 2 nic ng Ltd 2009 ro shi ct Wimborne Publi
n mmin progra ing informatio interfac
for the tware the sof s in the ! All ts/feature and PIC projec In 2 series ctronics Teach- in the Ele . Plus PIC x utions Nâ&#x20AC;&#x2122; Mi -In 2 book des and t) e Sol llers e Co ntro ironmenInterfac ach Te an ÂŽMicroco t Env s t Sourc USB men ! Hum elop ntroller s with it PIC Projec cks. ted Dev ! 8-b 24 Microco ntroller Controllers (Integra ! PIC 32 Microco Signal PIC Tri V8.20 ital
P LA o, M The Microc ip name and log h
On sale in WHSmiths or available direct from us:
5
BLISH THE PU
A practi oard layouts to Breadb ing
PLUS CD-ROM
01202 873872 www.epemag.com
ÂŁ7.99
FROM
Ele
Inclu P P&
ONICS ELECTR-IN 2 T E A C H ROCONTROLLERS
9.
0 5 . 9 ÂŁ ding UK
ELECTRONICS TEACH-IN 2
23/03/2009
dd 1
Everyday Practical Electronics, February 2010
11:39:27
Teach-In 2010
7($&+ ,1
/$''(5 /2*,& 352*5$00,1* )25 7+( 3,& 0,&52 0ARTª ª !DVANCEDª 0ROGRAMMINGª ANDª)NTERFACINGª4ECHNIQUESª By Walter Ditch
T
(% ÚFTH AND PENULTIMATE PART OF THIS SERIES BEGINS BY EXPLORING BASIC CONCEPTS RELATED TO HARD WARE INTERFACING INCLUDING METHODS OF CONNECTION TO INPUT DEVICES SUCH AS SWITCHES AND TO OUTPUTS INCLUDING ,%$S SEGMENT DISPLAYS RELAYS SO LENOIDS AND MOTORS 4HIS KNOWLEDGE WILL GIVE YOU AN APPRECIATION OF THE HARDWARE DESIGN OF AN ACTUAL INDUSTRIAL 0,# q ALTHOUGH OF COURSE THE CIRCUITS CONSIDERED WILL BE RATHER MORE BASIC THAN THOSE OF A COMMERCIALLY AVAILABLE PRODUCT (ARDWARE DESIGN IS ALSO IMPOR TANT IN EMBEDDED CONTROL APPLICATIONS WHERE THE 0)# BECOMES AN INTEGRAL PART OF AN ELECTRONIC SYSTEM ADDING INTEL LIGENCE AND ÛEXIBILITY 7EmLL ALSO USE THE CHOSEN EXAMPLES TO DEMONSTRATE THE USE OF COMPUTER BASED ELECTRONIC SIMULATION SOFTWARE 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 WHICH HAVE BEEN GROUPED TOGETHER UNDER THE UMBRELLA TERM OF lAD VANCED PROGRAMMINGm 4OPICS COVERED INCLUDE • "YTE ORIENTED PROGRAMMING DATA TRANSFER COMBINATIONAL LOGIC
46
NUMERIC COMPARISON AND ARITHMETIC OPERATIONS • #REATION OF SIMPLE STATE BASED SYS TEMS BY USING THE BUILT IN SEQUENCER FEATURE #ONCEPTS COVERED HERE AND IN PREVIOUS PARTS OF THE SERIES WILL BE PULLED TOGETHER NEXT MONTH WITH THE ÚNAL INSTALMENT FOCUSING ON THE DEVELOPMENT OF CUSTOM EXTENSIONS TO THE SOFTWARE ! NUMBER OF SOFTWARE SOLUTIONS WILL BE DEVELOPED MAK ING IT STRAIGHTFORWARD TO CONTROL THE HARDWARE DEVICES DISCUSSED HERE AND MANY MORE BESIDES
,ISTINGS !S USUAL ALL PROGRAM LISTINGS FOR THIS SERIES ARE AVAILABLE FROM THE ,I BRARY 4UTORIALS SECTION OF THE &1& WEBSITE WWW EPEMAG COM 9OUmLL ALSO NEED THE HEADER ÚLES SUPPLIED WITH 0ART WHICH SHOULD BE lUN ZIPPEDm INTO A SINGLE FOLDER TOGETHER WITH THE SAMPLE ÚLES FROM EACH PART OF THE SERIES -AKE SURE YOU HAVE INSTALLED THE FREELY AVAILABLE -0,!" )$% SOFTWARE WHICH WILL BE NEEDED TO ASSEMBLE THE EXAMPLE PROGRAMS !ND OF COURSE IN ORDER TO ACTUALLY TEST THE PROGRAMS YOU WILL NEED A SUITABLE 0)# DEVELOPMENT BOARD ÚTTED WITH ONE OF THE SUPPORTED 0)# MICROCONTROLLER TYPES OR SIMULATION
SOFTWARE SUCH AS 0ROTEUS 63- FROM ,ABCENTER %LECTRONICS
(ARDWAREªDESIGNªCONCEPTS 0)# MICROCONTROLLERS ARE OFTEN USED IN lEMBEDDED SYSTEMSm WHERE THE 0)# BECOMES A ÛEXIBLE AND REPROGRAM MABLE ALTERNATIVE TO A HARD WIRED ELECTRONIC CIRCUIT !LTHOUGH SOPHISTI CATED INPUT OUTPUT CIRCUITRY IS ALREADY PROVIDED IN THE COMMERCIAL 0,# 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 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 FOR INSTANCE TO CONTROL A $# MOTOR FROM A LADDER LOGIC OUTPUT 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 INCLUDING SWITCHES ,%$S TRANSISTORS RELAYS MOTORS SOLENOIDS AND OPTOCOUPLERS
Everyday Practical Electronics, March 2010
Teach-In 2010 3TARTINGªWITHªTHEªDATAªSHEET 4HE DEÚNITIVE SOURCE OF INFORMA TION FOR THE HARDWARE DESIGNER IS THE APPROPRIATE 0)# DATA SHEET WHICH MAY BE DOWNLOADED FROM THE -ICROCHIP WEBSITE WWW MICROCHIP COM IN 0$& 0ORTABLE $OCUMENT &ORMAT FORMAT AND THEN VIEWED USING THE FREELY AVAIL ABLE !DOBE 2EADER SOFTWARE 0)# DEVICES REALLY DO VARY PAR TICULARLY IN THEIR CURRENT HANDLING CAPACITY SO MAKE SURE THAT YOU CARE FULLY READ THE DATA SHEET FOR THE ACTUAL MICROCONTROLLER BEING USED PRIOR TO DESIGNING ANY INTERFACING CIRCUITRY
#ONNECTINGªINPUTªSWITCHES 0)# MICROCONTROLLERS ARE BASED IN TERNALLY ON #-/3 TECHNOLOGY SO ANY INPUT CIRCUITS WILL DRAW NEGLIGIBLE CUR RENT BEING EFFECTIVELY VOLTAGE CONTROL LED INPUT LEAKAGE CURRENTS OF P! OR LESS 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 TYPICALLY USING A CALCULATION BASED ON THE POSITIVE SUPPLY VOLTAGE 6$$ 4HIS CAN SEEM COMPLEX BUT ASSUM ING A 6 POWER SUPPLY AND STANDARD INPUT CIRCUITRY A LOGIC WILL BE REC OGNISED AS A VOLTAGE IN THE RANGE 6 TO 6 ¯ 6$$ 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 USING NOTHING MORE COMPLEX
THAN A SWITCH AND A RESISTOR FOR EACH PORT BIT 4HIS IS ILLUSTRATED BY &IG )T IS ASSUMED HERE AND IN FOLLOWING INTERFACING EXAMPLES THAT A SIMPLE LADDER LOGIC PROGRAM IS RUNNING 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 AND SEVERAL OTHER CIRCUIT VARIATIONS ARE POSSIBLE 3WITCH 37 PROVIDES A DIRECT CONNECTION TO LOGIC WHEN CLOSED 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 WHERE A WEAK PULL UP OR PULL DOWN IS APPLIED 4HIS LATTER CIRCUIT MAY BE PREFERRED FOR A GENERAL EXPERIMENTATION ARRANGEMENT PARTICULARLY IF THERE IS ANY POSSIBIL ITY OF THE PORT BEING CONÚGURED AS AN OUTPUT SINCE IT AVOIDS THE POSSIBILITY OF AN EXCESSIVE OUTPUT CURRENT 7HY USE A K RESISTOR 7ELL THE PRE CISE VALUE IS NOT CRITICAL 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! EFFECTIVELY OVERCOMING ANY INPUT PORT LOADING EFFECTS 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 THUS AVOIDING FALSE TRIGGERING OF INPUT CIRCUITS
&IG ª-ETHODSªOFªCONNECTINGªINPUTªSWITCHES
Everyday Practical Electronics, March 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 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 WHERE INPUT SWITCHES ARE DIRECTLY LINKED TO THE 0)# IT WOULD NOT BE ADEQUATE IN CASES WHERE THE USER WAS ALLOWED TO MAKE THEIR OWN CONNECTIONS VIA INPUT TERMINALS (IGHER VOLTAGES OR INCORRECT POLARITIES WOULD BE QUITE LIKELY TO OCCUR LEADING TO THE LIKELIHOOD OF DAMAGE TO THE MICROCONTROLLER OR EVEN THE RISK OF ELECTRIC SHOCK TO THE USER ! MORE ROBUST INPUT CIRCUIT WOULD BE ADVISABLE IN THIS CASE INCORPORAT ING SOME KIND OF ELECTRICAL ISOLATION OF THE LOW VOLTAGE AND POTENTIALLY HIGH VOLTAGE SECTIONS /PTOCOUPLER OPTOISO LATOR CIRCUITS ARE IDEALLY SUITED TO THIS PURPOSE AND THESE WILL BE DISCUSSED SHORTLY FOLLOWING CONSIDERATION OF OUTPUT DEVICES
)NTERFACINGªOUTPUTS !CCORDING TO THE 0)# DATA SHEET THE MAXIMUM CURRENT CAPACITY OF A SINGLE OUTPUT PORT IS M! BOTH AT LOGIC CURRENT BEING lSOURCEDm OR ÛOWING OUT OF THE PIN AND AT LOGIC CURRENT ÛOWING INTO THE PIN OR BEING lSUNKm (OWEVER THERE WILL ALSO BE AN OVER ALL MAXIMUM CURRENT LIMIT 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 SUNK SOURCED BY 0/24! AND 0/24" COMBINED M! • 0)# & q MAXIMUM CURRENT SUNK SOURCED BY 0/24! OR 0/24" SEPARATELY M! • 0)# & q MAXIMUM CURRENT SUNK SOURCED BY ALL PORTS COMBINED M! $ESIGN CONSTRAINTS ALSO EXIST RE LATED TO THE MAXIMUM CURRENT SUNK OR SOURCED PLUS THE OVERALL POWER DISSIPATED BY THE ENTIRE DEVICE &OR EXAMPLE 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!
47
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 INCLUDING BOTH THE SUPPLY VOLTAGE TO THE 0)# ITSELF AND ALSO 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 6/( IS DEÚNED AS BEING 6$$ q 6 WHICH FOR A 6 POWER SUPPLY WOULD BE IN THE RANGE 6 TO 6 3IMILARLY THE MAXIMUM OUTPUT VOLTAGE FOR A LOGIC 6/, IS GIVEN AS 6 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! SO SLIGHTLY WORSE ÚGURES MAY BE FOUND IN PRACTICE 4HIS GIVES US THE NECESSARY INFOR MATION TO DESIGN OUTPUT INTERFACE CIRCUITRY NOTING THAT THE 0)# MICROmS POWERFUL AND SYMMETRICAL OUTPUT DRIVE CIRCUITRY PROVIDES US WITH GREAT DESIGN ÛEXIBILITY )MAX M! BOTH AT LOGIC AND ALSO AT LOGIC
ASSUMED HERE BUT FORWARD VOLTAGES MAY VARY DEPENDING ON THE COLOUR OF THE ,%$ 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 HERE WILL GIVE A CURRENT OF APPROXIMATELY M! ASSUMING THAT A VOLTAGE OF 6 APPEARS ACROSS THE RESISTOR TERMINALS q OR SLIGHTLY LESS IN THE EVENT OF WORST CASE OUTPUT VOLTAGES OF 6/( AND 6/,
#ONTROLLINGªLARGERªCURRENTSª ANDªHIGHERªVOLTAGES 7HERE HIGHER VOLTAGES AND OR HIGHER CURRENTS MUST BE CONTROLLED THEN
A TRANSISTOR OUTPUT CIRCUIT IS A GOOD CHOICE 4RANSISTORS COME IN MANY FORMS INCLUDING BIPOLAR AND ÚELD EFFECT TYPES AND HIGH GAIN $ARLINGTON PAIR COMPOSITE DEVICES ARE ALSO AVAIL ABLE 4O KEEP THINGS SIMPLE A CIRCUIT BASED ON AN /1/ BIPOLAR TRANSISTOR WILL BE CONSIDERED HERE AS SHOWN IN &IG 4HE /1/ BIPOLAR TRANSISTOR IS A THREE TERMINAL DEVICE WHICH IS USED HERE AS A CURRENT CONTROLLED SWITCH WITH A RELATIVELY SMALL CURRENT ÛOWING INTO THE BASE TERMINAL " CONTROLLING A LARGER CURRENT ÛOWING INTO THE COL LECTOR TERMINAL # %SSENTIALLY EITHER CURRENT IS ALLOWED TO ÛOW INTO THE BASE TERMINAL AND THE TRANSISTOR TURNS ON AND HENCE THE LAMP LIGHTS OR NO CURRENT ÛOWS INTO THE BASE AND THE LAMP AND TRANSISTOR ARE BOTH OFF
$RIVINGª,%$S &IRST LET US CONSIDER THE INTERFACING OPTIONS FOR DIRECTLY CONNECTED ,%$S AS SHOWN IN &IG !S CAN BE SEEN THE SYMMETRICAL DRIVE CAPABILITY ALLOWS US TO CONNECT THE ,%$ EITHER WAY ROUND WITH $ BEING ILLUMINATED BY A LOGIC OUTPUT AND $ BY A LOGIC ! TYPICAL ,%$ FORWARD VOLTAGE OF 6 AND A MAXIMUM CURRENT OF M! IS
&IG ª#ONTROLLINGªAª 6ªLAMPªBYªUSINGªAªTRANSISTORªSWITCHINGªCIRCUIT
&IG ª,%$ªINTERFACINGªOPTIONS
4
4HE TRANSISTOR IS ENABLED IN THE CIRCUIT OF &IG BY OUTPUTTING A LOGIC TO BIT OF 0ORT " PIN WHICH IN TURN SUP PLIES A CURRENT OF APPROXIMATELY M! TO THE BASE TERMINAL OF THE TRANSISTOR 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 BECOME A MUCH LARGER COLLECTOR CURRENT 7HEN THE TRANSISTOR IS SWITCHED ON ALMOST ALL OF THE 6 SUPPLY APPEARS ACROSS THE LAMP TERMINALS WITH ONLY 6 TO 6 ACROSS THE COLLECTOR EMITTER % JUNCTION OF THE TRANSISTOR SO 6#% 6 TO 6 AT WHICH POINT THE TRANSISTOR IS SAID TO BE lSATURATEDm 3TRANGE AS IT MAY SEEM THIS CIR CUIT IS BEST DESIGNED BY WORKING
Everyday Practical Electronics, March 2010
Teach-In 2010
&IG ª!ªSIMPLEªMULTIPLEXEDª,%$ªDISPLAY BACK FROM THE OUTPUT TO THE INPUT BEGINNING WITH THE LAMP 4O TAKE AN EXAMPLE ASSUMING THE LAMP IS RATED AT 6 AND HAS A RESISTANCE OF : ! SIMPLE CALCULATION SHOWS THAT THE LAMP CURRENT WILL BE ! SO OUR ÚRST DESIGN CONCLUSION IS THAT WE WILL NEED A TRANSISTOR WITH A 6#% MAN RATING GREATER THAN 6 AND )# IN EXCESS OF ! WHICH IS QUITE STRAIGHTFORWARD .EXT 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 IF H&% MIN AND )# M! 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 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 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! 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
&URTHERªTRANSISTORªSWITCHINGª APPLICATIONS 4HE PREVIOUS TRANSISTOR SWITCHING CIRCUIT IS CLEARLY USEFUL IN ITS OWN RIGHT ALLOWING LARGER CURRENT DEVICES TO BE CONTROLLED AND ALSO DEVICES WHICH HAVE HIGHER OPERATING VOLTAGES %QUALLY IMPORTANTLY IT MAY BE EASILY ADAPTED TO CONTROL DEVICES SUCH AS SEGMENT DISPLAYS OR INDUCTIVE LOADS SUCH AS RELAYS SOLENOIDS OR EVEN MOTORS !S A ÚRST EXAMPLE &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 THE CATHODE CONNECTION MAY BE SIMPLY GROUNDED BUT IN A MULTIPLE DIGIT DISPLAY AS SHOWN IN &IG EACH DISPLAY IS ENA BLED IN A RAPIDLY REPEATING SEQUENCE 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
Everyday Practical Electronics, March 2010
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 BUT THE BRIGHTNESS IS NORMALLY INCREASED SINCE EACH DIGIT IS ONLY ILLUMINATED FOR A FRACTION OF THE TIME 7E WILL REVISIT THIS APPLICATION NEXT MONTH WHEN CUSTOM MACROS WILL BE DEVELOPED TO DRIVE SINGLE AND MULTIPLE DIGIT SEGMENT DISPLAYS
)NDUCTIVEªLOADS ! TRANSISTOR MAY ALSO BE USED TO EN ERGISE THE COIL OF A RELAY AS ILLUSTRATED BY &IG )N THIS EXAMPLE THE RELAY IS SHOWN ENERGISING A 6 LAMP BUT A MORE ÛEXIBLE ARRANGEMENT WOULD BE TO BRING OUT THE RELAY CONTACTS TO EXTER NAL SCREW TERMINALS ALLOWING USERS TO MAKE THEIR OWN CONNECTIONS 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 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 SUCH AS A $# MOTORS STEPPER MOTORS OR EVEN SOLENOIDS q WITH ELECTRONIC DOOR LOCKS AND PNEUMATIC
4
Teach-In 2010 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 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 THEN THE FOLLOW ING SIMULATION AND DEBUGGING TIPS MAY PROVE USEFUL
&IG ª#ONTROLLINGªAªRELAYªUSINGªAªTRANSISTORªSWITCHINGªCIRCUIT VALVES BEING JUST TWO APPLICATIONS OF FOLLOWER WHICH CAUSES THE EMITTER TO SOLENOIDS BE PULLED UP TO ALMOST 6 EACH TIME !LTHOUGH NOT CONSIDERED HERE IT IS THE INTERNAL ,%$ IS ILLUMINATED 4HIS ALSO POSSIBLE TO USE TRANSISTOR CIRCUITS ALSO ILLUMINATES THE EXTERNAL INDICATOR TO PROVIDE BIDIRECTIONAL CONTROL OF ,%$ VIA CURRENT LIMITING RESISTOR 2 MOTORS OR TO ENERGISE THE COILS OF A AT THE SAME TIME SUPPLYING A LOGIC BIPOLAR STEPPER MOTOR WITH POSITIVE OR INPUT TO THE 0)# MICROCONTROLLER AT NEGATIVE POLARITY 3UCH A CIRCUIT WOULD PIN 2! USE TWO OUTPUT PORT BITS PER CONTROLLED 4HIS TYPE OF INPUT CIRCUITRY HAS TWO DEVICE LINKED TO A l( BRIDGEm TRANSISTOR ADVANTAGES &IRST IT ALLOWS CONNECTION CIRCUIT WITH A SMALL $# MOTOR REQUIR OF HIGHER INPUT VOLTAGES AND SECOND IT ING ONE BRIDGE TWO PORT BITS PER MOTOR PROVIDES ELECTRICAL ISOLATION OF POTEN AND A TWO COIL STEPPER MOTOR BEING TIALLY DANGEROUS INPUT VOLTAGES FROM LINKED TO FOUR OUTPUT PORT BITS THE RELATIVELY EXPENSIVE PROCESSOR #USTOM SOFTWARE ROUTINES TO CONTROL CIRCUITRY STEPPER MOTORS WILL BE DEVELOPED NEXT "EAR IN MIND THAT THE INPUT PROTEC MONTH IN ADDITION TO THE SEGMENT TION CIRCUITRY OF AN ACTUAL 0,# IS LIKELY DISPLAYS ALREADY DISCUSSED TO BE MORE COMPLEX THAN THAT SHOWN HERE OFFERING OVER VOLTAGE AND REVERSE )SOLATINGªHIGHªANDªLOWª POLARITY PROTECTION
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 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 BUT THIS TIME BASED ON OPTOCOUPLER TECHNOLOGY AS ILLUSTRATED BY &IG )N THIS EXAMPLE 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 THUS ENABLING THE PHOTO TRANSISTOR CONNECTED TO THE OUTPUT 4HE TRANSISTOR WITHIN THE OPTO COUPLER IS WIRED AS AN EMITTER
&OR SIMPLE APPLICATION AND VIEW ING OF LOGIC LEVELS THE lLOGICSTATEm AND lLOGICPROBEm COMPONENTS ALLOW LOGIC LOGIC INPUTS TO BE APPLIED AND DISPLAYED RESPECTIVELY ! MOMENTARY ACTION lLOGICTOGGLEm INPUT DEVICE IS ALSO AVAILABLE AND LOGIC PROBES ARE FOUND IN TWO DIFFERENT SIZES 4HE DEFAULT OSCILLATOR FREQUENCY OF -(Z SHOULD BE CHANGED TO -(Z ON EACH INSERTED MICROCONTROLLER THUS ENSURING THAT TIME CRITICAL PROGRAMS OPERATE AT THE DESIRED SPEED 0ROTEUS 63- PROVIDES A VA RIETY OF lANIMATEDm COMPONENTS WHICH MAY BE USED TO GIVE A VISUAL INDICATION OF CIRCUIT OPERATION DUR ING SIMULATION !NIMATED DEVICES INCLUDE SWITCHES ,%$S SEGMENT DISPLAYS LAMPS RELAYS $# MOTORS AND STEPPER MOTORS 4HE lVIRTUAL INSTRUMENTSm FEATURE EMULATES COMMON MEASURING INSTRU MENTS SUCH AS THE AMMETER VOLTMETER SIGNAL GENERATOR AND OSCILLOSCOPE
&IG ª0ROVIDINGªINPUTªISOLATIONªBYªUSINGªANªOPTOCOUPLER
Everyday Practical Electronics, March 2010
Teach-In 2010 2EFER BACK TO 0ART &IG TO SEE THE !T THIS STAGE YOU SHOULD NOW HAVE 4ABLE ,ISTING AND ASSOCIATED lDIGITAL OSCILLOSCOPEm IN ACTION A GOOD APPRECIATION OF THE HARDWARE TEXT FOR MORE DETAILS 9OU ALSO HAVE THE ABILITY TO PAUSE FOUND IN A TYPICAL 0,# AND YOU SHOULD • "YTE LOGICAL COMMANDS q PERFORM THE SIMULATION AND CLICK ON COMPO BE ABLE TO DESIGN SIMPLE LOW VOLT ING COMBINATIONAL LOGIC OPERATIONS ON NENTS IN ORDER TO VIEW INSTANTANEOUS AGE 0)# INTERFACE CIRCUITRY FOR USE IN EACH BIT OF A REGISTER SIMULTANEOUSLY PARAMETERS INCLUDING VOLTAGE CUR EMBEDDED CONTROL APPLICATIONS 4HE • "YTE COMPARISON q COMPARING BYTE RENT AND POWER DISSIPATION q WHICH NEXT SECTION LOOKS AT THE BYTE PROCESS VALUES USING OPERATORS SUCH AS lLESS CAN OFTEN BE SIMPLER THAN PLACEMENT ING CAPABILITIES OF THE 0,# SOFTWARE THANm lEQUAL TOm lNOT EQUAL TOm lGREATER OF NUMEROUS MEASURING INSTRUMENTS WHICH WILL BE USED TO BUILD A DIGITAL $EDICATED MICROELECTRONICS INSTRU COMPARATOR AND ALSO AN ADDER SUB THANm AND THEIR COMBINATIONS • "YTE ARITHMETIC q ADDING AND SUB MENTS ARE ALSO AVAILABLE INCLUDING TRACTER CIRCUIT TRACTING BYTE VALUES WITH SUBTRACTION A MULTIPLE CHANNEL PATTERN GENERATOR USING mS COMPLEMENT ARITHMETIC AND A LOGIC ANALYSER 7ORKINGªWITHªBITSªANDªBYTES 0ROTEUS PROVIDES A BUILT IN SOURCE ,ADDER LOGIC EXCELS AT THE MANIPULA CODE EDITOR PLUS A NUMBER OF BUILT IN TION OF INDIVIDUAL BITS q FOR EXAMPLE "YTEªLOGICALªCOMMANDS ASSEMBLERS INCLUDING -0!3-7). READING INPUTS PERFORMING SIMPLE "YTE LOGICAL COMMANDS PERFORM 5SE OF THIS ASSEMBLER IS AN ALTERNATIVE TO COMBINATIONAL LOGIC OPERATIONS AND COMBINATIONAL LOGIC OPERATIONS SUCH THE -0,!" )$% WHICH HAS BEEN USED OUTPUTTING THE RESULTS #ERTAIN OTHER AS !.$ /2 AND 8/2 ON EACH BIT OF A THROUGHOUT THIS SERIES .OTE THAT THE COMMANDS ALREADY CONSIDERED MAY SOURCE REGISTER COMBINING THE SOURCE -0!3- ASSEMBLER ALSO SUPPLIED WITH BE REGARDED AS EITHER BIT ORIENTED WITH A lMASKm TO PRODUCE A RESULT BYTE 0ROTEUS DOES NOT RECOGNISE 0)# & OR BYTE ORIENTED DEPENDING ON THE #AREFUL CHOICE OF LOGICAL OPERATION SOURCE CODE ÚLES AT THE TIME OF WRIT APPLICATION AND MASK BYTE ALLOWS A VARIETY OF ING ALTHOUGH THE -0!3-7). VERSION 4HIS INCLUDES COUNTERS TIMERS AND OPERATIONS TO BE PERFORMED INCLUDING SEEMS TO HAVE NO SUCH PROBLEM SHIFT REGISTERS ALL OF WHICH MAKE USE SETTING CLEARING INVERTING OR COPYING ! VARIETY OF SOFTWARE DEBUGGING OF A BYTE SIZED lWORKING REGISTERm SELECTED BITS %ACH COMMAND OFFERS A MATCHED FEATURES ARE PROVIDED THROUGH A POW WHICH MAY BE OPTIONALLY USED BY THE ERFUL INTEGRATED DEVELOPMENT ENVIRON PROGRAMMER 2ECALL THAT COMMANDS PAIR OF OPERATIONS WHICH IS SELECTED MENT )$% 4HE lWATCH WINDOWm IS HAVE ALSO BEEN INTRODUCED WHICH CAN BY THE VALUE OF THE MASK BIT PARTICULARLY USEFUL FOR DEBUGGING LADDER LOAD A BYTE SIZED VALUE INTO A REGISTER • !.$ WITH TO COPY THE SOURCE LOGIC PROGRAMS ALLOWING THE CONTENT OF OR COPY A BYTE FROM ONE REGISTER TO AN BIT UNALTERED !.$ WITH TO CLEAR THE SELECTED INTERNAL REGISTERS TO BE VIEWED OTHER THE lPUTIm AND lPUTRm COMMANDS OUTPUT BIT TO ZERO DURING RUN TIME 2EFER BACK TO 0ART RESPECTIVELY ÚRST INTRODUCED IN 0ART • /2 WITH TO SET THE OUTPUT BIT TO &IG TO SEE THIS FEATURE USED WHEN DE 5SE OF BYTE ORIENTED COMMANDS CAN /2 WITH TO COPY THE SOURCE BIT BUGGING A LOW SPEED TIMER APPLICATION GREATLY SIMPLIFY THE WRITING OF CERTAIN /THER )$% FEATURES INCLUDE SINGLE STEP PROGRAMS AND A FURTHER ADVANTAGE IS UNALTERED • 8/2 WITH TO INVERT THE SOURCE BREAKPOINTS SOURCE CODE VIEW PLUS THEIR EFÚCIENT CODING AND HIGH SPEED OF BIT 8/2 WITH TO COPY THE SOURCE BIT REGISTER AND MEMORY VIEW WINDOWS EXECUTION 4HE ONLY POTENTIAL DOWNSIDE )N GENERAL ) HAVE FOUND SIMULATION FOR THOSE NEW TO MICROELECTRONICS AT UNALTERED 4HESE POSSIBILITIES ARE ILLUSTRATED OF ANIMATED ELECTRONIC DEVICES TO BE LEAST IS THE GREATER CONCEPTUAL DIFÚCULTY TROUBLE FREE WITH A COUPLE OF MINOR WHEN WORKING WITH BYTE VALUES COM GRAPHICALLY BY THE EXAMPLE OF &IG EXCEPTIONS &IRST THE CONNECTION OF PARED WITH INDIVIDUAL BITS 4HIS MAY IN WHICH A BINARY SOURCE BYTE ANIMATED $# MOTORS AND STEPPER INCLUDE THE NEED TO WORK WITH A VARIETY l m AT THE CENTRE OF THE ÚGURE MOTORS CAN GIVE lTIMESTEP TOO SMALLm OF NUMBERING SYSTEMS SUCH AS BINARY IS COMBINED WITH A MASK BYTE OF l ERRORS IN MIXED SIMULATIONS )F YOU OCTAL HEXADECIMAL AND DECIMAL IN ADDI m TO PRODUCE THREE DIFFERENT RESULT ENCOUNTER THIS ERROR THEN ONE WORKA TION TO THE REPRESENTATION OF SIGNED AND BYTES BY USING !.$ /2 AND 8/2 OP ROUND MIGHT BE TO REPLACE THE MOTOR UNSIGNED NUMERIC VALUES mS COMPLE ERATIONS AT THE LEFT RIGHT AND BOTTOM RESPECTIVELY WITH AN ANIMATED LAMP OF THE SAME MENT ARITHMETIC FOR EXAMPLE 4HE 0,# SOFTWARE OFFERS TWO DIF RATING IN ORDER TO DEMONSTRATE CIRCUIT 4HE 0,# SOFTWAREmS DEDICATED BYTE OPERATION PROCESSING CAPABILITIES FALL INTO THE FERENT VERSIONS OF EACH COMMAND AS 3ECOND YOU MAY OBSERVE TRANSIENT FOLLOWING CATEGORIES SHOWN IN 4ABLE OSCILLATION OF OUTPUTS SUCH AS RELAY !S USUAL COMMAND NAMES ARE • "YTE DATA TRANSFER q USING THE lPUTIm SUPPLIED IN LOWER CASE AND REGISTER CONTACTS IN MORE COMPLEX SIMULATIONS 4HIS SEEMS TO RELATE TO THE METHOD AND lPUTRm COMMANDS AS DISCUSSED NAMES ARE UPPER CASE .OTICE THAT COM USED BY THE 0)# MICROCONTROLLER TO ABOVE 0LEASE REFER BACK TO 0ART MAND NAMES ENDING WITH lRm REGISTER UPDATE AN OUTPUT PORT IN WHICH /RJLFDO 6\QWD[ DQG $GGUHVVLQJ 0RGH THE OUTPUT PORT IS ÚRST READ IE IN 2SHUDWLRQ PUTTED THEN UPDATED AND ÚNALLY 5HJLVWHU ,PPHGLDWH ! 5HJLVWHU 5HJLVWHU 5HJLVWHU ! 5HJLVWHU RE OUTPUTTED 9OU CAN AVOID THIS $1' DQGL 65&B5(* %<7( '67B5(* DQGU 65&B5(* 65&B5(* '67B5(* UNWANTED FEEDBACK EFFECT BY TEM 25 RUL 65&B5(* %<7( '67B5(* RUU 65&B5(* 65&B5(* '67B5(* PORARILY PLACING lBUFFERm COMPO ;25 [RUL 65&B5(* %<7( '67B5(* [RUU 65&B5(* 65&B5(* '67B5(* NENTS BETWEEN APPROPRIATE OUTPUT PORTS AND ANY EXTERNAL CIRCUITRY 4ABLEª ª"YTE ORIENTEDªLOGICªCOMMANDS
Everyday Practical Electronics, March 2010
Teach-In 2010 PRODUCING THREE OUTPUTS l! "m l! "m AND l! "m ! POSSIBLE PROGRAM IS GIVEN IN ,ISTING WRIT TEN FOR THE 0)# & MICROCONTROLLER 4HE PROGRAM IS RELA TIVELY STRAIGHTFORWARD BEGINNING BY MASKING OFF THE UPPER BITS OF 0ORTS ! AND " STORING THE RESULTS IN AUXILIARY REG ISTERS !58 AND !58 4HESE INTERMEDIATE VAL UES ARE THEN COMPARED &IG ª"ITªMASKINGªWITHªBYTEªLOGICALªCOMMANDS WITH THE THREE POSSIBLE COMPARATOR RESULTS BEING COMBINE A PAIR OF REGISTERS WHILE AN lIm IMMEDIATE COMBINES AN IMMEDIATE WRITTEN IN ORDER TO BITS q OF 0ORT $ VALUE WITH A REGISTER )N EACH CASE 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
"YTEªARITHMETICªINSTRUCTIONS 4HE 0,# SOFTWARE PROVIDES THE ABIL ITY TO PERFORM ADDITION AND SUBTRACTION OF BYTE VALUES WITH AVAILABLE COMMAND OPTIONS SHOWN IN 4ABLE 4HIS IS LIKELY TO BE ONE OF THE LESSER USED FEATURES AND ALSO ONE OF THE MORE
CONCEPTUALLY DIFÚCULT DUE TO ITS USE OF mS COMPLEMENT ARITHMETIC (OWEVER POTENTIAL APPLICATIONS MIGHT INCLUDE CONTROL ORIENTED SYSTEMS IN WHICH A MEASURED PARAMETER SUCH AS TEMPERA TURE PRESSURE OR SPEED OF ROTATION IS COMPARED WITH A SET POINT WITH A SUBTRACTION COMMAND PRODUCING A DEVIATION VALUE 4HIS FEATURE MIGHT FOR EXAMPLE FORM PART OF A 0)$ PROPOR TIONAL INTEGRAL DERIVATIVE CONTROLLER 4HE EXAMPLE OF ,ISTING PERFORMS ADDITION AND SUBTRACTION OF TWO BIT NUMBERS OUTPUTTING THE RESULTS TO TWO BIT REGISTERS 5NFORTUNATELY A FULL DISCUSSION OF mS COMPLEMENT ARITHMETIC IS BEYOND THE SCOPE OF THIS SERIES 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 POSITIVE mS COMPLEMENT NUMBERS ARE ALLOWED
LQFOXGH ) 3/& 'HILQHV 3/& LQVWUXFWLRQV DQGL 3257$ E $8; 0DVN XSSHU ELWV RI 3RUW $
!S THEIR TITLE SUGGESTS BYTE SODFLQJ UHVXOW LQ $8; QXPEHU $
COMPARISON COMMANDS PER DQGL 3257% E $8; 0DVN XSSHU ELWV RI 3RUW % SODFLQJ UHVXOW LQ $8; QXPEHU %
FORM NUMERICAL COMPARISONS BETWEEN TWO VALUES PRODUC HTU $8; $8; 7HVW LI $ % ING A LOGIC VALUE IF THE COM RXW 3257' RXWSXWWLQJ UHVXOW WR ELW RI 3RUW ' PARISON IS TRUE )N FACT YOU MAY RECALL THAT WE BRIEÛY DISCUSSED JWU $8; $8; 7HVW LI $ ! % BYTE COMPARISON COMMANDS IN RXW 3257' RXWSXWWLQJ UHVXOW WR ELW RI 3RUW ' 0ART MAKING USE OF THE lEQIm OWU $8; $8; 7HVW LI $ % EQUAL IMMEDIATE COMMAND RXW 3257' RXWSXWWLQJ UHVXOW WR ELW RI 3RUW ' TO TEST AN IMMEDIATE VALUE AND A REGISTER AS PART OF THE LIGHT HQGS 0DUNV HQG RI 3/& SURJUDP CHASER PROGRAM OF ,ISTING ,ISTINGª ª!ª BITªCOMPARATORªPROGRAMª ,ST ? ASM 4HE FULL RANGE OF BYTE COM 6\QWD[ DQG $GGUHVVLQJ 0RGH PARISON COMMANDS AND OPTIONS $ULWKPHWLF 2SHUDWLRQ ARE GIVEN IN 4ABLE 5HJLVWHU ,PPHGLDWH ! 5HJLVWHU 5HJLVWHU 5HJLVWHU ! 5HJLVWHU !S AN EXAMPLE WE WILL DE $GG DGGL 65&B5(* %<7( '67B5(* DGGU 65&B5(* 65&B5(* '67B5(* SIGN A DIGITAL COMPARATOR WHICH 6XEWUDFW VXEL 65&B5(* %<7( '67B5(* VXEU 65&B5(* 65&B5(* '67B5(* WILL COMPARE TWO BIT NUM BERS REFERRED TO AS l!m AND l"m 4ABLEª ª"YTEªARITHMETICªCOMMANDS &RPSDUH 2SHUDWLRQ
6\QWD[ DQG $GGUHVVLQJ 0RGH 5HJLVWHU ,PPHGLDWH ! 5HJLVWHU
5HJLVWHU 5HJLVWHU ! 5HJLVWHU
/HVV WKDQ
OWL 65&B5(* %<7( '67B5(*
OWU 65&B5(* 65&B5(* '67B5(*
/HVV WKDQ RU HTXDO
OWHL 65&B5(* %<7( '67B5(*
OWHU 65&B5(* 65&B5(* '67B5(*
(TXDO
HTL 65&B5(* %<7( '67B5(*
HTU 65&B5(* 65&B5(* '67B5(*
1RW HTXDO
QHL 65&B5(* %<7( '67B5(*
QHU 65&B5(* 65&B5(* '67B5(*
*UHDWHU WKDQ
JWL 65&B5(* %<7( '67B5(*
JWU 65&B5(* 65&B5(* '67B5(*
*UHDWHU WKDQ RU HTXDO
JWHL 65&B5(* %<7( '67B5(*
JWHU 65&B5(* 65&B5(* '67B5(*
4ABLEª ª"YTEªCOMPARISONªCOMMANDS
TO BE IN THE DECIMAL RANGE TO AND NEGATIVE DECIMAL NUMBERS ARE BETWEEN AND 4HE MOST SIGNIÚCANT BIT OF THE SUBTRACTED RESULT INDICATES THE SIGN 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 AND THEN ADDING TO THE
Everyday Practical Electronics, March 2010
Teach-In 2010 LQFOXGH ) 3/& 'HILQHV 3/& LQVWUXFWLRQV DQGL 3257$ E $8; 0DVN XSSHU ELWV RI 3RUW $ SODFLQJ UHVXOW LQ $8; QXPEHU $
DQGL 3257% E $8; 0DVN XSSHU ELWV RI 3RUW % SODFLQJ UHVXOW LQ $8; QXPEHU %
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
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 WHICH EXTENDS THE CONCEPT OF BYTE PROCESSING TO INCORPORATE SIMPLE STATE BASED SYSTEMS
LQFOXGH ) 3/& 'HILQHV 3/& LQVWUXFWLRQV DQG VHTXHQFHU GDWD KHOG LQ ((3520 VHH RUJ + VHFWLRQ
3EQUENCER BASEDª SYSTEMS
OG 3257$ (QDEOH LQSXW VLQJOH VKRW VHTXHQFH
4HE BUILT IN SEQUENCER FACILITY MAKES IT EASY TO CREATE COMPLEX ANIMATED SEQUENCES WITH USER DEÚNED DATA IN %%02/- MEMORY BEING SENT AT REGULAR INTERVALS TO THE CHOSEN DESTINATION REG ISTER 3INGLE SHOT OR REPEATING SEQUENCES MAY BE PRODUCED WITH UP TO STEPS DEPEND ING ON THE CAPACITY OF THE %%02/- MEMORY WITHIN THE CHOSEN MICROCONTROLLER 4YPICAL APPLICATIONS OF THE SEQUENCER INCLUDE TOYS FES TIVE DECORATIONS SHOP SIGNS RUNNING LIGHT DISPLAYS AND MANY MORE BESIDES .OTE THAT THE & ! AND & ! MICROCON TROLLERS HAVE BYTES OF BUILT IN %%02/- WHILE THE & & AND & OFFER BYTES 0LEASE REFER BACK TO 0ART 4ABLE FOR A DETAILED LIST OF MICROCON TROLLER FEATURES 7RITING SEQUENCER BASED PROGRAMS IS A LITTLE DIFFERENT TO THAT SEEN SO FAR SINCE THE USERmS PROGRAM IS EFFECTIVELY MERGED WITH SEQUENCER DATA CONTAINED WITHIN THE 0,# HEADER ÚLE DURING ASSEMBLY 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 THE HEADER ÚLE IS EDITED SO THAT IT CONTAINS THE REQUIRED SEQUENCER DATA &INALLY A SUITABLE LADDER LOGIC PROGRAM IS WRITTEN AND ASSEMBLED IN THE NOR MAL WAY &OR THE SAKE OF SIMPLIC ITY SAMPLE SEQUENCER DATA
VHT G 26&/ 6HTXHQFHU ZLWK VWHSV +] FORFN LQSXW 7 PV 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 +] FORFN LQSXW 7 PV 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 FRPPDQG 8S WR E\WHV DUH DYDLODEOH ZLWK WKH 3,& ) 7UDIILF OLJKW GDWD LV VKRZQ EHORZ GH % 6WHS 5HG GH % 6WHS 5HG $PEHU GH % 6WHS *UHHQ RI GH % 6WHS *UHHQ RI GH % 6WHS *UHHQ RI GH % 6WHS *UHHQ RI GH % 6WHS *UHHQ RI 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 +] 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
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 WITH A SIMPLE EXAMPLE SHOWN IN ,ISTING 4HIS PROGRAM PRODUCES A NON REPEAT ING OUTPUT SEQUENCE ON 0ORT " WHICH IS TRIGGERED BY AN ACTIVE HIGH ENABLE INPUT CONNECTED TO BIT OF 0ORT ! 4HIS ENABLE INPUT MUST BE HELD CONTINUOUSLY HIGH DURING THE SEQUENCE CAUSING THE SEQUENCER TO BE RESET WHEN IT GOES LOW 4HE SEQUENCER ITSELF IS DEÚNED US ING THE lSEQm COMMAND 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 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 AS SHOWN IN ,ISTING )N THIS CASE THE lSEQUENCER ÚNISHEDm STATUS BIT l3%1&). m IS ÚRST INVERTED AND THEN USED AS THE ENABLE INPUT TO THE SEQUENCER !T ÚRST THE SEQUENCER IS ENABLED BECAUSE IT IS NOT YET ÚNISHED BUT THE STATUS BIT BECOMES SET ON COMPLE TION 4HIS RESETS THE SEQUENCER CAUSING THE SEQUENCER TO RESTART 4HE SEQUENCER FEATURE IS BEST SUITED TO APPLICATIONS NOT REQUIRING ANY GREAT DECISION MAKING CAPACITY 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 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 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 YOU SHOULD DOWNLOAD THE ÚLE CONTAINING ZIPPED PROGRAM LISTINGS FOR 0ART OF THE SERIES AS USUAL 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 WHICH HAVE BEEN MODIÚED TO INCLUDE THE TRAFÚC LIGHT SEQUENCER DATA WITH THE RELEVANT SEQUENCER CONTENT FOR THE 0)# & MICROCON
4
TROLLER BEING SHOWN IN ,ISTING .OTICE THAT %%02/- DATA IS SPECIÚED AS A SERIES OF DATA BYTES STARTING AT HEXA DECIMAL MEMORY LOCATION 4HE ACTUAL SEQUENCER DATA CONSISTS OF EIGHT STEPS WITH THE RED AMBER AND GREEN TRAFÚC LIGHTS ASSUMED TO BE CONNECTED TO THE RIGHTMOST SEQUENCER OUTPUT BITS !SSUMING THAT EACH STEP LASTS FOR ONE SECOND THEN WE CAN SEE THAT THE GREEN OUTPUT WILL BE ACTIVE FOR ÚVE SECONDS WITH ALL OTHER STATES LASTING ONE SECOND EACH 4HE SEQUENCER WILL OPERATE IN CONTINUOUS MODE AUTOMATICALLY RE TURNING TO STATE AFTER THE ÚNAL STATE THUS GIVING AN AMBER TO RED TRANSITION ! SUITABLE TRAFÚC LIGHT PROGRAM IS GIVEN IN ,ISTING THIS TIME WRITTEN FOR THE 0)# & WITH LOW VOLTAGE PROGRAMMING ENABLED .OTICE THAT CONTINUOUS OPERATION HAS BEEN ENABLED AND AN ADDITIONAL ENABLE INPUT HAS BEEN ADDED LINKED TO BIT OF 0ORT ! 4HE UPDATED SOFTWARE SUPPLIED IN 6ERSION TURNS OFF THE SEQUENCER OUTPUT WHEN IT IS DISABLED AND MAKES OTHER MINOR CORRECTIONS 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 AS SHOWN IN &IG &OR OTHERS THE PROGRAM MAY EASILY BE ADAPTED TO RUN ON SUPPORTED HARD WARE PLATFORMS 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 INCLUDING ELECTRONIC TOYS AND DECORATIONS $EVELOPMENT OF NEW SYSTEMS AND APPLICATIONS CAN BE BOTH INTERESTING AND CREATIVE AND WILL ALSO GIVE YOU
PLENTY OF OPPORTUNITIES TO PRACTISE YOUR HARDWARE DESIGN SKILLS
3UMMARY 7E HAVE COVERED A LOT OF GROUND THIS MONTH RANGING FROM HARDWARE DESIGN AND THE USE OF COMPUTER BASED SIMULA TION TO BYTE ORIENTED PROGRAMMING AND EVEN SIMPLE SEQUENCER BASED SYSTEMS 3EVERAL OF THESE TOPICS WILL BE EXPANDED IN THE NEXT AND ÚNAL PART OF THE SERIES 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 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 WATCHDOG TIMER 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 INCLUDING SEG MENT DISPLAYS $# MOTORS AND STEP PER MOTORS WITH THE POSSIBILITY OF DIGITAL POSITION MEASUREMENT USING 'RAY CODE 7E WILL ALSO REVISIT THE TRAFÚC LIGHT APPLICATION ONE LAST TIME 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-
Everyday Practical Electronics, March 2010
HandsOn Technology Low Cost 8051C 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 8051C 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
http://www.handsontec.com
Teach-In 2010
TEACH-IN 2010
LADDER LOGIC PROGRAMMING FOR THE PIC MICRO Part 6: Customising and Extending the Software By Walter Ditch
T
! "
#
$
%
! #
& ' ( ) * + ,! #
! . "
Everyday Practical Electronics, April 2010
/ # Everyday Practical Electronics 0www. epemag.com/1 # 2
03 ' ' 41
!
* ! ' 5 . 6 .7 8, ! # 6 0www. microchip.com/mplab/1
396 ,
Changing default settings
" 0
% % 1 ,
! 6 : 6 ;
<
9 %
% "
! ;
. %
Reviewing input/output port settings .
! '5=>>? .
7 @
. 6 A 0 ! 1
!
# !
45
Teach-In 2010
! 9 "
'5=>>? )4 0 . 7 ,1 '5 0 81
$
R S 0#A 9. #A 97 #A 9 #A 98 #A 9,
1 R'S
R4S . ! 5 ' !
'5=5)?
$8# ! 0A % = ' + 0 ' : S4T1 !
! 1
S
$8#
#
$8# # '5=5)?. ! '>
. % '%
s P IC16F627A,
PIC16F628A, PIC'5=5M>. N * # *: :# *: ,' 6 *: s '5=>> N ' ) * # *: :# *: *9 *: 99 *: 6 *: .:9, .8 *:4 s '5=>>? N ' ) * # *: :# *: ,' 6 *: *: .:9, $ (7 * 7 .
;
#
# ' ) 0 '1 #
setports
movlw 0x1f ; Set bits 0-4 as inputs (1 = input, 0 = output) movwf TRISA ; Set TRISA register (Port A = all inputs) .<8 movlw 0x00 ; Set bits 0-7 as outputs @ movwf TRISB ; Set TRISB register (Port B = all outputs)
! O 0#
M6@Q 0'Âľ 1
R
S 1 !
'
U (
# $8# %
" @ $8# %
; # %
$8#
<* 07 $8# A,+ '5=>>? ! @ # !
1 " $8#
% Using the watchdog timer S - # 6 0*9 @1
%
!
Modifying device R S
, @ Optimising program code 0$8#1 ; # % # !
-
&
A Q R S R
- s # S - s
R A s 6 ! S &
46
Everyday Practical Electronics, April 2010
Teach-In 2010 Methods of reducing program size
include "16F887.PLC"
; Defines PLC instructions
putr
; Transfer Port A to Port C
PORTA, PORTC
Even the simplest of ladder logic programs is likely ld PORTB, 0 ; Read Port B bit 0 out PORTD, 0 ; Output to Port D bit 0 to use 130 to 180 program ld PORTB, 1 ; Read Port B bit 1 words when assembled, out PORTD, 1 ; Output to Port D bit 1 due mainly to the overld PORTB, 2 ; Read Port B bit 2 head introduced by the out PORTD, 2 ; Output to Port D bit2 # not be a problem in most ; etc. scenarios, since supported endp ; End of PLC program PIC microcontrollers are available with program ! " # $ memory sizes in the range ' >% 0A % # ' ) ! 5 ) â&#x20AC;&#x2DC;chainâ&#x20AC;&#x2122; multiple shift registers, with Q 1 alternative ways to transfer data from the data shifted out by a previous A simple way to keep track of command being left in the W regis
program memory usage is to read the Another possibility for moderate ter, automatically becoming the data summary information at the end of the % ! . R S 0 use of the output produced by a previ-
R S ! 1 . ! ! M M 0= S'41 is shown below for the PIC16F887 #
- were cascaded to create a custom der logic programs, but can also offer < A potential disadvantage of this an alternative to manually reading the Program Memory Words Used: 181 technique is the possibility of making Program Memory Words Free: 8011 # % - program operation rather cryptic, so While it is vital to keep track of proach is to realise that the majority of it should perhaps be used sparingly, the size of your assembled machine commands leave their result, or their
! code program, it is equally impor- $ % 0$1 tant to keep your source code files # ! It is always a good idea to make . ! liberal use of comments, in order !
nario, the softwareâ&#x20AC;&#x2122;s default alloca !
â&#x20AC;&#x2DC;ldâ&#x20AC;&#x2122; command, which simply leaves its ! .(_4
# .(_? 0 5M 1 others to understand your programs, $ .
= and in any case will be removed at â&#x20AC;&#x2DC;outâ&#x20AC;&#x2122; command takes this value from the W register, sending it to the speci- # - Currently, allocated general purpose commands such as counters, timers any effect on the program size, as these and shift registers all offer similar
will only be assembled if they are actu- functionality, giving the possibility of 58N? 0 ! @ 1 3 that additional customisation features ' ' 4 9 " 3 ' ' 4 A ! + >
! 0^ S'41 " %
80 program words to the minimum ; Unused Ram locations 6DH â&#x20AC;&#x201C; 74H program size, due mainly to the use of lookup tables EQU H'75' ; Block of eight user defined variables (start) 0 TEMP0 TEMP1 EQU H'76'
1 TEMP2 EQU H'77' One possibility for code TEMP3 EQU H'78' TEMP4 EQU H'79' EQU H'7A' the use of a single byte-ori- TEMP5 EQU H'7B' ented command in place TEMP6 EQU H'7C' ; Block of eight user defined variables (end) of several bit-oriented TEMP7 . R S STEMP EQU H'7D' ; Stores Status register value during an Interrupt or â&#x20AC;&#x2DC;putrâ&#x20AC;&#x2122; command, for ; Service Routine (ISR) ! WTEMP EQU H'7E' ; Stores W register value during an ISR the same task as several LOGIC EQU H'7F' EQU H'7F' â&#x20AC;&#x2DC;ldâ&#x20AC;&#x2122; and â&#x20AC;&#x2DC;outâ&#x20AC;&#x2122; instructions LASTRAM Defining a block of eight user defined variables. 0 1 . % & ' ( )
Everyday Practical Electronics, April 2010
4
Teach-In 2010 include "16F627.PLC"
Adding custom extensions to the software
; Defines PLC instructions ; Start of main program
call
SUB1
; Call subroutine 1 unconditionall
This section will consider three different cusgoto loop ; Go to start of scan loop tomisation scenarios, each of which will add a sig; Put subroutine definitions after main nificant new capability ; program, but before 'endp' statement. to the software. Topics ; Subroutine 1 (called al a s) considered will be: SUB1 puti b'00110011', PORTB ; Displa 33H on Port B Conditional program s return ; Return to main program execution endp ; End of PLC program Code conversion s Listing 6.4. Mixing assembly language and ladder logic (Lst6_4.asm) s Finite state machine. (Recall from the introduction that be â&#x20AC;&#x2DC;nestedâ&#x20AC;&#x2122; up to eight levels deep. # ! 5 + (However, bear in mind that the these new features are included with creates an additional eight auxiliary PLC software makes use of inter- the updated version of the PLC softregisters called TEMP0â&#x20AC;&#x201C;TEMP7, hence rupts, hence using the stack to hold
increasing the number of available return addresses from interrupt the series.) ! 5M ')> 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
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 assembly 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 â&#x20AC;&#x2DC;callâ&#x20AC;&#x2122; and â&#x20AC;&#x2DC;returnâ&#x20AC;&#x2122; instructions, which would allow a more structured approach to program 5 M example. The program may be seen to contain three assembly language statements which are, in order â&#x20AC;&#x2DC;callâ&#x20AC;&#x2122;, â&#x20AC;&#x2DC;gotoâ&#x20AC;&#x2122; and â&#x20AC;&#x2DC;returnâ&#x20AC;&#x2122;, plus two ladder logic statements â&#x20AC;&#x2DC;putiâ&#x20AC;&#x2122; and â&#x20AC;&#x2DC;endpâ&#x20AC;&#x2122;. There is also the â&#x20AC;&#x2DC;includeâ&#x20AC;&#x2122; assembler directive, plus the R9(7'S in the left margin in order to identify Subroutines may be thought of as small self-contained sub-programs, which are called from the main program, 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
4
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 placed in the left margin next to the # 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 scan loop, in order to avoid a soft % R Â&#x20AC; S (trying to return from a subroutine which hasnâ&#x20AC;&#x2122;t actually been called in the proper way). This is achieved by placing a â&#x20AC;&#x2DC;goto loopâ&#x20AC;&#x2122; statement after the main program, but before the sub # statement must still be the â&#x20AC;&#x2DC;endpâ&#x20AC;&#x2122; macro statement, which contains an additional â&#x20AC;&#x2DC;goto loopâ&#x20AC;&#x2122; statement, plus the required â&#x20AC;&#x2DC;ENDâ&#x20AC;&#x2122; of program assembler directive. While this example does demonstrate 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 â&#x20AC;&#x2DC;ifâ&#x20AC;Śthenâ&#x20AC;Śelseâ&#x20AC;&#x2122; style decisions.
Scenario 1 â&#x20AC;&#x201C; conditional code execution In the previous section, we saw just how easy it is to add subroutines to our ladder logic programs. The â&#x20AC;&#x2DC;callâ&#x20AC;&#x2122; and â&#x20AC;&#x2DC;returnâ&#x20AC;&#x2122; assembly language statements, when used appropriately, allow the use of subroutines within ladder logic programs. On the downside, we had the added complexity of â&#x20AC;&#x2DC;labelsâ&#x20AC;&#x2122; in the left margin, plus the need to add a â&#x20AC;&#x2DC;jp loopâ&#x20AC;&#x2122; statement at the end of the main program, and before the 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 5 Â&#x2026; At this stage, you may like to refer back to Fig.2.7 and associated text ) macro text substitution feature of the assembler. The essential point to understand is that custom macros allow us to create our own new commands, bly language, and then converted to machine code by the assembler. As its name suggests, the â&#x20AC;&#x2DC;subdefâ&#x20AC;&#x2122; 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 argument is automatically placed into the left margin by text substitution, thus eliminating the need to place your own labels. The second feature of the
Everyday Practical Electronics, April 2010
Teach-In 2010 ; The 'subdef' macro defines a subroutine ; ( hich should end ith a 'return' statement) subdef
macro goto
subdef arg1 loop
subdef arg1 endm
; Go to start of scan loop ; Put label in left margin for call instruction ; 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
This logical structure is important, as will now be discussed.
Tips for using subroutines with ladder logic
In a typical high level programming language, ccall macro ccall arg1 subroutines are deandl 0 01 ; Test least significant bit of W reg. signed to be called btfss STATUS, ; Skip subroutine if LSB is clear many times from the call ccall arg1 ; Call subroutine endm ; End of macro main program, thus offering a reusable li , brary of pre-tested code. include "16F887.PLC" ; Defines PLC instructions The purpose is slightly different in our ladder ; Start of main program logic implementation, call SUB1 ; Call subroutine 1 unconditionall with subroutines offering a more structured program ld PORTA, 0 layout, plus the ability to ccall SUB2 ; Call subroutine 2 if bit 0 of Port A 1 conditionally execute a block of code if a tested ld not PORTA, 0 condition is true. ccall SUB3 ; Call subroutine 3 if bit 0 of Port A 0 In general, some care is ; End of main program needed when designing subroutine-based ladder ; Put subroutine definitions after main logic programs, to ensure ; program, but before 'endp' statement. that individual register bits, such as inputs and subdef SUB1 ; Subroutine 1 is called al a s outputs, are only updated puti b'00110011', PORTC ; Displa 0 33 on Port C return ; Return to main program once per scan cycle. For example, if an output is subdef SUB2 ; Subroutine 2 is called if PORTA,0 1 set to 1 at the start of the puti b'00001111', PORTD ; Displa 0 0F on Port D scan loop and later set to return ; Return to main program 0, the output will appear to oscillate as the scan subdef SUB3 ; Subroutine 3 is called if PORTA,0 0 cycle repeatedly executes. puti b'11110000', PORTD ; Displa 0 F0 on Port D return ; Return to main program Thus, any â&#x20AC;&#x2DC;complementaryâ&#x20AC;&#x2122; actions contained endp ; End of PLC program within subroutines should Listing 6.6. A simple conditional subroutine program (Lst6_6.asm) be called by mutually exclusive test conditions, as macro is a â&#x20AC;&#x2DC;jp loopâ&#x20AC;&#x2122; command, which The example of Listing 6.6 illusis automatically placed at the start of found in an ifâ&#x20AC;Śthenâ&#x20AC;Śelse program each subroutine, hence forcing the â&#x20AC;&#x2DC;ccallâ&#x20AC;&#x2122; and â&#x20AC;&#x2DC;subdefâ&#x20AC;&#x2122; macros, plus pre- structure. Available subroutine related com viously considered â&#x20AC;&#x2DC;callâ&#x20AC;&#x2122; and â&#x20AC;&#x2DC;returnâ&#x20AC;&#x2122; of the main scan loop. Thus, we have assembly language commands, to mands are summarised in Table 6.1. eliminated both of the previously mentioned subroutine issues, by use of an extremely simple macro. The second â&#x20AC;&#x2DC;ccallâ&#x20AC;&#x2122; macro provides a conditional subroutine call feature, which is an alternative to the unconditional subroutine call discussed previously. The idea is that the result of a previous command, such as a â&#x20AC;&#x2DC;ldâ&#x20AC;&#x2122; or â&#x20AC;&#x2DC;ld_notâ&#x20AC;&#x2122;, is tested by the ccall statement, with the subroutine being called, only if the command returns a true result (as indicated by a logic ' $ register).
Everyday Practical Electronics, April 2010
implement conditional and unconditional subroutines. : three subroutines, SUB1, SUB2 and SUB3, which are placed after the main
R S statement. The main program consists
; tine, followed by conditional calls to subroutines two and three. Notice that the conditional calls are complementary, based on the state of bit 0 of Port A, so only one conditional subroutine call will be made in a single scan loop.
Scenario 2 â&#x20AC;&#x201C; code conversion The â&#x20AC;&#x2DC;retlwâ&#x20AC;&#x2122; assembly language instruction may be used as an alternative to the â&#x20AC;&#x2DC;returnâ&#x20AC;&#x2122; statement seen earlier, offering the facility to place a literal $ from a subroutine. This feature commonly allows subroutines to return a result to the calling program, or possibly a success/failure result code. However, with some clever coding, the retlw command may be persuaded to perform code conversion, transforming binary values into a variety of other
4
Teach-In 2010 upper four bits of the binary value to call SUBROUTINE Call a named subroutine unconditionally (assembly language zero, thus preventstatement). ing a potential table return overflow. Return to the main program, at the line following the subroutine call (assembly language statement). One slightly undesirable feature of ccall SUBROUTINE Call a named subroutine conditionally, if the previous command this technique is returns a true result (in least significant bit of W register). that the lookup table subdef SUBROUTINE Define a named subroutine. subroutine becomes a permanent feature Table 6.1. Subroutine-related commands of the assembled program, even if the ; The 'bin27seg' macro calls the follo ing subroutine hich must be placed in ; the first 256 locations of program memor associated macro is not used. This ; 7 segment displa look up table inevitably leads to ; subroutine a small increase in bin27seg sub1 andl 0 0f ; Mask off upper 4 bits of W to prevent table the minimum size of ; overflo assembled machine add f PCL ; Add W to LSB of program counter and return ; ith look up value in W code programs, but retl b'00111111' ; Displa '0' this should not be retl b'00000110' ; Displa '1' retl b'01011011' ; Displa '2' given that up to 8k retl b'01001111' ; Displa '3' of program memory retl b'01100110' ; Displa '4' is available in supretl b'01101101' ; Displa '5' retl b'01111101' ; Displa '6' ported PIC microretl b'00000111' ; Displa '7' controllers. It should retl b'01111111' ; Displa '8' also be noted that retl b'01100111' ; Displa '9' any lookup table retl b'01110111' ; Displa 'A' subroutines must retl b'01111100' ; Displa 'B' be placed in the retl b'00111001' ; Displa 'C' first 256 locations retl b'01011110' ; Displa 'D' retl b'01111001' ; Displa 'E' of program memory, retl b'01110001' ; Displa 'F' in order to prevent memory page errors ; Macro definition for binar to segment displa conversion. when the W register is added to the lower bin27seg macro bin27seg arg1, bin27seg arg2 byte of the program movf bin27seg arg1, W ; Put binar value into W call bin27seg sub1 ; Call lookup subroutine counter. mov f bin27seg arg2 ; Put result in destination register Fig.6.1 shows a endm ; End of Binar to 7 segment potential application ; displa converter macro of this technique to Listing 6.7. 6.7. Binary-to-7-segment display andmacro. macro Listing inary to seven segment displaysubroutine subroutine and drive a single 7-segrepresentations. This is an extremely register, which causes the PIC micro ment display, with the associated propowerful technique, with potential to jump forwards in program memory gram shown in Listing 6.8. applications including: As can be seen, the resulting binary hence returning the converted value to 7-segment display program is res 7-segment displays markably simple, from a programming the W register. s Gray code (position measurement) in The example of Listing 6.7 shows perspective at least, consisting of a s Stepper motor control a subroutine used to convert a 4-bit single line of code. The real complexbinary value to a format capable of ity is hidden in the lookup table and s Binary encoders and decoders. The basic idea is to create a sub- driving a directly connected 7-segment Clearly, the method used here routine which contains a lookup display, plus the associated macro with 7-segment displays may easily table consisting of a series of retlw This example creates a new â&#x20AC;&#x2DC;bin- be applied to other code conversion statements, each of which will return a particular value to the calling 27segâ&#x20AC;&#x2122; (binary to seven segment) scenarios. With this in mind, a diverse program. We then place our initial macro definition, which in turn selection of code conversion macros binary value (to be converted) into calls the â&#x20AC;&#x2DC;bin27seg_sub1â&#x20AC;&#x2122; subroutine has been developed, covering topics the W register prior to calling the to perform the actual code conver- including position measurement (Gray subroutine. The subroutine begins sion. Notice the use of bit masking code), stepper motor control, plus biby adding the value contained in the at the start of the subroutine as a nary encoders and decoders, as given W register to the program counter data validation check, forcing the in Table 6.2. Command
Function
Everyday Practical Electronics, April 2010
Teach-In 2010 First, the priority encoder (pencode) macro provides the inverse operation 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-segment display. The latter command allows â&#x20AC;&#x2DC;packedâ&#x20AC;&#x2122; 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
5 T output port bits, since it requires two Fig.6.1. Displaying a binary value on a 7-segment display 8-bit output ports, include "16F627.PLC" ; Defines PLC instructions just to drive a pair of 7-segment disbin27seg PORTA, PORTB ; Displa binar code from PORTA bits 0 3 plays. A multiplexed ; on 7 segment displa connected to 7-segment display is ; Port B bits 0 6 (bit 7 is unused) endp ; End of PLC program in its use of output port bits, as illusListing 6.8. A simple binary-to-7-segment display program (Lst6_8.asm) trated by Fig.6.2. Command Function U n f o r t u n a t e l y, bin27seg SRC_REG, DST_REG Use a 4-bit binary value to drive a directly connected seven segment increased I/O efficiency comes at the display. price of increased bin2gray SRC_REG, DST_REG Convert a 1â&#x20AC;&#x201C;4 bit binary value to Gray code. complexity of the gray2bin SRC_REG, DST_REG Convert a 1â&#x20AC;&#x201C;4 bit Gray code value to binary. software. As disdecode SRC_REG, DST_REG cussed last month, a Use a 1â&#x20AC;&#x201C;3 bit binary code to set a single output bit (0â&#x20AC;&#x201C;7). multiplexed display pencode SRC_REG, DST_REG Produce a priority encoded 3-bit binary value, equivalent to the operates by briefly highest set input bit (0â&#x20AC;&#x201C;7). activating each digit step SRC_REG, DST_REG Use a 2-bit binary value to drive a 2-pole stepper motor in full step in a rapidly repeating mode. sequence, thus giving hstep SRC_REG, DST_REG Use a 3-bit binary value to drive a 2-pole stepper motor in half step the illusion that all mode. digits are simultaneously illuminated. swap SRC_REG, DST_REG Swap nibbles between source and destination registers. A suitable control Table 6.2. Available code conversation macros and related commands program is shown in include "16F887.PLC" ; Defines PLC instructions Listing 6.10. Donâ&#x20AC;&#x2122;t worry if puti 0 AB, AU 0 ; Packed digit displa buffer this seems complex, since the program bin27seg AU 0, PORTC ; Displa lo er nibble on Port C can be broken down s ap AU 0, AU 1 ; S ap nibbles from displa buffer into a number of bin27seg AU 1, PORTD ; Displa upper nibble on Port D smaller sub-sections, each of which is endp ; End of PLC program relatively simple to Listing 6.9. Using packed binary values with 7-segment displays (Lst6_9.asm) understand. First, registers AUX0 and AUX1 Most of these new commands make can review details of their implementhe same use of lookup tables as the tation by viewing the appropriate are used as a display buffer, holding bin27seg command, differing mainly ! @ the four digits in packed binary form. in the number of input bits allowed, note that a couple of these new mac- Bit 0 of Port A acts as a display enand the binary values returned. You ros are coded slightly differently: able input, causing the output to be
Everyday Practical Electronics, April 2010
Teach-In 2010 ; Multiple ed LED Displa include "16F887.PLC"
; Defines PLC instructions
puti puti
0 12, AU 0 0 34, AU 1
; AU 0 ; AU 0 ; AU 1
ld out ld out
OSCH, AU 2, OSCH, AU 2,
; ; ; ; ; ;
ld ccall
PORTA, 0 SCA ROW
; Scan ro s if bit 0 of Port A
ld not ccall
PORTA, 0 BLA ED
; Disable ro
ld ccall
PORTD, 0 DIGIT1
; Displa
digit 1 if enabled
ld ccall
PORTD, 1 DIGIT2
; Displa
digit 2 if enabled
ld ccall
PORTD, 2 DIGIT3
; Displa
digit 3 if enabled
ld ccall
PORTD, 3 DIGIT4
; Displa
digit 4 if enabled
subdef decode return
SCA ROW AU 2, PORTD
; Send digit enable pulses to Port D
subdef puti return
BLA ED 0 00, PORTD
; Turn off displa driver transistors ; Blank 7 segment displa
4 0 5 1
AU 1 hold 4 digits to be displa ed L.H. 2 digits of displa R.H. 2 digits of displa
AU 2 bits 0 1 aveforms are decoded to produce digit scan pulses (see also 'SCA ROW' subroutine) Read 8 ms aveform Send to bit 0 of register AU 2 Read 16 ms aveform Send to bit 1 of register AU 2
; Conditional subroutine calls 1
scan if bit 0 of Port A
; Subroutine definitions
subdef DIGIT1 s ap AU 0, bin27seg AU 3, return
AU 3 PORTC
; ; ; ;
Displa digit 1 subroutine S ap nibbles of AU 0 into AU 3 Send to 7 segment displa Return from subroutine
subdef DIGIT2 bin27seg AU 0, return
PORTC
; Displa digit 2 subroutine ; Send to 7 segment displa ; Return from subroutine
0
four display driver transistors, one after another, but note that the SCANROW subroutine is only called if the display is enabled – 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 transistors (Fig.6.2), thus disabling the display. During normal operation, the ‘decode’ macro within the SCANROW subroutine 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 output bits of Port D are also used to conditionally call a further four subroutines (DIGIT1, DIGIT2, DIGIT3 and DIGIT4), which ensures 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 considered earlier.)
Controlling stepper motors
Two new macros have been provided AU 3 to control two-pole PORTC stepper motors, in either full-step or half -step mode. The ‘step’ subdef DIGIT4 ; Displa digit 4 subroutine command takes a twobin27seg AU 1, PORTC ; Send to 7 segment displa bit binary input, usreturn ; Return from subroutine ing it to output the endp ; End of PLC program sequence 0011, 0110, 1100, 1001. Similarly, Listing 6.10. A multiplexed 7-segment display driver program with blanking control the ‘hstep’ macro uses in a repeating sequence. These oscilla- a three-bit input code to generate the blanked when it is low, or enabled tor bits produce a two-bit binary count sequence 0001, 0011, 0010, 0110, when high. (00, 01, 10, 11, 00, ...) which repeats 0100, 1100, 1001. As its name suggests, The next section of the program copmore than 50 times per second. This half-step mode uses intermediate ies two of the higher order oscillator count is ‘decoded’ by the SCANROW states, causing the motor to move in bits to register AUX2, which will be subroutine, to enable each of the smaller angular increments. used to enable the four display digits subdef DIGIT3 s ap AU 1, bin27seg AU 3, return
; ; ; ;
Displa digit 3 subroutine S ap nibbles of AU 1 into AU 3 Send to 7 segment displa Return from subroutine
Everyday Practical Electronics, April 2010
Teach-In 2010
; < ! with suitable optocoupler hardware. s ap OSCL, AU 0 ; S ap nibbles from OSCL to AU 0 Gray code uses a spestep AU 0, PORTB ; Send step se uence to bits 0 3 of Port B cial binary counting sequence, such that only endp ; Marks end of PLC program one bit changes at any = ( " # $ time as the disc rotates. This property elimiinclude "16F627.PLC" ; Defines PLC instructions nates the potential for ld PORTA, 0 ; Read Port A bit 0 (Count do n input) unwanted intermediate or PORTA,1 ; OR ith Port A bit 1 (Count up input) states as the disc rotates. and OSCL,1 ; Clock input to up do n counter The latest version ctr ud 0, d'7', PORTA, 1, PORTA, 2 of the PLC software ; Up do n counter 0, final value 7 provides two new com; Direction Port A bit 1 mands related to Gray ; Reset Port A bit 2 code. The â&#x20AC;&#x2DC;bin2grayâ&#x20AC;&#x2122; ; Up do n counter orking register CUD0 command generates a hstep CUD0, PORTB ; Send half step se uence to bits 0 3 of Port B Gray code value based on a binary input, endp ; Marks end of PLC program while the corresponding â&#x20AC;&#x2DC;gray2binâ&#x20AC;&#x2122; routine = ( " # $ generates a binary code A simple full-step program is shown register CUD0 (address 0x5C), which based on a Gray-coded input. It is will allow the desired position of the this latter command which is used in Listing 6.11. # - stepper motor to be observed in real to measure the position of an output shaft, as illustrated by the example quency half of oscillator register OSCL time.) of Listing 6.13. into register AUX0, prior to using this In this case, a four-bit Gray code on value to drive the stepper motor. (It & Port A is converted to binary, before is also possible to use register OSCL "> ! $ being output as a binary value on Port directly to drive the stepper motor, but The example of Listing 6.12 illustratthe speed of operation is then consider- ed the possibility of open loop position B. Bit masking techniques may optionally be used to reduce the number of ably faster.) control of a stepper motor. However, A more sophisticated control pro- stepper motors can easily slip due to input bits, if required. gram is shown in Listing 6.12, with their low output torque, so the desired 3 % 5 the output of an up/down counter position and the actual position are not used to provide forward and reverse always the same thing. The only way to machine You may recall from Part 5, last control, combined with position con- really be sure of the actual shaft positrol based on the running count value. tion is to measure it, and Gray code is month, that a simple sequencer was used to generate one-off or repeatHardware connections to inputs and ideally suited to this purpose. outputs are shown in Fig.6.3. Fig.6.4 shows a 3-bit Gray-coded ing output sequences. This feature (Users of Proteus VSM may wish disc, which may be used to measure was seen to be ideal for generation of to add a Watch window variable for rotary shaft position, when combined timed output sequences, such as those include "16F627.PLC"
; Defines PLC instructions
Everyday Practical Electronics, April 2010
Teach-In 2010 ' ! 1
% # 9#.#,
R S 0 1 #
4
" # Fig.6.3. Using an up/down counter to control the position of a stepper motor 5 'Â&#x2026; include "16F627.PLC" ; Defines PLC instructions '5=>> 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) generated by electronic toys, displays,
@ " !
! .
R S R S ! ! = . ! " # 5 + . R S 5 'M # N ; % N % # ! # *A#. 4 0
4
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
3
4
10 second delay
Green
4
1
1 second delay
mber
ed
mber
@ % ; ( ) H
Fig.6.4. Using a Gray-coded disc to measure rotary position
Everyday Practical Electronics, April 2010
Teach-In 2010 state
macro movl or f
state arg1, state arg2, state arg3, state arg4, state arg5 state arg1 ; Move state number to W STATE, W ; OR ith current state ( ero result ; if the are e ual) STATUS, ; Check if state arg1 current state st v(state arg1) ; o, so goto end state arg5 ; es, so call subroutine state arg3, state arg4 ; check if state transition condition ; is true (1) st v(state arg1) ; o so goto end state arg2 ; Cop ne t state to STATE register STATE
btfss goto call btfss goto movl mov f st v(state arg1) endm
; End of Finite state machine macro
I @) J K ! ) ) ; Traffic Lights include "16F88 L.PLC"
; Defines PLC instructions ; First section
state 0, 1, LOGIC, 1,
state state state state
1, 2, 3, 4,
2, 3, 4, 1,
TIML, TIML, TIML, TIML,
0, 1, 2, 3,
Finite State Machine
ERO
O E TWO THREE FOUR
Define state se uence
; Automatic transition from state 0 1 ; after po er up ; ; ; ;
Red Red Amber Green Amber (then back to Red)
; Second Section
State transitions
e i timl
STATE, 1 0, 2
; 2 second timeout state 1 2
e i timl
STATE, 2 1, 1
; 1 second timeout state 2 3
e i timl
STATE, 3 2, d'10'
; 10 second timeout state 3 4
e i timl
STATE, 4 3, 1
; 1 second timeout state 4 1
; Third section
Actions performed
subdef ERO puti b'00000000', PORTB return
; All lights off after po er up
subdef O E puti b'00000001', PORTB return
; Displa
Red
subdef TWO puti b'00000011', PORTB return
; Displa
Red
subdef THREE puti b'00000100', PORTB return
; Displa
Green
subdef FOUR puti b'00000010', PORTB return
; Displa
Amber
endp
; End of PLC program
Amber
Listing 6.1 . A simple traffic light finite state machine. , ; ( ) ) " # , $ Everyday Practical Electronics, April 2010
itself. Notice that a LOGIC, 1 value causes an automatic transition from state 0 to state 1, with time delay status bits causing all subsequent state transitions. The second section uses â&#x20AC;&#x2DC;eqiâ&#x20AC;&#x2122; comparison operators to enable each timer once the STATE register is equal to the tested value. The timer output bit becomes 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. # tion contains the subrou light values to Port B.
; !
The main aims of this series have been to make microcontroller programming 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 microelectronics. The ladder logic software used in the series has been placed into the public domain by the author, so you are free to to extend it to suit new applications. Although it has been carefully tested, like any complex program, 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 construction projects to EPE in the future. EPE
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
Breakout Board & Modules
50
Integrated Circuits
Discrete Parts
PWM Motor Speed Controller
Assembled Kits
Connectors
http://www.handsontec.com