52
50 Everyday Practical Electronics, November 2009 Teach-In 2010 By Walter Ditch TEACH-IN 2010 LADDER LOGIC PROGRAMMING FOR THE PIC MICRO Part 1: Getting Started – Working with Inputs and Outputs T HIS - - - - - - www.microchipdirect.com Everyday Practical ElectronicsEPE www.labcenter.co.uk - Comparing PLCs and microcontrollers

Teach-in-2010: Ladder Logic Programming with PIC

  • Upload
    lee

  • View
    1.951

  • Download
    15

Embed Size (px)

DESCRIPTION

Ladder logic programming for the PIC micro.

Citation preview

Page 1: Teach-in-2010: Ladder Logic Programming with PIC

50 Everyday Practical Electronics, November 2009

Teach-In 2010

By Walter Ditch

TEACH-IN 2010LADDER LOGIC PROGRAMMING FOR THE PIC MICRO Part 1: Getting Started – Working with Inputs and Outputs

THIS�������������������������� ���������� ������ ����� ���� ����������������������������

����������� ������ ��� ��������������������������

���� ������ ���� � ������ ����� ���������������������������������������������������������������� �� �!��� � ������"��� !������������ �!��� ��� ������ ��-������� ������ ��� ������� �������� �������� �� ����� ����������������������������������#������������������"��������������������������"����������������������������� ������� ������� ������ ������$�������

!����� ����� ���� ��������������������������������������������������� ������ ��� ������ ����%������� ������� �� "�� ������� "�����������������&���������'��������������� ��� �������� �������� ����������������� ������� ������ �������� ������$��������(����'�������������������������� ������� ��� $����� ���������� ���������������������������������"��������� ������ ���� �������������������� ��������� ��� ���������������������#��������������������������������������"��$����������������������������

#�������� �������������� ��������������������� �� ���������� �������

�!�%������ ������ �� ���� ����������� �� ����� �������� ��'��� ������ ���� ��������� ������������ �� ������%���������������������� ���-���������������������������������������������

��'��� ����� ��� ������ ���� ��-���������������������������������������������!�%�������������������������������������������������"������%"������������������������#���������������������������������������������������������"����������������-"����������������������������������� ����� ����� ������� ������ "���������"���

)�"��$����������������������������������� ������ ������� ����������������������������������*

� )��������"���������������-$�������������+����������������������,

� #����������������������� ������� ���� �����%������

���������+��.,�������� )�$������� ���� "���%�������

����������(�������������������%"�����

����������������������������������"����������������������������������������� "������ ���� ��$�����%"�������������

#��� ������� ��������� ����� ��������������"���������������������"����

������"��������������������������������������������������������� ���� ��������� ���� ����� +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

#��� ����� ����������� "������� ���!�� ���� �� ���������� ������ ��

Page 2: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, November 2009 51

Teach-In 2010

size, complexity and, of course, cost. The inputs and outputs circuits of a PLC, for example, are extremely rugged, with digital inputs often be-ing connected via opto-isolators, and digital output types including transis-tor, thyristor, triac and relay. This al-lows the PLC to directly control high power devices, such as motors, pneu-matic actuators and the like. A typical

implement combinational and se-quential logic functions in electrical control circuits, and it is in part this electrical basis which makes it easy for electrical engineers to understand – even those without a computing background. Consider, for example, a simple electrical circuit consisting of a switch and a lamp, and also its rep-resentation using a ladder diagram, as shown in Fig.1.2.

Considering the circuit on the left, closing the switch will clearly cause the lamp to light. The ladder diagram on the right is equivalent, consisting of a pair of vertical power rails, with one or more horizontal ‘rungs’. (The ladder-like appearance gives this type of diagram its name.) Closing the normally open switch contacts on the left of the ladder diagram will con-nect power through the horizontal rung, hence lighting the lamp.

Historically, the output would typically have been a relay coil, thus allowing a relatively low voltage control circuit to switch mains oper-ated power devices. For this reason, PLC inputs are often referred to as contacts, while outputs are called coils. It can be seen from the ladder diagram that an output coil is rep-resented graphically using a pair of curved braces (although a circular output symbol is sometimes seen).

This extremely simple concept is the basis of PLC operation, and in part explains why electrical engineers are so comfortable writing PLC programs.

This added complexity is avoid-ed here by the pre-configuration of default settings, such as port directions, in the supplied PLC header ������+2�� �����������������012134�����������(��������������"�����input, while Port B is an output.) You can, of course, change these settings, simply by editing the relevant section �����������������"�����������������

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 mi-crocontroller operate at much lower voltage and current than those of a PLC, they are essentially the same from a software point of view. The internal structure of a microcontroller also contains many similar elements to those found inside a PLC, including a central processing unit, program mem-ory (ROM), together with a variety of volatile and non-volatile data memory types. (The content of volatile memory types, such as static RAM, is lost when power is removed, while non-volatile memory, such as EEPROM, is retained.)

The allocation of connections as in-puts or outputs is, of course, pre-deter-mined by the PLC manufacturer, since this is a pre-requisite for the connection of specialised interface circuitry. Not so in the microcontroller world, where the assembly language programmer nor-mally 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 – just like a real PLC.

So, having established that PLCs and microcontrollers have a lot in

Fig.1.1. A typical industrial PLC

Fig.1.2. A simple switch and lamp circuit (left) and its equivalent ladder diagram (right)

common, let’s turn our attention to lad-����������������������������������offer in terms of software development.

Ladder diagrams and ladder logic

Ladder logic owes its origin to the use of switches and relays to

Ladder logic programs are also very concise, with a section of code to (1) read an input and then (2) control a linked output requiring as little as two lines of code. Listing 1.1 shows a possible implementation.

In general, a PLC program is cre-ated by converting each input contact

Page 3: Teach-in-2010: Ladder Logic Programming with PIC

52 Everyday Practical Electronics, November 2009

Teach-In 2010

and output coil of the system’s ladder diagram into a series of equivalent program statements. Execution of the program is then a continuously operat-ing sequence of:

Reading inputs Performing logic-based

calculations Controlling outputs

This repeating process is known as the scan cycle, and is shown graphi-cally for a slightly more complex example in Fig.1.3.

It can be seen that each rung of the ladder diagram is evaluated from left to right, starting at the top rung and working progressively down (Steps 1 and 2 of Fig.1.3). The End of Program

A number of conclusions may be immediately drawn from this method of operation:

1. Execution of a PLC program con-sists of a continuously operating pro-gram 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 ‘seen’ by

the input phase of the scanning loop.

4. The average time taken to react to a changing input is re-lated to the scanning loop duration.

5. It may take more than one scanning loop for the results of complex calculations to fully propagate through the system. This may lead to the possibility of transient glitches as calcula-tions ‘ripple-though’.

In practice, you ������ ���� ����� ���-der logic solutions are suitable in the majority of logic-based control

scenarios, since the computer is typi-cally operating at much higher speed than the system being controlled.

Now that the basic principles of ladder logic programming have been covered, the next step is to obtain the

required software, which will then enable us to create and test an execut-able program.

Obtaining the softwareThe ladder logic software is designed

to work with the MPLAB Integrated De-velopment 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:

PIC16F627/PIC16F627A (head-������&012134��!�',

PIC16F628/PIC16F628A (head-������&012136��!�',

� ���012176�+����������&012176�PLC’)

P IC16F88 (header f i les ‘16F88_L.PLC’ and ‘16F88_H.PLC’ offer low voltage and high voltage program versions respectively)

� ���012664�+����������&012664�PLC’)

��� ��������� ���� ���� ��� �� ������are all 18-pin ICs, differing mainly in ���� $�������� �� ~���%"����� �����memory, static RAM, or EEPROM-based non-volatile data memory. The PIC16F887 is a 44-pin IC, having enhanced input/output capabilities. These features are summarised in Table 1.1.

Inclusion of the appropriate header file will cause a number of default settings to be chosen, such as port directions, oscillator type and so on. These settings have been tested with a number of hardware configurations, and are intended to simplify the configuration proc-ess as far as possible. (You should of course review these settings to ensure compatibility with your own requirements.) Default options are summarised in Table 1.2.

A number of required files are available in a compressed ZIP file, which may be obtained from the the Library > Project Code section of the Everyday Practical Electronics website (www.epemag.com). The contents of the ZIP file are given in Table 1.3.

ld SWITCH ; Read state of Switch out LAMP ; Output to Lamp

Listing 1.1. A notional section of a PLC program based on the circuit and ladder diagram of Fig.1.2

Fig.1.3. The repeating scan cycle of a PLC executing a ladder logic program

statement forces program execution to �������������"�������������������rung (Step 3), causing the program to run continuously. This program might be coded using statements such as those given in Listing 1.2.

ld SWITCH_A ; Read state of Switch A out LAMP_A ; Output to Lamp A

ld SWITCH_B ; Read state of Switch B out LAMP_B ; Output to Lamp B

endp ; End of PLC program

Listing 1.2. A PLC program based on the ladder diagram of Fig.1.3

Page 4: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, November 2009 53

Teach-In 2010

Filename Description

16F627.PLC PLC header file for the PIC16F627/627A microcontroller

16F628.PLC PLC header file for the PIC16F628/628A microcontroller

16F648.PLC PLC header file for the PIC16F648A microcontroller

16F88_L.PLC PLC header file for the PIC16F88 microcontroller – low voltage programming enabled on pin RB3

16F88_H.PLC PLC header file for the PIC16F88 microcontroller – high voltageprogramming enabled, pin RB3 available for general I/O

16F887.PLC PLC header file for the PIC16F887 microcontroller

PIC16F627.DSN Proteus VSM simulation – PIC16F627A based Digital I/O Board

PIC16F88.DSN Proteus VSM simulation – PIC16F88 based Digital I/O Board

PIC16F887.DSN Proteus VSM simulation – PIC16F887A based Digital I/O Board

Lst1_3.asm Source code file for Listing 1.3

Lst1_4.asm Source code file for Listing 1.4

Lst1_5.asm Source code file for Listing 1.5

Lst1_6.asm Source code file for Listing 1.6

Assembling and execut-ing simple PLC-style programs

In this section you will see just how easy it is to create and assemble simple programs and then run them on a variety of different PIC-based systems. I recommend that you try these activities out for yourself, if at all possible.Begin by extracting the entire

����������������������������-venient folder and then use the MPLAB IDE’s File > Open menu �����������������������&!��0�>�asm’, the content of which is ���������!�������0�>�

����������������������-ally identical to the code snippet �����������������!�������0�0��"��� "����� �� ���� ���012664�microcontroller. It is suitable for use either with the PICkit 2 Debug Express board, or with Proteus VSM electronic simu-lation software. (Note that the PICkit 2 board has a single input ����������"������)�0�������������������������������������������bit of Port B, plus eight LEDs connected to Port D – which explains the choice of inputs ��������������!�������0�>�

Having displayed the source +����,��������.�!(<�������� ��step is to assemble it, in order to create a machine code (.hex) ��������������������"�����-loaded and programmed. The ���� ����� ��� �� ����� ���� �-quired microcontroller type by selecting the ��������� ��Device menu option, and then selecting the PIC16F887 from the Device drop-down list. Next click on the blue title bar of the ���������������������������highlighted and then assemble ��������"����������������Project > Quickbuild Lst1_3.asm menu option. If everything has gone ����������������������~���������������������������������-"����� ������������ ��� �� &<�����

Succeeded’ message, displayed in the Build tab of the Output window. The MPLAB IDE has now done its �"� ���� �� !��0�>��� � ���� ����� �����been created in the same directory ��� ���� ����� ���� ����� ����� �� "��programmed.

Device Program(kWords)

RAM (bytes)

EEPROM (bytes)

Max I/O (bits)

Other Features

PIC16F627 1 224 128 16 2 comparators

PIC16F628 2 224 128 16 2 comparators

PIC16F648 4 256 256 16 2 comparators

PIC16F88 4 368 256 16 2 comparators 7-channel ADC

PIC16F887 8 368 256 35 2 comparators 14-channel ADC

Table 1.1. Major features of supported PIC microcontrollers

Device Inputs Outputs Other Features

PIC16F627 / 628 / 648

Port A (5 bits) Port B (8 bits) Comparators disabled, pull-ups disabled 4MHz external crystal oscillator selected

Timer 0 configured for use by PLC software MCLR enabled, Watchdog timer enabled

PIC16F88 Port A (5 bits) Port B (8 bits) Comparators disabled, pull-ups disabled 4MHz external crystal oscillator selected

Timer 0 configured for use by PLC software MCLR enabled, Watchdog timer enabled

ADC disabled

PIC16F887 Port A (8 bits) Port B (8 bits) Port E (4 bits)

Port C (8 bits) Port D (8 bits)

Comparators disabled, pull-ups disabled 4MHz internal oscillator selected

Timer 0 configured for use by PLC software MCLR disabled, Watchdog timer enabled

ADC disabled

��� �������� ������������������������������

Table 1.3. File contents of ‘PLC1.zip’

include "16F887.PLC" ; Defines PLC instructions

ld PORTB, 0 ; Read Port B bit 0 out PORTD, 0 ; Output to Port D bit 0

endp ; End of PLC program

Listing 1.3. Reading a switch and outputting to an LED (Lst1_3.asm)

Page 5: Teach-in-2010: Ladder Logic Programming with PIC

54 Everyday Practical Electronics, November 2009

Teach-In 2010

Syntax Function Ladder Diagram Symbol

ld REGISTER, BIT[0-7] Read an I/O bit

ld_not REGISTER, BIT[0-7] Read an I/O bit (inverted)

out REGISTER, BIT[0-7] Send to output bit

out_not REGISTER, BIT[0-7] Send to output bit (inverted)

Table 1.4. Bit input/output commands

Fig.1.4. A Proteus VSM simulation of the PIC16F887 microcontroller

What happens next depends on how you intend to actually run the program. If you are using the PICKit 2 board then the next step is to run the PICkit 2 programmer application, then use the File > Import Hex menu option ����������������������+��� ,�����

created earlier. Next, click the Write button to program the PIC16F887 mi-crocontroller. You should see a green Programming Successful message in the programmer window at this stage. Finally, apply power to the board by clicking the On checkbox situated just

under the VDD PICkit 2 label at the upper right.

Pressing Switch 1 will now cause the LED con-nected to RD0 to toggle on and off. However, you may note that the LED actually goes out when the switch is pressed, which is the opposite of what you might have expected. Examin-ing the schematic diagram supplied with the PICkit 2 documentation solves the mystery, revealing that SW1 normally reads as a logic-1, providing a logic-0 when

pressed. The required logic of our program may be easily restored by replacing the ‘ld’ instruction with its negative logic ‘ld_not’ equivalent, as given in Table 1.4.

From Table 1.4, we can also see that a negative logic output command

Page 6: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, November 2009 55

Teach-In 2010

(out_not) is available. Thus, we can create a logical inversion either by using ‘ld_not’ followed by ‘out’, or ‘ld’ followed by ‘out_not’. If you are using the PICkit 2 board, then you can use this information to modify the program of Listing 1.3 so that pressing the switch causes the LED to come on, rather than go out.

If you are lucky enough to have the full version of Proteus VSM, Version 7.0 or later, then this may be used to simulate the operation of the program of Listing 1.3. Begin by using Proteus to open the supplied PIC16F887.DSN ����� ������ ����� ������ ��� ����� ���Fig.1.4.

include "16F627.PLC" ; Defines PLC instructions

ld PORTA, 0 ; Read Port A bit 0 out PORTB, 0 ; Output to Port B bit 0

ld PORTA, 1 ; Read Port A bit 1 out PORTB, 1 ; Output to Port B bit 1

endp ; End of PLC program

Listing 1.4. Reading and controlling multiple inputs and outputs (Lst1_4.asm)

Controlling multiple inputs and outputs

To take a slightly more complex example, suppose we wanted to con-trol several inputs and outputs. This could be achieved as illustrated by Listing 1.4, shown for a PIC16F627-based system.

Assuming you have a suitable PIC programmer and experimentation board, such as the Velleman K8048, the ����������������������.�!(<��=;���������������������������+����"�-ing of course to set the device type to either the PIC16F627 or PIC16F627A, as appropriate). Next, connect the

Fig.1.5. The output produced by Listing 1.4, running on a Velleman K8048 board

include "16F887.PLC" ; Defines PLC instructions

ld PORTE, 3 ; Read Port E bit 3 (ICSP pin 1) out PORTD, 3 ; Output to Port D bit 3

ld PORTB, 7 ; Read Port B bit 7 (ICSP pin 4) out PORTD, 2 ; Output to Port D bit 2

ld PORTB, 6 ; Read Port B bit 6 (ICSP pin 5) out PORTD, 1 ; Output to Port D bit 1

ld_not PORTB, 0 ; Read Port B bit 0 inverted (SW1) out PORTD, 0 ; Output to Port D bit 0

endp ; End of PLC program Listing 1.5. Controlling up to four inputs using the PICkit 2 Debug Express

(Lst1_5.asm)

programmer to your PC via the sup-plied serial cable and then download and execute the program. When the program is executed, pressing a switch ����������������������"���������A should cause the corresponding bit of Port B to be activated, as shown in Fig.1.5.

If you have access to the Proteus VSM software then you use this to load the ‘PIC16F627.DSN’ simulation and then follow the procedure described earlier to load and execute the program of Listing 1.4.

Surprisingly, it is also possible to develop similarly complex programs for the PICkit 2 Debug Express board, despite the fact that the PCB is limited to a single physical input switch! The trick in this case is to use the PICkit 2 Logic Tool application to control up to three additional digital input signals via the In Circuit Serial Programming (ICSP) interface, which links the ‘black box’ to the PIC16F887 PCB. When not being used to download programs, the Logic tool allows inputs RE3, RB7

and RB6 to be controlled by activating pins 1, 4 and 5 of the ICSP interface respectively.

To see this in action for yourself, begin by assembling the program of Listing 1.5, and then download the ��������� �������� ���� ���� �� ����PIC16F887 in the normal way.

Next, enable power to the PCB by clicking the On check-box and then select the Tools > Logic Tool option from the pull-down menu, which will display the PICkit 2 Logic Tool dialog of Fig.1.6.

Ensure the Mode option is set to Logic I/O by clicking the button at the upper right, and then click the Enable

Our machine code program created earlier must be logically attached to the PIC16F887, prior to running the simulation. To do this, right-click on component U1 and select the Edit Properties option from the context menu to display the Edit Component dialog. From here, you can click the �������������������"�������������� &!��0�>��� '� ���� ������� �������Close the dialog and then click the Play button at the lower left of the Proteus window to run the simulation. You’ll then be able to click on the input con-nected to bit 0 of Port B, which should cause the corresponding bit of Port D to change (as illustrated by Fig.1.4).

Page 7: Teach-in-2010: Ladder Logic Programming with PIC

56 Everyday Practical Electronics, November 2009

Teach-In 2010

Fig.1.6. Controlling digital inputs via the PICkit 2 Logic Tool dialog

IO button to allow logic levels to be directly observed or controlled. Next, set pins 4 and 5 to be outputs, at which point you should be able to control the state of the LEDs connected to outputs RD0-RD3, with the program of Listing 1.5 running. (Note that Pin 6 in Fig.1.5 ������������������������������������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 avail-able from the EPE Readers’ Services, and is supplied as standard with a PIC16F88 microcontroller, although a wide variety of other PICs are also supported.

The board brings out the inputs of Port A and the outputs of Port B via switches and LEDs at the lower left and lower right respectively. A 16MHz crystal oscillator is supplied �������������������������������������four times faster than the 4MHz default used by the PLC software. If you are �������������������������������PLC software, I’d recommend replac-ing this with a 4MHz crystal – which will ensure that time-dependent programs covered in later parts of the series run at the correct speed. +�������������� ���� �!�� ������ ���� ���

�������� �� ������������� ���"���an internal RC oscillator at 4MHz in the event that the external oscillator fails to start.)

A USB cable is supplied as standard, although the board can also accommo-date an external DC supply (shown at the upper left of Fig.1.7). If the board is powered from the USB cable, then the PIC must be programmed using ‘low ������� ��������'�� ������ ������use of Port B, bit 3 (RB3). To use LVP with the PIC16F88, the upper (RB3) jumper to the left of the LCD display must be positioned to the left, as shown in the image. (Be sure to do this with the power removed, and be very

careful which jumper you enable, to avoid damaging the PIC microcon-troller.)

#�� ������� �� ���� ������ ����are provided, supporting low volt-age or high voltage programming (‘PIC16F88_L.PLC’ and ‘PIC16F88_H.PLC’ respectively). Listing 1.6 shows a suitable test program, which also demonstrates the use of active-low inputs and outputs, as originally seen in Table 1.4.

#�������� ������� �����"���� ���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 – see Fig.1.4 and associated text for details.

Troubleshooting tipsWhile operation should be mostly

trouble free, the following trouble-shooting 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

Page 8: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, November 2009 57

Teach-In 2010

2. Ensure that the relevant include ���� ��� ��� ���� ����� ������� ��� ���������"��� ����� ����� �������� ���������"�������"�����"��������������

>�� ����� ������ ���� .�!(<� �=;�������� ����� ��� ����� ��������� ��������� ���������� ������ �����������������������"��������������������

7��#��������"���������������"���������������������������������������������������������������������������+��,������������������������������ ���� ���� ������ �������� +����,���������������������������������������������� ���� �������� ���� ����������������������

��� #�� �� ����� ��������� ���� �������������������)����������������.�().������"�������������������������������������������������������������������������������������������������������������� �������������������������������13����������

; (Low voltage programming version ; with RB3 used as the LVP pin)

ld PORTA, 0 ; Read Port A bit 0 out PORTB, 2 ; Output to Port B bit 2

ld_not PORTA, 1 ; Read Port A bit 1 (inverted) out PORTB, 5 ; Output to Port B bit 5

ld PORTA, 2 ; Read Port A bit 2 out_not PORTB, 6 ; Output to Port B bit 6 (inverted)

ld_not PORTA, 3 ; Read Port A bit 3 (inverted) out_not PORTB, 7 ; Output to Port B bit 7 (inverted)

endp ; End of PLC program

Listing 1.6. Controlling normal and inverted signals with the PIC16F88 (Lst1_6.asm)

1������������������������-����������������������������������"������������������������������"�� ������� �� �������� �� ���� ������� ���� ������ ��� ���� ���� "�� ������� ����������� ���� ���������� ������ ����� ������ ������ �� ��"��������������

4��2���������-�������������������-��� ���� ������������� ��"����������������� +��'���������������������������� ����� ��� ����������,

Final thoughts�������������������

��'��� ������� ��������� ���� ��-������� ������������������������������<��� ��� ����� �������������������������

�����������������"���������������������'���"�������������������������������������������������������������������������������������������

��'��� ���� ����������� ����� ���������������"���������������������������������������������������������"��������������� ������-������"����������������������������������������������������

#����� �� ����������������� "�����"��������������������������������������������� ��"��������� ����� ��������"����� �� <����� ������ ����� ���(�=�� �@�� ���� ;�@� +� �������%�@,����'��� ����� ���� �� �� ������� ��������������������������$������������������������������������������������������������ �� ����"��� ��$������ ��������������

��'������������������������������-������������������� �����"�������������������������������������������������� �����"��� ��� ���� "����� �� ������ ����� ����� � "����� ������ 2������������ �������� ��������� ������ ��������� �������� ����� ������� ������� ���� �������������5��������!;=�

COOL COMPONENTS

Established in 2004, Cool Components supplies interesting, useful and powerful electronic components at excellent prices.

Arduino Boards + Shields Fast Update GPS Modules Olimex PIC, AVR + ARM Boards

Serial Bluetooth Adaptors

Plug-In Media Player Modules Serial Controlled OLED Displays Iron-On PCB Fabrication

Servos + Servo Controllers

WWW.COOLCOMPONENTS.CO.UK

Follow product news on: twitter.com/coolcomponents

0871 288 7685

We work with manufacturers including Sparkfun, Olimex, Arduino and many others to bring you the best from the cutting edge of new electronic technology.

include "16F88_L.PLC" ; Defines PLC instructions

Page 9: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, December 2009 ��

By Walter Ditch

TEACH-IN 2010LADDER LOGIC PROGRAMMING FOR THE PIC MICRO Part 2: Working with Combinational and Sequential Logic

THIS is the second instalment of a six-part series, discussing the use of ladder logic programming

methods with PIC microcontrollers. Ladder logic is the fundamental basis of Programmable Logic Controllers (PLCs), which are a specialised type of industrial computer, designed to be easily programmed by engineers. Thus, the aim of using ladder logic is to simplify the development process, making PIC programming accessible to the widest possible audience.

You may recall that last month we discussed the use of ladder diagrams to graphically represent simple electrical circuits, and converted these to execut-able machine code programs for the PIC micro by using commands such as: ‘ld’ (read an input bit); ‘out’ (send result to an output bit); plus their negative log-ic counterparts ‘ld_not’ and ‘out_not’ respectively. We saw that a PLC-style program executes by following a repeat-ing cycle of reading inputs, performing calculations and controlling outputs, known as the scan cycle.

The PLC software itself consisted of ������������������ ���������������������number of common PIC microcontrol-lers, including the 16F627A, 16F628A, 16F648, PIC16F88 and PIC16F887. By including the appropriate header �������������������������������������were able to use the freely available

MPLAB Integrated Development Envi-ronment (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, Mi-crochip Direct’s PICkit 2 Debug Express board, Matrix Multimedia’s PICmicro MCU Development board, plus Proteus VSM electronic circuit simulation soft-ware from Labcenter Electronics.

Moving onIn this second instalment, we’ll

continue our tour of ladder logic by looking at:

Creation of repeating waveforms by using ‘oscillators’

Combining inputs using simple combinational logic operators (AND and OR)

Availability of other logical func-tions (NOT, NAND, NOR, XOR, and XNOR)

Using internal memory locations (auxiliary relays) to hold intermedi-ate results and to solve complex logic networks

Creation of latched (stored) outputs to capture momentary input signals, including the provision of set and reset inputs outputs.

We’ll then use these concepts to de-velop a simple and extendable alarm circuit, using just a few lines of code, and suitable as the basis of either a car alarm or burglar alarm. Features will include multiple input sensors, a latched alarm status output, and a pulsed armed/disarmed LED.

Simple systemsThe above concepts will be drawn

together to create a number of simple ���������������������������������������‘system armed’ indicator, plus a simple alarm circuit. These simple building blocks may be used as the basis of a wide variety of more complex systems, with potential applications being mainly limited by your imagination.

The article concludes by discussing the PLC software’s internal operation in a little more detail. This knowledge 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 – particularly the various !"#�������� ����$� ��� "����������� �����������%�������� �������������������������Also, make sure you have installed

Page 10: Teach-in-2010: Ladder Logic Programming with PIC

�� Everyday Practical Electronics, December 2009

the freely available MPLAB IDE software, which will be needed to actually assemble the example programs. And of course, in order to actually test the programs, you will need a suitable PIC develop-ment board or simulation software.

Creating repeating waveforms by using oscillator bits

The PLC software provides two 8-bit registers, OSCH and OSCL, which contain a total of 16 oscillators, with periodic times ranging from 512�s to 16.77 seconds, based on the default clock frequency of 4MHz. Available periodic times and frequencies are shown in Table 2.1.

is important to also be aware that they are also used internally as time refer-ences by several other PLC commands yet to be considered, including timers and PWM (pulse width modulated) outputs. For this reason, the use of a dif-ferent clock frequency to the assumed value of 4MHz is likely to cause time-critical programs to run correspond-ingly faster or slower.

Simple combinational logic functions

Simple switch-based and ladder logic circuits may easily be developed to implement Boolean logic functions such as AND and OR, as shown in Fig.2.1.

Two or more switches in series cre-ates an AND function, since all input contacts must be simultaneously closed to activate the output device (or output coil). Similarly, parallel switch contacts will provide a logical OR ar-rangement, with one or more closed contacts creating a route for the power ���������������������������������������the output device.

Notice in Fig.2.1 that all inputs and outputs have been labelled, thus it is possible to state the logical operation of the upper and lower systems in Fig.2.1 as:

‘LAMP = A AND B’, (switches in series), and

‘LAMP = A OR B’ (switches in parallel).

The example program of Listing 2.2 shows a possible coding for these logical operations, based on the 16F88 microcontroller.

In this case, the output on Port B bit 0 is generated by ANDing the lower two input bits on Port A, while Port B bit 1 is the result of ORing bits 2 and 3 of Port A. This method is extendable, simply add successive logical opera-tors in order to increase the number of inputs. Also, note that NAND or NOR operators may easily be created by replacing the ‘out’ instruction with its negative logic equivalent ‘out_not’.

A simple application which com-bines oscillators with logic functions

Waveform production&����������� ������'������������������

this section explains how the oscilla-tor waveforms are produced, and also covers the derivation of the periodic times of Table 2.1. (This is not essential reading, so you can skip this and come back to it later.)

Recall from Part 1 that the PLC soft-ware assumes an oscillator frequency of 4MHz. This signal is used to generate a number of other waveforms, includ-

����������� �� �����������������

����������� �� �����������������

������������� � ��������� !�� �� ���� ������������� � ��������� !�� �� ����01�3��67

�������������� ����������������� ���������������� ���������������� ���������������� ���������������� ���������������� ���������������� ��

01�3��67

�������������� ���������������� ���������������� ��������������� ��������������� ��������������� ��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’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 re-ferred to as OSCH here), but using a 1:256 prescaler (frequency divider). Thus, the OSCH register increments once every 256�s.

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 512�s for bit 0 of OSCH. Periodic times of subsequent bits are derived by repeat-edly doubling this initial value (and frequencies are, of course, calculated as the reciprocal of periodic times.)

The PLC software uses a Timer0 (OSCH) overflow interrupt to incre-ment the low frequency oscillator register (OSCL), in effect creating a 16-bit timer register in software, from the 8-bit timer provided in hardware.

These waveforms may be used di-rectly in user programs. However, it

Listing 2.1. Creating a 2Hz pulsed output (Lst2_1.asm)

Page 11: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, December 2009 ��

would be to enable a pulsed output only when a key is pressed. A simple exam-ple is shown in Listing 2.3 – this time written for for the PIC16F627/627A microcontroller.

of connecting a virtual oscilloscope to Port B bit 1 using the Proteus VSM software.

As can be seen, the measured peri-odic time of 530�s, obtained using the

be ‘seen’ by the PLC software until its next pass through the scan cycle.)

Other logical operationsIt was previously seen from Fig.2.1

that two normally-open switches in series creates a logical AND function, while parallel switches provide a logi-cal OR (inclusive-OR to be precise). The related exclusive-OR function provides an output if precisely one of the inputs is true, which is logically equivalent to the statement ‘The out-put is true if (A is true and B is false) OR (A is false and B is true)’. Listing 2.4 gives an example.

In addition to optionally inverting the output bit, as previously discussed, it is also possible to perform logical operations where one of the input bits is inverted. The full range of Boolean logic functions, based on normally-open or normally-closed input con-tacts, is shown in Table 2.2.

Using internal memory to hold intermediate results

While the above methods may be used to solve simple Boolean logic cir-cuits, more complex logical problems may require an alternative technique. Consider for example the ladder dia-gram of Fig.2.3.

The trick in this case is to use standard logical operators to solve each horizontal ‘rung’ of the lad-der diagram, writing the result to a series of auxiliary relays. These intermediate results may then be combined using standard logical commands to calculate the final output state.

Listing 2.5 demonstrates the use �� ��������������� ��������������������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 un-derstanding of the ‘single bit’ combi-national logic capabilities of the PLC software. For future reference, it is worth mentioning that a number of ‘byte oriented’ logical commands are also available, which will be discussed later in the series.

The next section demonstrates how the application of feedback from out-put to input may be used to create a simple latch, which is, of course, the basis of sequential logic.

Fig.2.1. Switch-based and ladder logic versions of Boolean logic functions

Listing 2.2. Simple logical functions (Lst2_2.asm)

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 512�s from Table 2.1. (Some ran-��������������� ��� ������������ ������the changing oscillator bit will not

1

Page 12: Teach-in-2010: Ladder Logic Programming with PIC

�� Everyday Practical Electronics, December 2009

Using feedback to create latched outputs

Surprisingly, it is possible to read the state of an output in just the same way as an input. This allows feedback to be applied, which in turn enables the creation of circuits where a mo-mentary input signal causes an output to be Set or latched until it is manually cancelled. Fig.2.4 shows the creation of a latch circuit using standard ladder logic commands.

In this case a momentary signal on the Set input, Port A bit 0, enables the latch output (commonly referred to as Q in bistable circuits), which is connected to Port B bit 0. The key to understanding this circuit is to notice from Fig.2.4 that the state of the Q out-put is also connected in parallel with the Set input, proving a logical OR arrangement. Thus, the latch is held in the on state once the momentary Set input is removed. The circuit remains enabled until the normally closed Re-set input (Port A, 1) is pressed, which breaks the circuit and resets the latch.

The ladder diagram also contains an optional second rung which reads the Q output (Port B bit 0) and generates an inverted (Not Q) output on Port B bit 1. A program listing is given in Listing

2.6, which is suitable for use with the PIC16F88 microcontroller.

The PLC software also includes a dedicated latch command, which pro-vides an alternative to using separate ladder logic commands. Fig.2.5 shows a ladder diagram incorporating the latch, while Listing 2.7 gives a modi- ������������������������������+9&<<�microcontroller

While the use of the latch command does reduce the source code by a cou-ple of lines, the actual machine code generated is identical in either case. Which approach to use is therefore a matter of personal preference.

Fig.2.2. Connecting a virtual scope to the Port B bit 1 output in Proteus VSM

Listing 2.4. The exclusive-OR operator (Lst2_4.asm)

Table 2.2. Single-bit Boolean logic commands

Fig.2.3. A complex logic circuit requiring a two-stage approach

Page 13: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, December 2009 ��

Building simple systemsTo bring together some of the con-

cepts discussed, let’s begin by creating �����������������>?@������������������be found in the ‘system armed’ output of an immobiliser circuit. We’ll use a latch to arm or disarm the circuit,

statements are optional, having the effect of reducing the pulse width to 1/8 of its initial value.

The program may be executed either using the appropriate Proteus VSM simulation (for those readers with ac-cess to this software), or by using the

Listing 2.5. Using internal relays to solve complex logic circuits (Lst2_5.asm)

The program uses bits 0 to 2 of Port A as input sensors, and Port A bit 3 as a Reset signal (1 = reset, 0 = system armed). Notice that the sensor status automatically becomes the input to the latch, with the latch output being sent ������>?@���������������������!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 in-clude a pulsed alarm output, and the provision of a ‘system armed’ indica-tor, similar to that seen previously. These additions are left as exercises for the reader.

A further potential development would be the automatic cancellation of the alarm after a given period of time, in order to prevent unnecessary annoyance due to false triggering. This enhancement will have to wait until next month, when timers will be covered.

Internal operation of the PLC software

A more detailed understanding of ��������������������������� ����!>#�software is useful at this stage, not only for curiosity’s sake, but also to explain the types of error messages which will inevitably be encountered as you begin to write programs of your own.

^�������������������������`!>^[�"����������@�����������?�����������{"@?������������������������������������� ������� ����� ��|�� ��� ����� ���

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

���������������������������������� ����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�#>�������������������������������-���������������>?@��������������!����@��������Z���������������������^}@�

Fig.2.6. Ladder diagram for a simple alarm with three sensors

!"#����\�@�����?|�������������"������latter case, recall from Part 1 of the se-��������������������������!"#����\�>�����Tool to set and reset the bistable. Pin 5 ����������������!����[�����9��������������������������������!�����{!����[��������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 trig-gered, and remain in this state until the alarm is manually cancelled. The ladder diagram for the alarm is shown in Fig.2.6.

Page 14: Teach-in-2010: Ladder Logic Programming with PIC

�� Everyday Practical Electronics, December 2009

executable machine code program. This powerful software has a macro facil-ity, which allows a text string to be automatically replaced by a section of ������� ���� ��|��� ������ �������������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 assem-bler, prior to conversion to machine code. Consider the implementation of the ‘ld’ instruction as an example, as shown in Fig.2.7.

As can be seen, the ‘ld’ macro accepts two argu-ments, ld_arg1 and ld_arg2. The macro substitution causes the original source code line to be replaced by three lines of assembly language. It is important to be aware that any assembler errors are likely to relate to the source code after the macro substitution, which does admittedly make the debugging process a little ������� �����

Notice that the above section of code results in the logic level present on the input port being placed �������������������� ���������of the (LSB) Working regis-ter (W), which is actually a general feature of the PLC software. The correspond-ing ‘out’ instruction, for example, simply takes ������������ �����������>�[�of the W register and sends it to the selected output ������������������� �����by examining the appro-�������������� ����������|��editor such as Windows Notepad.

An interesting observa-tion at this stage relates to the ‘endp’ or end program PLC instruction, which is of course, yet another macro. An examination of the header �����������������������������a jump instruction, which forces the PLC program to run

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)

Page 15: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, December 2009 ��

continuously – this being the basis of the PLC’s repeating scan cycle.

An obvious conclusion based on the above macro substitution is that any machine code programs are likely to be considerably larger than the source code might suggest. Thus, the main advantage of the ladder logic approach ������������ ������������������������-ess, rather than reduction in code size.

Summary and next stepsThis 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 incorpora-tion of inverted inputs and outputs (NAND and NOR for example). More

complex logical circuits were solved by use of internal storage (auxiliary relays) to hold intermediate results. We then used feedback from outputs in order to create simple self-latching circuits (simple sequential logic) and combined ��������������������������������������-ing ‘system armed’ warning light and an alarm circuit.

We also discussed the macro substitu-tion 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 demon-strated 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 architec-ture of the chosen PIC microcontroller.

The next part of the series will con-tinue the tour of the sequential logic ca-pabilities of the PLC software, by looking at timers and shift registers. The use of timers will enable an action to be per-formed for a given period of time, while shift registers will make it easy to create simple running light displays.

Fig.2.7. Macro substitution, as used by the PLC software’s ‘ld’ instruction

Please add £2.75 p&p per order. Prices include UK VAT.See website for overseas prices.

Special Offer prices for limited period or while stocks last.

Peak Electronic Design Ltd, West Road House, West Road,Buxton, Derbyshire, SK17 6HF.

tel. 01298 70012 www.peakelec.co.uk [email protected]

Measure capacitance and ESR!Capacitance from 1uF to 22,000uFESR from 0.01 ohms to 20 ohms

Battery included + Gold plated croc clips

This new model of the famous offersall the great features of the ESR60 but with

extended measurement range and audible alerts.

Atlas ESR

Atlas ESR PlusThis is the !

The New Atlas ESR Plus, Model ESR70

Atlas SCR - Model SCR100 Atlas ESR - Model ESR60

£89 inc VAT

£75 inc VAT

£79 inc VAT

Passive component analyser.Automatically identify and measureinductors, capacitors and resistors.

Auto frequency selection.Removable probes.

1uH - 10H1pF - 10,000uF1 Ohms - 2M

Atlas LCR - Model LCR40

£79 inc VAT

NEW MODEL

Special Offer!

Includes the Atlas LCR Passive ComponentAnalyser (model LCR40), Atlas DCASemiconductor Analyser (model DCA55),premium padded carry case and user guides.

Complete with extra spare battery.You’re ready to go!

Atlas Star Pack (LCR/DCA)

£125 inc VAT

Ideal Gift and Money Saving too!This pack saves you £20

Connect Triacs or Thyristors any way round.Auto part identification and pinout display.Categorises gate from 100uA to 100mA.

Load conditions regulated at 12V, 100mA,even for a dying battery.

Measures gate voltage drop.Long life alkaline battery supplied.

Supplied with premium probes.

electronic design ltd

Christmas gift ideas...

Capacitance from 1uF to 22,000uF.ESR from 0.01 ohms to 40 ohms.Great for ESR and low resistancemeasurements (short tracing etc).Automatic controlled discharge function.Audible Alerts (for good ESR, poor ESR,open circuit and more).Gold plated croc clips.User Guide and Battery included.

was £97 was £87

Atlas DCA - Model DCA55

£55 inc VAT

DarlingtonsMOSFETsDiodesTransistorsLEDsand more...

The famous Peak Atlas, now withfitted premium probes. Just connect any wayround to identify the type ofsemiconductor, pinout andlots of parameters too.Complete with battery,user guide and probes.

Look! New Probes.

Reduced Price!

...and if you change your mind after Christmas then no worries,you can have an exchange or refund without question.

Page 16: Teach-in-2010: Ladder Logic Programming with PIC

HandsOn Technologyhttp://www.handsontec.com

ISP to ICP Programming Bridge: HT-ICP200In-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-MP213A 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-02HT-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 CFlash programmer or as a development, prototyping, industry and educational platform.

For professional, hobbyists…

Page 17: Teach-in-2010: Ladder Logic Programming with PIC

42 Everyday Practical Electronics, January 2010

Teach-In 2010

By Walter Ditch

TEACH-IN 2010LADDER LOGIC PROGRAMMING FOR THE PIC MICRO Part 3: Timers and Shift Registers

PART three of this series on ladder logic (PLC-style) pro-gramming for the PIC micro

continues the tour of sequential logic by looking at timers and shift registers. This builds upon previous coverage of input/output commands, oscillators, combinational logic and self-latching circuits, allowing an increasingly wide variety of systems to be developed.

Timers often prove useful when building ladder-logic-based systems, making it easy to add time delays and timed outputs. For example, delaying ���������������� �������� �����������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 registersShift registers are also valuable,

allowing a binary pattern held in a register to be shifted to the left or right. A typical shift register application would be the creation of a moving light display, although they have many other uses.

The present article will also delve into the PLC software’s use of internal memory (registers). This knowledge may be required when writing programs, and often proves useful when debugging ladder logic software applications. For

example, the internal state of a timer or counter is normally only visible to the ������ � ��� �� ����� � ����� ����������� �������������������� ���� ����������value is also available as a byte value – if you know where to look.

In passing, a few of the PLC soft-ware’s byte processing commands will be introduced, these being used to sim-plify the coding of some of the example programs. A byte I/O command, for example, will be used to display the internal content of a shift register on a chosen output port. We’ll also make use of a byte comparison command to simplify the coding of a rudimentary ‘KnightRider’ style display.

Coverage of the sequential logic capabilities of the PLC software will continue next month with the intro-duction of counters and pulse-width- modulated (PWM) signals.

As discussed previously, all pro-gram listings for this article are avail-able from the Library > Project Code section of the Everyday Practical Electronics website (www.epemag.com). It is suggested that you copy �� ��� ����� ������������ �� � ��into a single folder on your com-puter, 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 actu-ally try out your programs. Please see earlier articles for further details of the development process, supported PIC microcontrollers, and associated hardware and software.

Also, remember that the example programs may easily be converted to run on any of the supported PIC micro-������� ���!����������������������� �� �� ��� � �� �������� ������� �input and output port assignments to suit those available with the chosen microcontroller.

Using low speed timersSo far, most of the programs consid-

ered have either produced an output �� �� �� ����� ���������� ��� �� � ��� �����instant (combinational logic), or have latched a momentary input signal (sim-ple sequential logic). This has allowed the development of some useful ap-plications, including the simple alarm circuit of Listing 2.9, as seen in Part 2.

A useful addition to this circuit would be the use of a timer to cancel the alarm after a period of inactivity. !������� ����" #�������� ���"�������-��� �����"��� ����� �������� ���� �a timer with a simple alarm circuit.

The PLC software provides up to 16 built-in timers, eight of which are ‘low speed’, with the remainder

Page 18: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, January 2010 43

Teach-In 2010

An important difference between a timer and a latch is that the en-able input needs to be continuously applied, in order to ‘enable’ the timer to count. If a momentary enable input is required, then this should be used ��� ���� � �� �� ������� "���� �� � ����� ��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 opera-tion, it can be seen that Port A bits 0-2 act as three separate input sen-sors. The combined sensor status is stored temporarily in auxiliary relay

Begin countingAn 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’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)

Fig.3.1. Using a low-speed timer to ������������� �������

being ‘high speed’. For time delays in the range 4ms to 1 second, you can use a high-speed timer, while longer delays, in the range 1 to 255 seconds, may be achieved with a low-speed timer. (Even longer delays are pos-sible by using ‘custom timer’ circuits, as will be seen in Part 4.)

The creation of a sim-ple time delay using a low-speed timer is shown in the ladder diagram of Fig.3.1 above.

This example provides ���� �� �������� �� ����(an on-delay timer), with the timer’s output bit TIML bit 0, going high five seconds after the input bit PORTA bit 0. An equivalent program, based on the PIC16F88 microcontroller, is given in Listing 3.1

!� ��������� ������-plied to the low-speed timer command ‘timl’ is the timer number, which is in the range 0 to 7. The cor-responding bit of register TIML (0-7) holds the status bit for for the selected low-speed timer. (Thus, TIML bit 0 holds the status bit for low-speed timer 0, and so on). Recall also from Part 1, that PLC command names are lower case (timl), while register names are upper case (TIML).

include "16F88_L.PLC" ; Defines PLC instructions ; (Low voltage programming enabled)

ld PORTA, 0 ; Read Enable input timl 0, 05H ; Low Speed Timer 0, final value = 5 seconds

ld TIML, 0 ; Read low speed timer 0 status bit out PORTB, 0 ; Output timer 0 status to Port B bit 1

endp ; Marks end of PLC program

���� ������������� ����������� ���������� ���������������������������� ; I/O Schedule ; Sensors = Port A bits 0-2 (1 = active) ; Armed/Reset = Port A bit 3 ; (1 = armed / 0 = reset) ; Output = Port B bit 0 (1 = triggered)

include "16F627.PLC" ; Defines PLC instructions

ld PORTA, 0 ; Load Sensor 1 or PORTA, 1 ; Or with Sensor 2 or PORTA, 2 ; Or with Sensor 3 out AUX0, 0 ; Output Alarm Sensor Status to AUX0, 0

ld AUX0, 0 ; Read Alarm Sensor status (Set input) latch AUX0, 1, AUX0, 2 ; Latched Alarm Status to AUX0 bit 1 ; Reset = AUX0 bit 2

ld AUX0, 1 ; Read Latched Alarm status timl 0, 0x05 ; Low Speed Timer 0 with 5 second timeout

ld TIML, 0 ; Read Alarm Timeout (1 = timeout reached) and_not AUX0, 0 ; Don't reset if active (* optional *) or_not PORTA, 3 ; OR with inverted Arm/Disarm input ; (0 = disabled) out AUX0, 2 ; Output Reset Alarm signal

ld AUX0, 1 ; Read Latched Alarm signal and_not TIML, 0 ; Disable if timed out (* optional *) out PORTB, 0 ; Alarm output to buzzer / indicator

endp ; Marks end of PLC program

���� �������!��� ���������������������������������������

Page 19: Teach-in-2010: Ladder Logic Programming with PIC

44 Everyday Practical Electronics, January 2010

Teach-In 2010

AUX0 bit 0, which in turn is used as the Set input to a latch circuit. The Q output of the latch is sent to bit 1 of register AUX0, while bit 2 of the same register provides the Reset input signal to the latch.

Next, the latch output becomes the ������������� �� �������� ��"������ �timer output being used to reset the �������� �� ����� �������� ��������� �� ������ ����� � �� � ����������� ���but a longer time delay would, of course, be used in practice). Finally, an audible or visible alarm output is generated by copying the latch output state to an appropriate output port bit (Port B bit 0 in this example).

Notice that two of the program lines are marked as ‘optional’ in the comments at the right. Try adding and removing these lines to see the differ�ent behaviours of the alarm, following a timeout. With both lines removed, the alarm will automatically reset after ����� ����������� � ���������� ������(suitable for a retail exit barrier alarm, for example).

However, this behaviour might cause annoyance in a residential burglar alarm, where a faulty sensor could cause �� ���������� � ����� �� � �� ������ � ������� �out. In the latter case, adding the two optional ��� �������� � ���������preventing a reset while a sensor remains active, and second, cancelling the output if the alarm has timed out.

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 ‘timl’. &�� "���� ��"��� �� ����ers, remaining command arguments are the timer number (0 to 7) followed ����� ��������� ����� ����the range 1 to 255.

2. The high speed tim�er’s status bit is available

from the appropriate bit of the TIMH register, with a value of ‘1’ indicat������������ ���� ��������� ����; �����that low speed timers use the TIML register.)

3. The timer’s internal count value increments once every four millisec�onds, giving possible time delays from 4ms to approximately one second.

Note: As you may have already �� �� ��� ��"��� �� ���� ������� ��timers are actually implemented as counters, with the input to the coun�ter being derived from an appropriate oscillator bit. This knowledge will prove useful in Part 4, when we build a custom timer.

On the bounceOne problem often encountered

when dealing with input switches is that of contact bounce. This mechani�cal effect is analogous to dropping a tennis ball onto a hard surface, and then watching it bounce several times before settling.

Exactly the same effect occurs when the mechanical contacts of a switch are

closed, but with the time for the contacts to settle being measured in milliseconds. Contact bounce can be particularly troublesome where an input switch is directly connected to a counter, with a single switch press causing the counter to increment multiple times.

A useful high speed timer applica�tion would be a switch debounce cir�������"������'?����$?������� ������� �being typically suitable. The output of �� ����� ������� ������� ��� ��� ��as the debounced input signal. Listing 3.3 gives a simple example, written this time for the PIC16F887 microcon�troller, and making use of a repeating input waveform being derived from an oscillator bit.

Pulsed outputsThe timers considered so far have all

� ������ �:���� ���#���� ����@����������possible to produce a pulse output by ��G������ ����� ���������������������to the program. The trick in this case is to realise that during the timer period the enable input will be high, while at the same time the status bit will be

include "16F887.PLC" ; Defines PLC instructions

ld OSCH, 7 ; Read a 15.26 HZ waveform (T = 65.54 ms) out PORTD, 0 ; Send waveform to Port D bit 0

ld PORTD, 0 ; Read Port D bit 0 ; (15.26 Hz waveform = Enable input) timh 0, 03H ; High Speed Timer 0, final value = 3 ; (T = 3 x 4 ms = 12 ms)

ld TIMH, 0 ; Read timer status bit out PORTD, 1 ; Output debounced signal

endp ; Marks end of PLC program

Listing 3.3. A switch debounce circuit based on a high speed timer (Lst3_3.asm)

include "16F887.PLC" ; Defines PLC instructions

ld OSCH, 7 ; Read a 15.26 HZ waveform (T = 65.54 ms) out PORTD, 0 ; Send waveform to Port D bit 0

ld PORTD, 0 ; Read Port D bit 0 ; (15.26 Hz waveform = Enable input) timh 0, 03H ; High Speed Timer 0, final value = 3 ; (T = 3 x 4 ms = 12 ms)

ld TIMH, 0 ; Load timer status bit out PORTD, 1 ; Output debounced (on-delay) signal

ld OSCH, 7 ; Read high speed timer Enable input and_not TIMH, 0 ; AND with inverted Status bit out PORTD, 2 ; Output pulse waveform to Port D bit 2

endp ; Marks end of PLC program Creation of on-delay and pulse output waveforms (Lst3_4.asm).Listing 3.4. Creation of on-delay and pulse output waveforms (Lst3_4.asm)

Page 20: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, January 2010 4

Teach-In 2010

outputs respectively. Notice that, based on the timebase of 5ms per division, the pulse width is approximately 12ms, which is in agreement with the delay value selected in Listing 3.4.

Use of internal storage and debugging programs

An understanding of the PLC software’s use of internal memory is useful when debugging pro-grams, and may in some cases be required when actually writing programs (as will be seen in the next section).

The PLC software uses a variety of PIC registers to hold its internal state, some of which have already been introduced. Each of these registers (around 100 in total) holds a single byte of data. Addresses associated with these registers, and others yet to be

introduced, can be viewed by opening �������� ������ �� ��� �������� 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 – after, of course, ��������� ��������� ���� �� ������� �� �� ��� �

Available debugging options related to the display of internal registers include:

1. Adding one or more ‘watch’ com-mands in an Integrated Development

low. Listing 3.4 shows the creation of both on-delay and pulsed outputs, once again using a repeating oscillator bit as the input.

Resulting waveforms are shown in Fig.3.2, which was produced with the program of Listing 3.4 running on a PICkit 2 Debug Ex-press development board, and viewed using a Tektronix TDS2004B four- channel digital stor-age oscilloscope.

In this case, the original wave-form is shown in orange, while the blue and magenta traces give the on-delay and pulse

Fig. 3.2.Output waveforms viewed using an oscilloscope

OSCH E H 01 ; High fre uency oscillator register

A 0 E H 20 ; Internal relay outputs A 1 E H 21 A 2 E H 22 A 3 E H 23 A 4 E H 24 A 5 E H 25 A 6 E H 26 A 7 E H 27 ; (8 bytes x 8 bits = 64 internal relays)

OSCL E H 28 ; Low fre uency oscillator register Listing 3.5. A small selection of internal memory used by the PLC software

Fig.3.3. Debugging with the aid of the Watch window in Proteus VSM software

Page 21: Teach-in-2010: Ladder Logic Programming with PIC

4 Everyday Practical Electronics, January 2010

Teach-In 2010

Notice that the above listing uses �� � :?Z#� � �J� ��� ������� � �� ���� ���� � J�� ������ ������ �!���� �����"��� ����� � �� "� �� ������� �� "��������� � ��������� ���[\]�����^���*�*������� ��������� ��� J��V�!� �]��&_�@`z���� ��� � �]�&\]V���� ������-� ���������������� �������� ����� ���� ������J �V������������������������������������� ���������� ���V������ J�� �������

&� "����� ���� �� ����������-���� � �#?'?'?'?'#� ������V�� �#?{|#�������V�� �#$}}#� �� �����V� ���� �##��� J�� �����V�� "���� �� � ���� ���-��� �� ������� �� ����� ��� ���� ��� ��" � ��� �� ~� � "����� ��� ������������ � � � ���� ��� ���� � ������� �� ������ �� �"������ ������-��������\ ��� �]�&\]���� ��� #��� ����� ���������������������� ������ �������

� #��� �������� ��� ������ ����� ������������������ �� J��� �������"� ��� �� "���� � � �� �� "���� ����� ���� �������������G ��� � ���������� ���������G�����������z`�

Shift registers\���� ���� ��� ��� ������������

"�������� ��������� �������� �����-���������� �� ����������������������������� ���� ���� � �� �� ��� �� � ���� �� ����������� ��������

���� ���������� -��� ����������� ����passing along a pro-����������� ��!� ���-� ���������� ���������� ������ ���� �������"�����^���*���

!���� ����� � ����� ��� � � ����� � ������ � �� ����� ���������� � ��� ��� ����"�G���� ���� ��z���� ����G� ���� ����� �� �� � ����� ���� ����� ���� ����� ���� �� � ������ ��� �� ��� ������ �� �� � �-

�"���� "������������� ���������� �� ������� ��� � ������� �� ��� ��� J� �������� V��"��� ����������������� ��������� �� � ����� �� ���� ��� � ������ ���� �� �� �� "� V�� &�������� ���������� ������ ���� ��������� ������������� �������������� ��� �"������ ��� `� ������ ������� ����"���� ����� ���� ����� �� ��� ������ �� ������������� ��������������

������ ���������� ���� ��� ������-��� ������ ��������"� ������ ��?� ��� |V�� ���� �� "����� ���� ��� ������"�G���� ���� ��!� � ������ ��� ����������������� ����G ����� �� �: ������ ��#����������� ����������������"�������������� ������ ���� �"����������{����������� �� �� ���

z��������� ���� ��������:��������#������ ������������ ����� �� � ��������� �� ����������������������" ���������G��; � ������̀ � �������������� ������ "����� � � �� ��� �� ������ �� ������� ����������������&�� ����� ��������"�G���� ���� ��������� ���� �������� ��� ��������� ���� ��������������� ������ ����� ���������������������� ��� ���!� � �����J��� �� � ����� ���� � ���-����������� �����"����� � ������

shift NUMBER[0-7],CLOCK_REG, CLOCK_BIT[0-7],RESET_REG, RESET_BIT[0-7],DIRECTION_REG, DIRECTION_ BIT[0-7]

Syntax Functionputi TE, RE ISTER Loads an immediate byte value into a destination register (puti = put

immediate).

putr RE 1, RE 2 Copies the content of a source register to a destination register, leaving the source unaltered (putr = put register).

Table 3.1. Available byte transfer commands

include "16F627.PLC" ; Defines PLC instructions

puti 0x0F, A 0 ; Load 0x0F (hex.) into register A 0 putr A 0, PORT ; Copy A 0 register to Port

endp ; Marks end of PLC program

Listing 3.6. Transferring data bytes between registers (Lst3_6.asm)

z������ ����@`zV�� ����� ������ "��� � ���� � �� ��� ���� ���� �� ��� �� ������������������"��������� � ������� �� ��� ���������������� V�

$������������� ����� ������������� ������������������� ���� ���� �����������������������"������������ ����� ��� ������� " ����� J� ���������-� �� ���z`����|�� �� ������������

Byte transfer^�� J���� �����������"��������� � ���

"� ����������� ���[\]����"� ��"������ ������������ ��� �������������� ���� � ����� ������������"������������� �̀ �����������"��� ����� J������������G������ �������� ��������"����"������ � ����� �&���@� ����_��&�� ��V������������� ����� J��� ����

z�� ��� ���� ����� � ���� ����� ���� � ��� ���� ��� ��� �"���� �� �� �J�:?Z#��������������� J�� ���������� V������� � ��� ����������������̂ ���*�*����"���� ��������������"��������� � �������� ������ "��� ���� ������������-������ ��"������"��� ����� �?�� ���� �!@]�?V�������� ����������� ���� ���-������� �����������������*�'�

\���������������"��@`z������ ������-��� �� �� �� ��� ��� ����� �"������ � ����� ������ ������������������������ � ���� ������ ������������� ��������������_�� �@�~��������������� ��� �� ��� ��������������� ���� ����������� ��� �V���� ����� �������� ���� ����������������� ����� ������ � ���� ��������� ��!��� �*�'���� ���� ������J������� ���������� ��"���������� ���������

!� ��� ������ ����� ����������������������������������� ����������������G � ����� �� � � ����� � ���������� ����������� ����� "���� :��#� ���� :���#�����������!� � J���� �����������*�{��������� ���������"� ����������������������� ����� ��������� ������ ���� ������� ��������� � ����������������������

Fig.3.4. A simple shift register

Page 22: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, January 2010 4

Teach-In 2010

Fig.3.5. Ladder diagram for a simple shift register program

The trick in this case is to under-stand exactly how data enters and exits each shift register. As already seen, the data input to a shift register is supplied by the result of the previous command. Similarly, data shifted out of one shift register becomes available to the next command (or is discarded if unused). Thus, all that is necessary to cascade multiple shift registers is to write each shift register command on successive lines, so the output of one shift register then becomes the input to the next.

Use of one or more Watch state-ments is a useful strategy when debug-ging programs containing multiple shift registers, as long as a suitably equipped IDE is available. You may then create a watch statement for each shift register and observe data rippling through from one working

register to the next. (Note in relation to Listing 3.8 that registers SHIFT0-SHIFT2 make use of memory loca-tions 0x47-0x49.)

Light chaser!� ������ 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 graphi-cally in Fig.3.6.

A latch is used to control the di-rection of the shift register, with the latch being automatically set and reset as the illuminated bit ‘bounces’ off each side of the output register. Changing the direction of the shift register is achieved in software by linking the latch’s Q output to the

Fig.3.6. Animating a simple ‘KnightRider’ display

A simple shift register application is shown by the ladder diagram of Fig.3.5.

The example program uses a 0.25Hz input signal as the data input to a shift register, with the clock being driven by a 1Hz signal. This creates an alternating pattern of two ones, followed by two zeros, since the clock frequency is four times faster than that of the data input.

A visible output is produced by the ‘putr’ command, which copies the shift reg-ister’s output register (SHIFT0) across to Port B. The equivalent pro-gram is given in Listing 3.7, in this case based on the PIC16F627 mi-crocontroller.

It is also straight-forward to link or ‘chain’ multiple shift registers, as shown in the example of Listing 3.8, this time written for the PIC16F887 microcontroller.

include "16F887.PLC" ; Defines PLC instructions

ld OSCL, 7 ; Read OSCL bit 7 (Data input) shift 0, OSCL, 3, PORTA, 0, PORTA, 1 ; Shift register 0 ; Data in = OSCL bit 7 ; Clock = OSCL bit 3 ; Reset = Port A bit 0 ; Direction = Port A bit 1 shift 1, OSCL, 3, PORTA, 0 , PORTA, 1 ; Chained shift register 1 shift 2, OSCL, 3, PORTA, 0 , PORTA, 1 ; Chained shift register 2 putr SHIFT0, PORTD ; Copy SHIFT0 working register to Port D

endp ; Marks end of PLC program Listing 3.8. Chaining multiple shift registers (Lst3_8.asm).Listing 3.8. Chaining multiple shift registers (Lst3_8.asm)

include "16F627.PLC" ; Defines PLC instructions

ld OSCL, 5 ; Read OSCL bit 5 (Data input) shift 0, OSCL, 3, PORTA, 0, PORTA, 1 ; Shift register 0 ; clock = OSCL bit 3, ; Reset = Port A bit 0, ; Direction = Port A bit 1 putr SHIFT0, PORT ; Copy SHIFT0 working register to Port

endp ; Marks end of PLC program Listing 3.7. A simple shift register program (Lst3_7.asm)Listing 3.7. A simple shift register program (Lst3_7.asm)

Page 23: Teach-in-2010: Ladder Logic Programming with PIC

4 Everyday Practical Electronics, January 2010

Teach-In 2010

shift register’s direction input and then using the state of the left and right bits of the shift register’s output register to set and reset the latch, respectively.

If a single illuminated bit can somehow be ‘injected’ into the shift register then this pattern will continuously shift left and right, as the latch is set and reset. Thus, the remaining problem is to inject an illuminated bit into the working ���� ������ ��������� �

In comparisonOne answer would be to design

a combinational logic circuit that would detect the binary pattern ‘0000 0000’ and then automatically inject a logic 1 into the shift register. This is quite feasible, but a simpler solution would be to introduce an appropriate instruction from the byte comparison family of commands.

These commands either allow a reg-ister to be compared with a numeric value (immediate value), or permit two registers to be compared, with the command outputting a logic 1 if the result of the comparison is true. Avail-able byte comparison types include:

Greater than (immediate and register-based – gti and gtr commands)

Greater than or equal (immedi-ate and register-based – gtei and gter commands)

Equal (immediate and register-based – eqi and eqr commands)

Not equal (immediate and register-based – nei and ner commands)

Less than (immediate and register-based – lti and ltr commands)

Less than or equal (immediate and register-based – ltei and lter commands).

Thus, we can use the ‘eqi’ (equal to an immediate value) command

to inject a logic 1 into the shift register, should the output register be empty. The resulting program is given in Listing 3.9, written for the PIC16F627/627A microcontroller.

Notice that the program uses bit 0 of Port A as the reset input. This is �� �������"������ ����������������-ally enable and disable the output display. If you want to run the shift register continuously then it is pos-sible to permanently disable the reset input, either in hardware or in software. The hardware approach is to physically ground the reset input, although this effectively wastes an input port bit.

You can also disable the reset input in software, by replacing the refer-ence to PORTA, 0 with a reference which always returns a ‘0’. To this end, the PLC software provides a reg-ister with the name ‘LOGIC’, with bit 1 of this register preprogrammed to a value of ‘1’ and bit 0 of the same reg-ister containing ‘0’. Thus, replacing the reference to ‘PORTA, 0’ in Listing 3.9 with ‘LOGIC, 0’ will permanently disable the reset function.

This is clearly a remarkably com-pact program, considering the com-plexity of the task performed. The main sub-tasks performed by the program are:

1. Using a latch to control the shift register direction.

2. Setting and resetting the latch when a non-zero bit reaches bits 7 and 0 of the shift register’s working register, respectively.

3. Injecting a logic 1 into the shift register if the working register is empty.

4. Copying the shift register’s work-ing register to an output port, in order to make it visible.

5. Optionally allowing the display to be blanked by resetting the shift register.

!��������������� -standing of the program’s operation, you should en-sure that you can match each of the above descrip-tive points to the actual section of code perform-ing that task.

Note that we’ll be using a sequencer com-mand later in the series to create much more

��" ��� ���� � J��� � ������ �� ���-plays than those seen so far – and the associated programs will be even shorter!

SummaryPart 3 of the series has contin-

ued the tour of the PLC software’s sequential logic capabilities, focus-ing on timers and shift registers. Low-speed and high-speed timers have been introduced, offering time delays ranging from four millisec-onds to approximately 255 seconds. !� � ������������ �� ���� ���� ����pulse output timers has been dis-cussed, and these have been applied in applications as diverse as alarms and switch debounce circuits.

A range of shift register applica-tions has also been developed. This has included the use of single and chained shift registers, repeating pattern displays based on oscilla-tor bit inputs, and even a simple KnightRider-style display.

We have looked at the use of in-ternal memory by the PLC software, and have seen how this knowledge could be used when debugging PLC software, either by adding watch statements, using a suitably capable IDE, or by adding debugging instruc-tions to programs. A number of byte processing instruction categories has also been introduced and used to sim-plify the coding of programs (selected byte transfer and byte comparison commands were used).

Next monthThe next part of the series will in-

troduce further sequential logic capa-bilities of the PLC software, including counters and the creation of pulse-width-modulated (PWM) signals.

include "16F627.PLC" ; Defines PLC instructions ; Latch controls shift direction ; (direction changes when 1 reaches end)ld SHIFT0, 7 ; MSb of working register = Set input latch A 0, 0, SHIFT0, 0 ; A 0, 0 = output ; LSb of working register = Reset input e i PORT , 0x00 ; Input a logic-1 if Port = 00000000 shift 0, OSCL, 0, PORTA, 0, A 0, 0 ; Shift register 0, clock = OSCL bit 0, ; Reset using Port A bit 0 = 1 ; Direction = output of latch putr SHIFT0, PORT ; Copy SHIFT0 working register to Port

endp ; Marks end of PLC program

Listing 3.9. A simple light chaser program

Page 24: Teach-in-2010: Ladder Logic Programming with PIC

HandsOn Technology is a manufacturer of high quality educational and professional electronics kits and modules, uControllerdevelopment/evaluation boards. Inside you will find Electronic Kits and fully assembled and tested Modules for all skill levels. Please check back with us regularly as we will be adding many new kits and products to the site in the near future. Do you want to stay up to date with electronics and computer technology? Always looking for useful hints, tips and interesting offers?

http://www.handsontec.com

Inspiration and goals... HandsOn Technology provides a multimedia and interactive platform for everyone interested in electronics. From beginner to diehard, from student to lecturer... Information, education, inspiration and entertainment. Analog and digital; practical and theoretical; software and hardware... HandsOn Technology provides Designs, ideas and solutions for today's engineers and electronics hobbyists.

Creativity for tomorrow's better living... HandsOn Technology believes everyone should have the tools, hardware, and resources to play with cool electronic gadgetry. HandsOn Technology's goal is to get our "hands On" current technology and information and pass it on to you! We set out to make finding the parts and information you need easier, more intuitive, and affordable so you can create your awesome projects. By getting technology in your hands, we think everyone is better offWe 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 [email protected]. And as always, feel free to let your geek shine - around here, we encourage it...

Page 25: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, February 2010 49

Teach-In 2010

By Walter Ditch

TEACH-IN 2010LADDER LOGIC PROGRAMMING FOR THE PIC MICRO Part 4: Counters and Pulse- Width-Modulated Waveforms

PART four of this series on ladder logic (PLC-style) programming for the PIC micro continues the

tour of sequential logic features by looking at counters and the genera-tion of pulse-width-modulated (PWM) waveforms. (Recall that previous in-stalments have covered topics includ-ing inputs and outputs, combinational logic, oscillators, latches, timers, shift registers, byte transfer and byte com-parison commands.)

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’s you!) simply uses ladder logic program state-ments to connect together the required electronic building blocks in order to construct a fully working system.

A machine code program is then automatically generated for the chosen PIC microcontroller by using the as-sembler’s macro substitution feature. This process has close parallels with the use of a compiler to convert a high level language program (such as BASIC, Pascal or C) into machine code – includ-ing, 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 pro-grams, and the source code programs are normally very concise.

I hope that you will use the tech-niques presented here in order to adapt the example programs, and to develop new ladder logic programs. It really is most satisfying to see your own design running on a small piece of silicon, per-forming tasks exactly as you intended!

SoftwareAs 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’ll also need ��� ���������������������� �����which should be ‘unzipped’ 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 simula-tion software such as Proteus VSM from Labcenter Electronics.

Counter applicationsAs their name suggests, counters are

used when you need to keep track of the number of times an event has oc-curred. In its most basic application, the counter simply provides a signal when the predetermined number of input signals has been detected – as in a simple unidirectional counter. Counters are also available which can count up or down – a bidirectional counter. Both types of counter main-tain a running total of the number of inputs received, in addition to the ������ ���������������������� ���output.

Counters may be used as build-ing blocks in a wide variety of more complex designs, with motor control being a typical application. For ex-ample, linking a counter to a stepper motor controller will allow a simple position control system to be created. It is also possible to vary the speed of a DC motor by using a counter as the input to a variable PWM waveform. In this case, a unidirectional counter would provide a ‘soft start’ feature, and a bidirectional counter would allow the motor speed to be dynamically increased or decreased.

Unidirectional counters may also be combined with oscillator signals to create custom time delays, as will be seen shortly.

Page 26: Teach-in-2010: Ladder Logic Programming with PIC

50 Everyday Practical Electronics, February 2010

Teach-In 2010

on a simulator, such as Proteus VSM, compared to a real PIC development board – and the difference is no fault of the simulator. Switch bounce is an un-wanted effect associationed with real switches, and can cause the counter to jump forward by an unpredictable number of steps for each key-press. Fortunately, a software-based switch debounce circuit has already been developed (refer back to Listing 3.3 and associated text) which can be easily added, as given in the program of Listing 4.2.

On-delay timerYou can see that the original input

to the counter (bit 0 of Port A) is now used to drive an on-delay timer hav-ing a delay of 12ms. The output of the on-delay timer (bit 0 of register TIMH) in turn becomes the input to the coun-ter, with the remainder of the second ����� �������������� �������������useful exercise is to load the programs of Listings 4.1 and 4.2 on to a suitable development board, comparing the ac-tual number of switch presses required to set the counter’s Status bit – the ����� ��� ��� ��������������������exactly ten switch presses every time.

As mentioned earlier, it is easy to create a custom timer by combining an oscillator waveform and a unidirec-tional counter. Referring back to Part 2, Table 2.1, it can be seen that a variety

Unidirectional countersThe PLC software provides up to

eight unidirectional (up only) counters, plus a further eight bidirectional counters. Operation of a basic unidi-rectional 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 oscil-lator hard-wired to its input. A simple unidirectional counter application is illustrated by the example of Fig.4.1.

include "16F88_L.PLC" ; Defines PLC instructions ; (Low voltage programming enabled) ld PORTA, 0 ; Read Port A bit 0 (clock input) ctr 0, 0AH, PORTA, 1 ; Counter 0 ; Final value = 10 (0AH), ; Reset = Port A bit 1

ld CTR, 0 ; Read counter 0 status bit (1 = finished) out PORTB, 0 ; Output counter 0 status to Port B bit 0

endp ; Marks end of PLC program

The previous input value provides the clock input to the counter, which is typically the result of a ‘ld’ or ‘ld_not’ instruc-����� "�� ���� � � �-eter actually supplied to the ‘ctr’ command is the counter number, which must be in the range 0-7. Remaining � � ������ ������� ��value (1-255), followed by the reset register and reset bit (0-7).

Each rising edge of the Clock input causes the internal counter register to increment. The counter’s Status bit becomes set when the counter reaches its ���#����� ����� �� ��value, which is in the range 1-255 (a final value of 10 is shown in the example of Fig.4.1). The counter’s status bit is available from the

Listing 4.1. Counting pulses using a unidirectional counter (Lst4_1.asm)

equivalent bit of the CTR register (so, for example, bit 0 of the CTR register holds the status bit for counter 0). Both the internal count value and the status bit are cleared by applying a logic 1 to the Reset input. So, the Reset input must be held low during normal operation of the counter.

The internal count value is not re-quired in simple counter programs, so ����������������$���� ������������� ����� ������� %& ��� '� �*�� ��� ������������%& ���'�+*��/������������� ��count values are available, if required, from registers CTR0-CTR7 respectively, and this running total may be used in more advanced applications. (An in-ternal 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 volt-age programming enabled on bit 3 of Port B.

The program uses the result from the previous command as the Clock input (obtained by reading the state of Port A bit 0), while Port A bit 1 provides the Reset input to the counter. The Status bit for counter 0 is loaded from bit 0 of the CTR register and is displayed on Port B bit 0.

This is one program which may give a visibly different result when tested

Fig.4.1. A simple counter circuit, shown in ladder diagram form

include "16F88_L.PLC" ; Defines PLC instructions ; (Low voltage programming enabled) ld PORTA, 0 ; Read Port A bit 0 (Count input)

timh 0, 03H ; High Speed Timer 0, final value = 3 ; (T = 3 x 4 ms = 12 ms) ld TIMH, 0 ; Read timer status bit (debounced input) ctr 0, 0AH, PORTA, 1 ; Counter 0, final value = 10 (0AH), ; Reset = Port A bit 1 ld CTR, 0 ; Read counter 0 status bit (1 = finished) out PORTB, 0 ; Output counter 0 status to Port B bit 0

endp ; Marks end of PLC program Listing 4.2. Adding a debounced switch input to the simple counter application (Lst4_2.asm)

Page 27: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, February 2010 5

Teach-In 2010

of oscillator frequencies are available from registers OSCH and OSCL, with period times ranging from 512�s to 16.77 seconds. Combining these inputs with the ability to count from 1-255 input cycles gives an incredibly wide range of potential time delays, ranging from a few milliseconds up to a maxi-mum of 255 × 16.77 seconds, or 4,276 seconds (approximately 71 minutes).

As an example, let’s assume that a time delay of 20 minutes (1200 seconds) is required – for a burglar alarm time-out perhaps. A quick calculation shows that 1200 seconds ÷ 255 would require a period time of 4.7 seconds, which unfortunately is not directly available from the OSCL or OSCH registers.

However, from Table 2.1, the next higher period time is 8.389 seconds, which is available from bit 6 of the OSCL register. A quick calculation shows that a count value of 143, combined with a period time of 8.389 seconds would give a calculated time delay of 1199.627 sec-onds, which is very close to our required time delay value. Listing 4.3 shows how this might be coded for the PIC16F627 microcontroller.

Don’t expect this program to do anything too exciting – it takes 20 minutes just to turn on a single LED! However, it might be useful to combine this custom timer with the burglar alarm program previ-ously seen in Listing 3.2, in order to provide a more practical time-out period. (This is left as an exercise for the reader.)

Longer delaysIf even longer delays are

required, then it is pos-sible to cascade multiple counters, in a similar way to the shift registers seen in Part 3. You can link up to eight counters, thus creating a single hybrid counter/timer up to eight bytes wide. The trick in this case is to use each counter’s

status output ‘directly’ as the count input to the next stage, at the same time using it to reset the current stage ��������������������;����������previous counter will then cause the next stage to increment, before reset-ting the current stage back to zero. As an example, Listing 4.4 shows a two-stage custom timer, this time written for the PIC16F887 microcontroller.

A repeating 1Hz oscillator waveform �������� ����������������������������� �� ��� ��� ��������+��<�����that the counter uses its own status bit to reset itself back to zero. The output ���������������� ��� �� ������-comes the input to the next counter (or may be manually read from bit 0 of the CTR register), causing the sec-ond counter to be cascaded from the ����=� ��� ���� ����� ��� ��� ����of six, and once again using its own status bit as a reset signal. The state ��� � �� ������� ��� �� ���� ������� ��registers PORTC and PORTD, allowing direct viewing on LEDs assumed to be connected to these ports. (Listing 4.4 is particularly suitable for use with the Proteus VSM 16F887 simulation supplied with Part 1.)

The next section considers bidirec-tional or up/down counters, which tend to be more versatile than their unidirectional counterparts, although quite similar from a programming perspective.

Bi-directional (up/down) counters

Eight bi-directional counters are available, and suitable for applications

where it is necessary to count values which may either increase or decrease. Consider as an example, a system designed to control entry to a car park, based on the number of spaces available. In this case, the number of spaces available would

decrease as cars enter the car park, but would rise as cars leave.

Coding of the bi-directional counter command is similar to its unidirec-tional counterpart, but with the addi-tion of a direction control input. The ctr_ud command has the following syntax:

include "16F627.PLC" ; Defines PLC instructions

ld OSCL, 6 ; 8.389 s periodic time clock input ctr 0, d'143', PORTA, 1 ; Counter 0, final value = 143 ; Reset = Port A bit 1 ld CTR, 0 ; Read counter 0 status bit (1 = finished) out PORTB, 0 ; Output counter 0 status to Port B bit 0

endp ; Marks end of PLC program

Listing 4.3. Using a custom timer to create a 20 minute delay (Lst4_3.asm)

include "16F887.PLC" ; Defines PLC instructions

ld OSCL, 3 ; Count 1 second pulses ctr 0, d'10', CTR, 0 ; Count to 10 then reset ctr 1, d'6', CTR, 1 ; Count to 6 then reset

putr CTR0, PORTC ; Copy low byte to Port C putr CTR1, PORTD ; Copy high byte to Port D

endp ; Marks end of program Listing 4.4. Creating a multiple-byte custom counter/timer (Lst4_4.asm)

ctr_ud CTR_NUMBER[0-7], FINAL_VALUE[1-255], DIRECTION_REGISTER, DIRECTION_BIT[0-7], RESET_REGISTER, RESET_BIT[0-7]

A further difference is the provision of two status bits, compared to the one used by the unidirectional counter. The upper threshold is set when the �� ��� ��������� ���� �����������one by the initial value. These status bits may be read from the appropri-ate bits of registers CUP (count up � ��*� ���@G<�%����������� ��*�respectively. (So, for example, the up-per and lower status bits for up/down �������������������� � �� �������������@J���K� ���@G<��K�������������*�Applying a 1 to the Reset input clears the internal count value, at the same time setting the appropriate bit of the @G<���������%������������� �������now contains zero).

Current count valueIf you need to know the current

count value, then this information is available from registers CUD0–

Page 28: Teach-in-2010: Ladder Logic Programming with PIC

5 Everyday Practical Electronics, February 2010

Teach-In 2010

cars currently inside the car park, and this would need to be scalable to an arbitrary number of digits, to suit the actual capacity. The number of available spaces would need to be displayed in decimal form, since few motorists can read binary or hexa-decimal numbers. Finally, suitable hardware interfac-ing would be required, including entry/exit sen-sors, time delays, and switch debounce logic.

In cases like this, where the PLC software doesn’t quite do what you might require, then one approach is to consider extending the PLC instruction set by

As can be seen, the mark-to-space ratio is ������� ����������-tion of time the wave-form is high, relative to the time the waveform is low. The duty cycle measures the time the waveform is high, rela-tive to the period (time) of the waveform.

The ‘duty cycle’ ap-proach is used by the PLC software, with pulse width and period ���� � ����� ���������in multiples of 1/500th of a second (ie 2ms). PWM signals may be created, based either

��������������������� �����%N������-ate’ values), or based on the content of internal registers – with the latter method being more suited to dynamic ������ ��������������#�����J����four PWM outputs of each type may be created.

The ‘pwmi’ command produces ��� �� ����� �Q��� � ���� %������ �*�PWM waveforms. The repeating pulse waveform is driven by an internal clock, which is linked to a 500Hz signal (taken internally from OSCH, 2). The three command arguments are the register number (0-3); the number of 2ms time periods the waveform should be high (1-255); followed by the total number of time periods in the waveform period (1-255). Output

@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�� ���������

include "16F887.PLC" ; Defines PLC instructions

ld PORTA, 0 ; Read Port A bit 0 ; (clock input to up down counter) ctr_ud 0, 0x0A, PORTA, 1, PORTA, 2 ; Up down counter 0, ; Final value = 0x0A (10) ; Direction = Port A bit 1 (1 = Up, 0 = Down) ; Reset = Port A bit 2 (1 = Reset)

ld CUP, 0 ; Load Up Down Counter 0 count-up status bit out PORTC, 1 ; Output final value reached status

ld CDN, 0 ; Load Up Down Counter 0 count-down status bitout PORTC, 0 ; Output initial value reached status

putr CUD0, PORTD ; Copy current count value to Port D

endp ; Marks end of PLC program Listing 4.5. Using a bidirectional counter (Lst4_5.asm)

��� ��������� �� ���� G�� ^��� ����� ���following a reset applied to Port A bit 2, the internal count value will be zero, ����� �������@G<��+�� �����������set (as seen from Port C bit 0). Assuming ������������������������������up, by applying a logic1 to Port A bit 1, then the counter will increment after � ������$���������������� ��� ��������� ����� �����@J���+�� ���������set (linked to bit 1 of Port C).

Bear in mind that the above car park scenario is used purely as an anal-ogy, and the program would certainly not be suitable in its current form to control a real car park for a number of reasons! To begin with, a display of the number of spaces available would be more useful than the number of

adding custom macros of your own. For example, the addition of a custom decade counter macro with up, down, carry and borrow connections, and ca-pable of being cascaded, would make it easy to display the number of spaces as a decimal number. We’ll look at advanced programming concepts, including cus-tomisation of the software, in the sixth ����� ��� ��������������

Creating repeating pulsesThe PLC software makes it easy to

create repeating pulse waveforms of � ������ ������� ������ ������ � ��-������ ���������������������������of their frequency and either their mark-to-space ratio or duty cycle, as illustrated by Fig.4.2.

Fig.4.2. Repeating pulse waveforms and their associated parameters

Page 29: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, February 2010 5

Teach-In 2010

capacity to modify the content of the registers used by the pwmr command at run-time, hence allowing real time control of the pulse width and period time respectively. As an example of this technique, Listing 4.8 shows the running count value of an up/down counter, being used to control the pulse width of a PWM waveform.

Operation of the program is logically divided into three sections, with the �������� ������������������������������������������������`{����-nal, and the third actually making the waveform visible on an output port.

Section 1: Applying an input to ei-ther bit 0 or bit 1 of Port A will enable the counter, but Port A bit 1 also serves to control the direction of the counter (1 = up/0 = down). Thus the former causes the counter to decrement, while

waveforms are available by reading the appropriate bits of the PWMI reg-ister. (Thus, for example, the output waveform for the ‘pwmi, 2’ command may be read from bit 2 of the PWMI register.)

Example of pwmi commandAs an example of the pwmi com-

mand, the program Listing 4.6 creates ����� �Q��� � ���� �`{� � ���������with duty cycles of 20%, 40%, 60% and 80%, and with a base frequency of 50Hz.

]Q ������������ �������������waveform in detail, notice that the pwmi, 0 command is supplied with a pulse width of 2 × 2ms (2 × 1/500th of a second), while the period time is ������� ���+�~������"������������is high for 4ms out of every 20ms, giving a 20% duty cycle and a base frequency of 50Hz. The waveform is made visible by copying the output bit from PWMI, 0 to bit 0 of Port D. Fig.4.3 shows the output produced by the program, running on a PICkit 2 Debug Express unit.

�������� ���� �������� ���Q���duty cycle waveforms, the ability

include "16F887.PLC" ; Defines PLC instructions

pwmi 0, d'02', d'10' ; 20 duty cycle on P MI, 0 pwmi 1, d'04', d'10' ; 40 duty cycle on P MI, 1 pwmi 2, d'06', d'10' ; 60 duty cycle on P MI, 2 pwmi 3, d'08', d'10' ; 80 duty cycle on P MI, 3

ld P MI, 0 ; Load P MI, 0 waveform (20 )out PORTD, 0 ; Output to Port D bit 0

ld P MI, 1 ; Load P MI, 1 waveform (40 )out PORTD, 1 ; Output to Port D bit 1

ld P MI, 2 ; Load P MI, 2 waveform (60 )out PORTD, 2 ; Output to Port D bit 2

ld P MI, 3 ; Load P MI, 3 waveform (80 )out PORTD, 3 ; Output to Port D bit 3

endp ; Marks end of PLC program

����������� ����������������������������� �������������to dynamically vary the duty cycle at run time can be more use-ful when developing applications – with potential scenarios including DC motor speed control, lamp dimmer circuits, or servo-based position control systems.

include "16F627.PLC" ; Defines PLC instructions puti d'02', AU 0 ; Put 2 into register AU 0 puti d'10', AU 1 ; Put 10 into register AU 1 pwmr 0, AU 0, AU 1 ; Create P M waveform based on AU 0 AU 1

ld P MR, 0 ; Load P MR, 0 output bit out PORTB, 0 ; Send P M signal to Port B bit 0

endp ; Marks end of PLC program

����������� ��������� ������ !"�����#$%������� ������������

&��'�� �������������������������������� ���������*��#+�6���7�8�"���9�; ��������

The ‘pwmr’ com-mand produces up to four ‘variable’ or register-based PWM waveforms. The three arguments supplied to the pwmr com-mand are the regis-ter_number (0-3), the register containing the number of pulses the waveform should be high (0-255), fol-lowed by the regis-ter holding the total number of pulses in the waveform (1-255).

A simple example is given in Listing 4.7, ���������� �����desired duty cycle parameter values into a pair of registers, and then uses the pwmr command to create a 20% duty cycle waveform.

The real power of this method is the

Page 30: Teach-in-2010: Ladder Logic Programming with PIC

5 Everyday Practical Electronics, February 2010

Teach-In 2010

Linking an up/down counter to an-other electronic sub-system (a PWM waveform generator in this case) is a powerful technique, and may be used as a building block in a wide variety of electronic systems. This concept will be explored further in Part 6, where a number of custom macros will be de-veloped, based on the general theme of ‘code conversion’, allowing direct con-nection of counters to devices includ-ing stepper motors, Gray-coded discs and seven-segment displays.

SummaryPart 4 of the series has continued the

tour of sequential logic features of the PLC software, introducing counters and

the generation of PWM waveforms. A wide vari-ety of systems may now be developed, ranging from burglar alarms to motor speed controllers – and using only a few lines of code in each case.

Next MonthWhile the develop-

ment of software using a ladder logic approach is clearly useful with microcontrollers, any practical system is likely to contain a combination of hardware and software. Essential concepts related to hardware interfacing techniques will, there-fore, be considered in the

next and penultimate part, allowing the PIC micro to be linked to a wide variety of hardware, including switches, LEDs, transistors, relays, motors, solenoids and opto-couplers.

Further byte-oriented capabilities of the software will be discussed, including the (surprisingly powerful) sequencer command. Byte-oriented logical and arithmetic capabilities will also be introduced, while other byte-�������� � � �������� ����� ��� ����;��recapped, including byte comparison and byte transfer commands.

These concepts will enable us to ex-plore a range of new applications, includ-ing LED-based animated displays, digital comparators and motor controllers.

the latter makes it increment, with the rate of change controlled by ANDing the combined signal with OSCL, 1 (a 4Hz square wave signal).

Section 2: The up/down counter is ���������������������� �� Q�����value of 31, with the running count stored in register CUD 0. This value is then used by the pwmr command as the pulse width value of a variable PWM � ����������� ��Q��������������%���pulses) obtained from register AUX1. Thus, the maximum duty cycle will be ������������������� ��������������������%���~����*

Section 3: The PWM status bit is read from bit 0 of register PWMR and copied to bit 0 of output Port B.

include "16F627.PLC" ; Defines PLC instructions

; First section configure up down counter ld PORTA, 0 ; Read Port A bit 0 (Slower input) or PORTA,1 ; OR with Port A bit 1 (Faster input) and OSCL,1 ; Clock input to up down counter ctr_ud 0, d'31', PORTA, 1, PORTA, 2 ; Up down counter 0, final value = 31 ; Direction = Port A bit 1 ; Reset = Port A bit 2 ; Up down counter working register = CUD0

; Second section configure P M signal puti d'32', AU 1 ; Put 32 into register AU 1 (= period) pwmr 0, CUD0, AU 1 ; Create P M waveform based on CUD0 and AU 1

; Third section display P M waveform ld P MR, 0 ; Load P M status bit out PORTB, 0 ; Output waveform to bit 0 of Port B

endp ; Marks end of PLC program Listing 4.8. Varying pulse width by using a bidirectional counter (Lst4_8.asm)

ELECTRONICS

TEACH-IN 2

PIC N’ MIX

A host of practical

programming and

interfacing information

C FOR PICs

A beginners guide

to using the C

programming

language to programme

PIC microcontrollers

A hostA hoosthoshooostosststPLUSPLPLPL

TheM

icrochipnam

eand

logo, MPLAB, PIC

and dsPIC are registered trademarks of Microchip Technology Incorporated in the USA and othercou

ntries

. ©20

09M

icroc

hip

Tech

nolo

gyIn

c.A

llrig

htsr

eser

ved.

Issu

e1.M

CCD10

16-02

.09.

Ele

ctronics Teach-In 2

© Wimborne Publishing Ltd 2009

All the software for the

projects/features in the

Teach-In 2 series and PIC

N’ Mix in the Electronics

Teach-In 2 book. Plus PIC

Project Source Codes and

PIC Tricks.

MPLAB®IDE V8.20 (Integrated Development Environment)

MAPS V2.32

Latest Treelink

Motor Control Solutions

16-bit Embedded Solutions

16-bit Tools & Solutions

Human Interface Solutions

8-bit PIC®Microcontrollers

PIC24 Microcontrollers

PIC32 Microcontrollers with USB

dsPIC®Digital Signal Controllers

PIC NPIPICPIIC N’ MIN’N’N’ MIMIXMIXIXIXPLUPLPLLUPPLPLULUULUUSUSULUUSUSSSULUSUSUS

USING PIC MICROCONTROLLERS

A practical introduction

Breadboard layouts to

aid understanding

Free software on CDROM

Simple programmer project

Free PIC Toolkit software

Everything you need

to get you started

FROM THE PUBLISHERS OF

£7.99

FREE

CD

-ROM

dd 1

23/03/2009 11:39:27

£9.50Including UK

P & P

On sale in WHSmiths or available direct from us:

01202 873872 www.epemag.com

ELECTRONICS TEACH-IN 2

PLUS CD-ROM

Page 31: Teach-in-2010: Ladder Logic Programming with PIC

46 Everyday Practical Electronics, March 2010

Teach-In 2010

By Walter Ditch

����� ��� ��� �� ���������������������� ������ ��������

T����������� ������ ������������� � �� �� � ���� ��� ������������� ��� ���� � �� �� ��� ����

�� � �� ������� �������� � ��������� �� ����� ��� ����� � ��� �� ������������� ������������������������������ �� �� �� ��������� � ����� ���� ����� �� ������!� "���� #��� �� ������ ��� � ���� � ��� ������ ��� �� ������ �� ����������������������$�%�&������������������ ���� ��������������� � ������� � � ��� ����� � ������������ ��������� ������������ ��������!������ �� ���������������������� �� �� ���������������������� � ��� �$'%�� ��� ����� ����������� � � ������� ���� �������� �� ����� � ���( ��������!) *��������� ��� ����� � ���� ��

���� ������ ��� ��� ���������� ���� �� � ���������������������� ���� �������� �� ��� $��� ��� +,-� �������� � �� �� �������!� .� ��� �� �������������� ������������ ������� ������ ���� � �� ��� ������� ��� ����� �$�%����� ��������� � ���� ��������� ���� � ���������������������� !"� ������ ������� �������������

������ ����������������� ����������� �� � � � ����� �� ��� �� ���� �� �� � ���� ��� � ��� ��� /���� �����������*!�"��������� � �������� 0

• � 1�� ���� � �� ����������2��� ���� ��� ���������� �������

�� �������������������� ������ �����3!

•�%� ������������ ���� ��� ������� ������������� ���������� 4� � ��� ��� !%�� ���� ��� � �� � � �� �� ��

�� ������ ����� ��� �� � � �� �������� � ����� ����� �� �� ��� ������ ������� ���� ����� �� �������� �� �� �� � ���� ������������ �� ���������� � ������ !� .� ��� �� ��� ������ ���������� ����� � � � � ��� ��� �#���� ��� �������������� ��� ������� �� ������ �� ��� ��������� ��� � ���������� �� ��� �!

��������.������������������������������

������ �� ��� ������ �������� ���������5�"��������� ���������� ������ ���� �2����������� ��3!�6��*������� ���� �� � ���� �������� ������� $��� 7�� ������ ������� � � /��8��� �*���������� ����� ������ �� ��������� ����� ��� ������� ������������ �� �� �!�-# � ��� � ���� �� � ����� ��

�� � �� ��� ����� � -$�.1� '��������� �� ����������� � � � �� ����� ��� � �� � ���� � �������!�.���������� �� ����� �� ����������� ��� �� � ��������� ��������� �� ������� � $'%� � � ���� �� ��������� �������� ������ �������� ��$'%������������� ����� ���������������

������ ��������$��� ���+,-��������� � ���� �������!

�������������� �� ����$'%������������� ���� ���� ��� ��

��/ �� �� ������ ��*���� � ��� �$'%�� ��� �� � ( ���� � �� � ���������� � �� ���� � ��� � ������� �� � ��������������!�.������������������� ������9���������������������� ��������� ������ ����� �����$�%������ ����������� ������� �� ��� ������������ � � �� �$'%�������������� ������ ���� �!������ �� ������ ������ � � � ���� �� � � � �������������� �� ���� ��� ����� �� � �� �������������� ������ � ����� �� ���� ����������������������� ���� � ��� �!.� ��� ������ ��� ����� � ��

� ������� ���4� ���������� ������������ �� ��������� � �� ��������� �� ��������������� � ��� �!� '����� ��������� ������������������ ��������������%���������������� �������� �������� ��� �� ��� ��� ������������������������&����� ����� ������ �������������������������������!������ � �� ������ ��� ����

����� � �� � � � ����� ����� �� � $'%����������� ���# ��������� ���� ����������� ���������������� ��������������������� ���������������� ���������������� ��!

��������� ������������������������������������

Page 32: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, March 2010 47

Teach-In 2010

:�� 0� "� � ������� �� $'%� ������������� ��� ��� �� � �� � ������������ �� � �� ��� �������� � ���������� �� �� ��� $���� 1!� "���� ������ �������� ���������� �$�%������� ����� ������ �������� � � ������������������ ������������� � �$����1� ��������� ���������������2������ �$'%7;<== ���� �3!)��� � �� � �������� 2<��!>!73� ��� � �

�� � ������������ ��� ���� �������# ������� �$'%��������������� �� 4�� ����� ���� � � �� � �� ����� ���� �� ����# ��� �������� ��������������� �����!����� ������� ���������� ���������� ��������� �4��� ���# �������������� ��������� ���# ������������� ������ ������������� ������ � ��� ����#���� � ����������#������ ��� �!�.���� ���������������������������

� ������� ���������� ����������������� �#������ � �������������������� ���������� ���2��� �����3����������� �� �����!�?�������� �9����������������������� ��� �������� ���������������� ����� � ������� �������� ����������� ��������� ����� ����� ����������� ��� �!

������� �����������.������������� �$'%������ ����� �

����������� ����������������� ����������������@>�.���������������7�2���� �� � ��� /����� �*� ��� (�������������� ���3������������A�2���� ��(����������� �������� ���/��#*3!��� � ����� � ����������� ���� ��

�������������� ��������� ��� �������� ����������������������������������������� ��&�������� ���4��� �� ��� ��� ����!� ,�� � ���� �� � � ���� ��� ���0

•�$'%7;<;@ .9;@=.9;B=.�&������������� ����#9����� �����$?C".���$?C"1�2����� �3�D�@AA�.!

•�$'%7;<= �==�&������������ ����#9����� �� ��� $?C".� ��� $?C"1�2� ��� ��3�D�7AA�.!

•� $'%7;<== � &�������� ���� ����#9����� ������������������� ��D�EA�.!� ���� ��������� ���� ����� � �

�� �� ��� �� �������� ���� �� ��#���� ����� ��� ����� �� � �� ���� ��� ��������� �� ��� �� � ��� � � ��� !� <��� ���� ���� �$'%7;<;@ .9;@=.9;B=.������ ����� ���� ������������� �0

•�-���������� ���������+,,����2 ���� ���� �����������3�D�FAA�.!

•�-���������� �� ����+������2������� ���� �����������3�D�@>A�.!

���������������������������"� � � ����� � ����� � ��� ������

���������� ������ �� ��� ������� ��������� �$'%������ ������������� � ������ �� ����� �� �-���������� ���� �2������ �� ���� ��3���$�<�2$����� ������ �� <����3� ����������� ��� � ��������� ��� ��������� �.��� �C � �������� !�$'%� � ��� �� � ���� ��� ����� ���

��������� �� �� ��� ���� �� ������������������# ���� ����������� �������� ���� ������ �������� ������������������ �� � ��� �� ��� ������ ���� ���������� ���������������!

���� ��������������� ���$'%������������� ���� ��� ����

� �������%-?,�� ������������������������������������� ������� ������ ���� ��� �� ���� �������� ��������� ��2������ #� ����� ������7�.����� ����� �� � ������ ������ ��������� �''����� � �3!�.�� ���� ������ ��� ������������������������ � ���� ��� ��� ������ ������ ��������� �+'����+'����� � ���� �� ���� ������������������������������ ������ �������� ������������� �+��!�"������� ������� ������������

����>+���� ����������������������������������������A������� �� ������ ���������� ����� ��� �A+����A! >+�2A!7>�G�+��3������ ��������7������� �������� ����� ��� �@!A>+����>+�2A!@>�G�+���H�A!=+3!"�����# ������ ���� ��������������

���� ��� ������� ����� ��� �������������� ����������������� ������ ��

��������������� ����������� �����������!�"��������������� �����<��!>!7!2'��������� ��� � ���������������

�� ������ ���� ��� ���� � ����� ���� ����������������������������������������������������$����.������ � 4���� ����������������������$����1!3�:���� ������� ������������������ �

���� � ����������� ������� ���������� � ������ ������������������� �������� !�,������,)7������� ������ ����� ��������������7��� ����� �������� #�������������� �������C7��� ��� !�,������,)@���C@������� ��� �������� ��������!�.� ����� �� �� ���� � ��� ����� ���

������� ,)F� �� CF�� �� � � � � #���������������������������� �!�"������� �� ����������� � � �� � �� �� ���� �� ��� �� ��� �������� � �������������� ��� �� � � ��� �� ������������������ ������� ��������� ���������������� ������������ ����������������� �� ���� ������������ �!)����� ��7A#�� ������I�) ����� ��� �

��� ���� ����������������������� �� ����� �� ����� ��(����� ���������� �� ����������A!>�.�2���>AA�.3���������� �������� ������� ����������*��� #�� ����� ������������7�.�� �� ���� ����� ������� �� ����� ����� ������ �� ������� ���������������������� � ��� � � ���� ����� �� ��� � �!� "� ��� ������������� �����8 ���������9���������� ������������� � ��� �� ������������������������� ���������� � ������ ������ �� � � ����������������� ������ ��������������������!

!�����"��#��������� ���� ��������������� ���

Page 33: Teach-in-2010: Ladder Logic Programming with PIC

4 Everyday Practical Electronics, March 2010

Teach-In 2010

•� "���� ������� ��� �� ����������� D� =AA�)� 2�� �� � � ����� �������������������� ������� ����� ������ �3!.� � ���� ����� ����� ��� �� �

����� ������� ������������������ ������������� ������ �$'%���� ������������ �������������� ������ ����# �������� ���� ��������7����������A����� ����������� ��2��� ����+?����+?��� �� ���� ������� �$'%������ �3!�"� �������������������� ������������7��+?��� ���� � ����� ���+���&�A! +�������������>+���� ����������������� ����� ��� �B!F+����>+!�,��������� �� � ������� �������

����� ������������A��+?��������� ���A!;+������������A������������� ������� ����� ��� �A+����A!;+!�2"� � ������ �� � ���� ���� ������������������ �������� ������ �������� �����������@>�.������������������ ����� ������ �������������� !3"���� ��� ����� �� � � ����� �����

����� ��� � ���� ������� �� ��� ����������������������� �$'%������*����� ����� �� ���� ������ ����������� ����������������� ������������ ��� ����( ���������2'���D�@>�.���������������A���������������73!

$��������%$�<������� ���������� ���� ��� ������

�������������� ������� �� �����������������<��!>!@!.�� �� � � � �� �� � ���� ������

���� ������������������������ ����� � ���� ��� ����� ������������7�� ���������� ������������A������������@�����������7!.������������������������ ����@+�

�� � ������� ���� �� ��� 7A�.� ����

���� ��� � ������������������ ���������� � �������� ������������� ���������� � �� ������������ �� ������������� �� �� ������� ������� �������� �������������� ������!�1��������� ������� ����� ���������� ����� ��������� ��������� ������� ��������� �� �� �� � �� �� ��� ������ � �� ���� � ��� �� � ���� ���������� � �������2CB���C>3!�"� ��� � �� ����� ����@ A�������

� � ��������� ������ ������������� ���7A�.������������������� ����@! +��� ����������� �� �������� ������&�������������� ������� � � ������������� ������������� �����+?����+?�!

�����&&����&������ ��������������������&�����)� � ����� ������� ���9������� ��

���� ��� ����� � � ������� ��� �� �

� ��������� ������� �������� ��� � ���������� !� "��������� ��� � �� ���������� �������� ������� �� � ��� �� ������ ��������������������������������� �� ��� ��� ����������� !�"��# ������������� ������������� �� �� ����� ������� ��������������� ������ � ��� � �����������<��!>!F!"� � ���� ������� ��������� ��� �

��� �� ������ ��� ������������� ��� � � �� � ���� �� ������� �� ��������������� ���� ������������ ��(����������� ��� �� �����213��������������� ������ ��(����������� ������ ������ �����2%3!���� ������� ��� ������ �� ��� ���� �� ��� (��� ���� �� ��� �� ��������� �����������������2��� � ��� �����������3����������� ��(���� ���� �� ��� �� �� �� ����������������� ���������!�

!�����'���%$�������� �����������

!�����(�� �����&&������"')�&����*+������������������������ ����� �� ���

"� ������������� �� ������ ������������<��!>!F���������������������7��������A����$����1�2���;3��������������������� ������� ������������� ���>�.������ ��� �� ���������� ������������������ ����������� �������C7!�"������������� �� ��� �������� �� ��� �� � ���� ���������� ����������2� � �� ��������<�������������� ����� 4������'%9'13����� ��� ���������� ������ ��������� �!�)� ��� ������������������� �����

�������������� �7@+���������� ����������� ������ ����������������A!7+� ��� A!@+� ������ �� � ���� ����� ���� �� 2�3� J��������� �� � ���������2���+%��D�A!7+����A!@+����������������� ��������������������� �/����� �*3!,��� � �� ��� ��� � ��� ����� ����

����� ��� � ��� � ��� �� ��� ���#���

Page 34: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, March 2010 4

Teach-In 2010

!���������������������� ��������&� ������"� � �� ������ ��������� ���������

������������� ������ ��������������������������� ��� ������ ��� ��� �� ���� �������� ��� �� ���� � ��� �� �������� ����� ���� ���������� �!��4����������������������� � �������� ������������� ��� ��������� �� �� ����������� ��� ������� � ����� ����� ��� �������� �������� � �������!�.�������� ���� ��<��!>!B��������������������������� �� ����� �� ��� �� ��� ������������������� � �� �� �� ������������� �������!���� ��� �� � ��������� � �� ���

������ �� � �� �� �� ������� ��� �� ��� ��������������������� ��� �2.3��� �� ���������� ����������� ��������������������������!�"� � ����� ������ ��2K3�� ��� �������# ���������������� ���� � ������� �� ���� �� �� ��� �� � �� �� �� �������2� � ���������� � �� ��������/����������� *� �� �� ��������3!�'������ ����������������� ������ �

�� ��������� ������������� ������� �� � ������� ������� ������� 2���������<��!>!B3�� ������������� ��� ������������� � ����� 4� � �������� �� � �������� ���� ��� ������� � ������� ������ ������� �!� "����/��� � �������� ������� � �*� ��� �� ������� ������� ����������� ��� ���� ������������������������ 4��� ��

��� ������� ������� �������!� 2%�������������� ���� ������ ����� ����������� ��������������������������� ���� ����� � ���� � ������ ����������� �� ������ ������� ��� ���������� ��� � ������ � ����������������������� ������������������� ���� !3) ������� �������������������� ���

�������� � ������������������ � �� � ��� ��������� ����� ������������ �������� �� �� ���������!

��� �����&���.������������������ ��� ����� �

���� ��� ����������� �������������� �����<��!>!>!'������ ���� ���� �� �����������

������� � @B+� ����� ���� ���� �( ���� � ��� � �� ������ � � �������������� �� ������������� �� ���� ��� �� � ���������������� ������ �# � �� ��� ��� �� ������� ���������� !� "� � ������� ��� � �������� � � �� � ��� �� ���� � �������� � � ��� ����� �� �� �� � �������� �� �� �� � �� ���� � ��� ��� �� ������������� ������������ ��� ��������� � ���� ��� /4� ����*� �� � ���� ���� ����� ����� � ���# � ��������������� ���� ������!"� ��� ������������������ ��� ��

��� ���� � ��� �� ��� �� ��� ������� ������ ����� �� � �%� �������� �� �� ���������� ��� � � ��� ����� &� ����� � ���������������#����� ������

��#� ����� �� � ������� ��� �� � ������� ������������ ����!�"���# �� ���� ����������� ���������� ����7@+�������� ����� ����@B�!�.������ ���������������������� ��������� �������� �A!>.��������������� ��������������������� ������ ��� ��������� ����� � +%�2�3� ������� � �����7@+���'%��� �� ������A!>.�����������4��� ��������������!�: ������ ���������<������� ��� ��

������� ��������������� �������������� ����������� ��� �� 4��� ���� ����� ��2'12��3�D�'%9�<�2��33!�,������ ���� �� ��� �<�2��3� D� 7AA� �� '%� D�>AA�.���� ��� �� 4��� ���� ����� �������� �>�.!�2C ��������� � �����# ��������� ����� ���� ��@>�.������ ������������������� �$'%*�������������� ��������������� ����>�.�(������������$����1�����A������� �� !3"� � �� � ���� �� J������ ��� �

��������������������� �� ���� ��������������� ����������� ������������� ���A! +��� ����������� ��� �� ���� ��� �������� ��� ������������������� ���!�L�� ������� �� 4��� ���� ����� �����>�.�������� ����������������� ������������ ���� ������ ����� ������������ �� ������0� C7�D�+C79'1�

� D�2+?��&�+1�39'1

� ≈� >A�� 2�� � � ��� �� � �� ����� ����� ��@B�9�>M�� �������� �� �3

!�����,�������&����&���&�-���%$����&�+

Page 35: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, March 2010

Teach-In 2010

��� ��� ���J������������������������ ����!.���������������� � ��� � ��������

����������� ������ ���������������������� ������ � ����� ������ ������� ����������� ��� ��� ���� � �� � ������ ��� ���������� �� �������������������� ���� ���� ��������!�,��������������������� ����������������������� ��������� ��� ��� ����# ������/������� *�������������������������������%�������� 4�������� ������ �2��������������� �������3��� � ���� ����� �� �� �������� � �����# ��������������������������!%������������ ������ ������������

�� �� ��������������� �� � ��� �� ��������� �������������� � �� �� ������������ ���������� �!

���&��������������&�����&�����"� � � ��� ������� �������� ������

� ���� ������������� ����� ��������������� �� ���� � ����������������� �� ��� ���������� ����������������� �� �� � ��� ������ ���� ������� �� �� �� �� ��� �� � ������������������� �� ��!�"������ ��� ���������� ��������� ����� ���������������������������������� ��� ������������� ��� ������������������� �����<��!>!;!'� ����� ���� �� � @B+� �%� ��

���� ��� �� �� �� ��� � ������� ������ ���������� � ������� 2,)7� ��C7� � �� ���� ��3� ��� �� � ���� ���� ��� � ��������� �!� %������ �� � ���������� ���� ���������� ��������������������� ����� �� � ����������������� �� ������� �������!�"� � ��������� ������ �� � �����

����� �� ��� ��� �� �� � ���� ���

������ ������������ ���� � ���� ������ ����� ��������������>+� ������ ��� ��� ����������������� �!�"��������������� ���� � �� ��������������7�������� ����������� �������C@������ ��� ���� �����������������7������ ��� �� � $'%� ������������ �� �����7 �2C.A3!"������� ��������������������������

���� �!�<����������������� ������������ ������������ ������ ������������� �� � ��������������������� ��������� ��������������� ���������� � � ���� ��� �� ��� � ���� ��������������!1 �������������� ���������� ��

�����������������������$�%������# ������� ���� ������ ��������������� � ����� ������ ������� ���� � �� ������������� ����!

��������)�#�����&����������?�� ����� � �������� ����� ��

������ �������������<���!>!7����>!;�� ��� �� �� ��� ������ ������ �� ���$��� ���+,-������� ��������� � ���� �������!�2"� �������������� ���������������� ����� ���������� �� ��� �!3�"���� ����� ������ ���� �� ��������������� ������� ��������� ���������!'�������� ��� �������������� �����

������ ������������� ��� ����������������������� ������������������� ��� ���0

7!�<�������� �������������� ��������������� � ������ �/�������� *���/��������� *� ����� ��� ����� ������A9������ 7� ������ ��� � � ���� �� �������� ��� �� ���� ��!�.���� ���������/���������� *������� ��� ������������� �������������� ��� ���������������� � ����8 �!

@!�"� �� ����������������� 4� ������7-�8��������� ���� �����B-�8��� ����� �� �������������� �������� ������ ���� ��� ��������� ���������� �� ����� �� ��� ���� �!

F!� $��� ��� +,-� ������ �� � ���� ��� ��� /��� �*� ����� �������������� ��� �������� ����������������������������� ������������ ��������!� .��� �� � ��� ������� � ������ ��� ������ �� �� ����������� ������ � ������%������������ �� ��������!B!�"� �/������������� ��*�� ��� �

���� ��������� ������������� ������������ ��� � �������� � �������� � ����� �� ����������� !�

!�������� �����&&��������&�+������������������������ ����� �� ���

!�����.��������������������&������*+�������������� ���&��

Page 36: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, March 2010

Teach-In 2010

.���������� ������������������ ���������� ����������� ������ ����������������$�%���������������� � �� � ��� � ���� ����� � ���� ������ �$'%��� ��� ����������������� ��� �� �� ��������� ���������!�"� � ���� ��������#������ ���� ����� �������������� ����� �� �$�%������� �������������� ��� ����������������������������� �� ���� � �� �9�������� ���������!

/��0���������*�������*+������ �������� �� ������� �������

���������������������&����� ���� �� ���� ������� � �������� ����� ����������� ������ �� ������� ������������ �� � � �����!�% ������� ��������� �� ��� ����� � �� ���� � � ��� �� �� ��� �� ������� � ����� ��� ���� � ��� � � ���� �� �� ����������!�"��������� ������ ������� �����

������� ���� �����������������# ��� ���� � ��� ���8 �� /���#��� � ���� �*������������ ������������ ������� �������� �!� C ���� ���� ��������� ������ �������� ������������������ ���8 ����� ������� ���� ��������������� ������� �� ���� ��������� ��2�� �/����*���/����*��������� �� ���� ���������������� ����$���F3!N� ������� ���� � �����������

�� ��������������� ������������ ������������� �� � ����� �� ���� � ����� ��� ���� ����������������� ����� � �����!�"� �������� ���������� ������ ���� � �� ��� ����� � �������� ��� ��������� ��� � ����� ����������������� ����#����������� ���� ��������� ������� ��������� ����!�"������������ ��� � ��������#���������� ��������� �������� ������������������������ �� �������� ��������������������� �� �� � ����������� �������� ���� ������� ��2@*������� �� ������� �������� ���� !3"� �$�%������� *��� ���� ����� �

���� ����� �������� �� ���� ���� �� ������������ ���� �0

•�1�� �������� ���&�������� �/����*��� /����*� �������� �� ������� ����� !� 2$� � � � � �� ��#� ��� $��� F��

"�� �F!7���������F!;���������� ��� ���������� �� ����!3

•�1�� ���������������&�� ��������������������������� �������� ������������ ���� �������� �����!

•�1�� ����������&������������ ���� �� ����� �� ������ ����� �� /� �����*��/ 4�����*��/��� 4�����*��/�� � ����*������ ������������!

•�1�� ������ ����&���������������������� ���� ��2��������������������@*������� � ������� ���3!

1+���&��� �&� ������1�� � ������� ������� � ������

���������� �������� �������������.:���?C����O?C��� ���������������� �� ���� ������������� ������ �������/��#*���������� ��� �������� !�%� ���� ����� � ��� ������� �� ������� ��#� ��� � ������ � ��� ��� ����� ���������� �� ����� ������������ �������� ������� ���������������� � �� ������!����� ������ ��� ��� � ���� ��

��������� ����������������� � �� ������� ���� ������ ���#����0

•�.:�������7� ��� ����� �� � ����� �������� � �!�.:�������A������ ���� ���������������8 ��

•�?C������7����� ���� ���������������7!�?C������A� ��� ����� �� � ����� �������� � �

•�O?C������7������ ����� ������ ����!�O?C������A����������� ������ �������� � �!"� � � ����������� �� � � �������� ��

���������� ��� �� � ���� � ��� <��!�>! �� �� ������ � ����� ����� � ��� �/7A7A�7A7A*����� �� �� ������ ����� ��������� ����������#���� ����/7777�AAAA*���������� ���� ����� � ��� �������� ����������.:���?C���O?C���� ���������� �� �������������������� �� ���� ��!"� � $�%� ������ � ��� ��� ���� ����

� � ��� ��������� �������������������"�� �>!7!.�� ������ ������ � �� � �

������ �� �� ��� �� �� � �� � ���� ��� ��� ���� ���� !�:���� ������������� �� ���������/�*�2� ���� �3��

2C � ����#����$���@�<��!@!@����� ��� �/������������������ *�������!3�6��������� ��� �������������� �

�� � ���������������#��������� �������� ������� ������ ������� � ���� �������� ����� �� ����� ������� ������������&������������ �� ������ �������� � ������� ������ ������������ ��!�� ���� �� ����� � �������� ������� ��� � � ���� ����� �� ���������������� ��� ����� ��� ����������������� �!>!�$��� ��������� ���������������� �

��� � ���������������� ��������������� ��� ���� �������� -$.,-)':!�N� ����������� ��� �������� ���� ������ �-$�.1�'�������������� ��� ������������������� �� �!� 2:�� ������� �-$.,-��� ��� ������������ �������$��� ����� ������ ����� �$'%7;<== ������ ���� ��� ���� �� � ��� ����������������������� �-$.,-)':�� ������ �������� ������������� �!3;!�.���� ������������ �� �������

� ��� ��� ������� ��������������� ������� ��� ��� � ���� �� ������ �� 2'��3!� "� � /����� �����*� ���������������� ��������� ���������� �������������������������� ���� ������ � �� ���� ���� ���� ������� ��� � �������������� !�2C � ����#����$���F��<��!F!F����� ������� ��� ��� ���� �� ��������������� ����� ����������!3�?�� ��'���� ��� ������� ����� ��� ����� #������� ����� � ��� � �� ��� ������ ���� ����� ������� ��������!'�� ����'��� ���������������

������ �� � �������� ��� ������ ������� ��� ������������� ��������� �� �����!�<������ �� � �� ����������� �� �%� ������� �� �� �� �������������� �/��� �� ����������*� ������ ����� �� ���������!� '�� ���� ���� ������� �������� �� ����#������������� ����� ��� ��� ���������������� ����������� ��� ������������ ������ ������ ����������� ����!�, ��������������� �� ����� ��

���������� ��� �������� ����� �� � ��������������� ������ �����������!�"���� � ��� ��� � �� � ��� �� � � ������� �� ��� �� � $'%� ������������ �� ������� ������������������������� ���������������������� ��2� ������� �3���� ����� ���������� �������� �!�6������������������ ��� ���#� �� ������� ����������������/���� �*������� ���� �� ��������� ������������������ �� ������������!

������������ �������������������������� ����� ���������������������� ���� ����� ��������� ������������ ����

���� ������ ������������� ���� ������� �������� �������� ����

��� ����� ������������� ���� ������ �������� �������� ����

���� ������ ������������� ���� ������� �������� �������� ����

��*&����"��1+��2��������&��� � ������

Page 37: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, March 2010

Teach-In 2010

����� ���������� ���� �������� ��/�*�2��� ��� 3������ ������ ��� ���� �������� ���� �!�'� ����� ���� �� ������������� ������� ��� ��� ��������� ���� �!.� �������� ��������� ����� � �

��� � �� �� � ��� � ����� �� � ������#�������� ������������������� ������ ������# �����������������!

1+��� ���������� ��2����.���� ������� ����� �������� �

��������� ������� � ������� �� ����� ����������� �� � ������� ��������������������7���� ������ ����������������� !�'�������������� ��������� ���� (��������� ����� �������������������$���F���#����� ������ �/ 4�*�2 4��� ��� ��� 3� ���������� ������� ��� ���� ����� ���� ������������ �� ���������� �������������������F!E!"� �������� ������� �����

����������������������� ���� ���"�� �>!@!.��� ���� ��� ������� �

�������������������������������� ����� � ���� B����� ���� ����� � �� �������/.*���/1*��

������������ ����������/.�5�1*���/.�P�1*���/.�D�1*!�.�������� �������������� ����������>!7�������� � ���� �� � $'%7;<== ������������� �!"� � ������� ��� � ��

��� ��� ���������������� ����������#��������� ���� ��B���������$�����.� �� 1�� ������� �� �� ����������������� ����� ���.NOA���.NO7!�"� � ��� �� ��� ����� ��� ��� ������ �������� �� � ��� �������� ����������� ������� ���

����� ������ ����������A&@����$�����!

1+������������ ������� �����"� �$�%������� ������� ���� �����

�������� ������������������������������� ���� ������������� ���������������������"�� �>!F!"���������# ������� �� ������ �� �� ��

�� ��� ��� ���������� ������ ���� �

��� ������������������� ���������� ����@*������� � ������� ���!���� � ������ ������������������������� ����������� � ������ ��� ���������� ��� ����� � ���������� �� ����� ���� ���� ������� �������������������� �� ����� � � �� ������ ����� ����������� ������ ��������� �� ��������� !�"����� ��� ������������ ���� ���������������$'��2��������������� ������ ������ 3�������� �!"� � ���� �����������>!@�� �������

���������������������������B�������� ���������������� �� �������������=������ ���� ��!N������ ���� � ����� ���������� ���

@*������� � ������� �������� ������ ����� ���������� �� ��������� ������� ������������������>!@��������������� ���� � ���������� � ������ ��@*������� � �� �������$�����!�"� ���������� ������������� ��� ������ ��� ��� ���������� ��� �����0

•�'��=������ �� � ������������� �@*������� � ����� ���� ����� ��

!�����3��1������0���������*+���&��� �&� ������

������������ �������������������������� ����� ���������������������� ���� ����� ��������� ������������ ����

���������� ���� ������������� ���� ����� �������� �������� ����

��������������!"� ����� ������������� ���� ������ �������� �������� ����

�!"� � �!��� ������������� ���� �!���� �������� �������� ����

�����!"� � ����� ������������� ���� ������ �������� �������� ����

������������� #���� ������������� ���� #����� �������� �������� ����

�����������������!"� � #����� ������������� ���� #������ �������� �������� ����

���������� ����������������������������������������������

�������������� �!"####����" ��$%#����&��'��((��)�!������������� ��������������������������������������(�����*�����������$%#�+��,!��"�"-��������������. �!"####����" ��$%�����&��'��((��)�!������������. ��������������������������������������(�����*�����������$%��+��,!��"."-���������������������������������������������/�������$%# ��$%����������������������������0�.��������������� �#�����������������������(�����*����������!���#�����������

�*��������$%# ��$%����������������������������1�.��������������� �������������������������(�����*����������!���������������

����������$%# ��$%����������������������������2�.��������������� �3�����������������������(�����*����������!���3�����������

���(��������������������������������&��'������������(��*��,�

����������"���,2*��� ������������������4����5"����6

��*&����'��1+��� ���������� ������

��*&����(��1+������������ � ������

��� � � �� �� � � ����� �� � A���� H7@ �� �� ���� � � �������� ��� � � � �� � �7� ���7@=!�"� ����������������������� � ������� �� � ����� ����� ���� �����������8 ������������������� �� �������� ��������� ���� �@*������� � ����� !

•�$������ ��������� ���� ���� �� �� ��� @*�� ����� � ��/ ���� *���������������� ����� ������������ ������7������ �

������������ ����������� ���������������� ����� ���������������������� ���� ����� ��������� ������������ ����

���� ������ ������������� ���� ������� �������� �������� ����

"$���%�� �"$��� ������������� ���� �"$���� �������� �������� ����

Page 38: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, March 2010

Teach-In 2010

� ����!�"� ��� �� ����� ������ ����������7��� �� ��� ����� ���������� ����� ���� ���� ����#����������� �����!"� � ��������� ��

���� ������� �� �� � � �4� � �� � ��� �� ������ �� ����� ���� ��������� ����� ����� ��� �������� ������ ���� ��� ������ ��!

������ ��2*�����+�����"� � �������� � 4� � ��

�������� �# �� ��� ��� ����� � � ����� �� ��� ��� 4� � ���������� ��� � ����� �� ��$C?-� � ������ ���� ����� ������� ���������� ����� �� �������� ����� �!�,��� ���������� � ����� 4� � ������ ������� �������������@>>��� ����� � ����� �� �� � ������� ��� �� ���$C?-� � ����� �������� ����� ������������� �!�"������ ���������� ��� �� �� 4� � ������� �������� ����� �� ������������������������������������������������ �� ��� �!2:�� � ���� �� � 7;<;@ .�

�� 7;<;@=.� ������������� ��� �� � 7@=� ��� �� �������������$C?-������ ��� �7;<;B=��7;<==���7;<== ���� ��@>;���� �!�$� � �� � ����#����$���7��"�� �7!7������� ��� ����������������������� ��� ��� �!3)������� 4� � ���� ��

����������������� ����� � ���������� ����������� ��� ��� �*������������ �� ���� ���� �� �������� 4� � ��������� �������� �� � $�%�� � ���� ��������� ����!�"� � ����� �� �� ��� ������������ � �� � ��� � ���� ����� ����� ����� �� � �������� � ���� ����� ������ ���� ��� ������� �� 4� � �����J ��!�: ������ �� � ���� ���� ��� �������������������� �� 4��� ��� 4� � ����!�<������ � ������ � ��� �������� ������� ��� ����� ����� ��� ���� �� ���������!<����� ��# ������������

��������� �� 4� � �����

����������� ����������������������������������������������

��������������� �!"####����" ��$%#����&��'��((��)�!������������� ���������������������������������������(�����*�����������$%#�+��,!��"�"-���������������. �!"####����" ��$%�����&��'��((��)�!������������. ���������������������������������������(�����*�����������$%��+��,!��"."-��������������������������������������������������������$%# ��$%� �����������������4�����������5�.���������������!������$%# ��$%� �����������������4�����������6�.�����������

����(��������������������������������&��'������������(��*��,�

����������'�������������*��� ������������,2*������*����4����5'����6

���������� �3��������������������������������������������/������������������������������������������7������88���&�6�����*�9"3�##"��������

������������� �#����������������8��!����(���6����*�6�7����/����

��/������"3�" ��4�� �#���������4/�����:��7�3����(��+#63�-�����������������������������������9;�����'���(���+��0��<����,�-�

�(�������48= �����.���������������(>��/�����?������������.�

���(���������������������������&��'������������(��*��,�

����������(������ ����������&�2����������� �����������&������4����5(����6

����������� �3��������������������������������������������/�������������������������������������������7������88���&�6�����*�9"3�##"��������

����@�����48= AB �#��������������8��!����(���6������������>�������*�

���/������"3�" ��4�� �#���������4/�����:��7�3����(��+#63�-������������������������������������9;�����'���(���+��0��<����,�-��

��(�������48= �����.���������������(>��/�����?������������.�

����(���������������������������&��'������������(��*��,�����������,������ �������������������&�+�4����5,����6

������������������������������������CC��7���������������������88���&������

����*�����9"3�##"�����������������������88���&������7���������!>��7��������������������������������������/�+�/����-���,,����������������������������������������$(����3D��!>�������?����!��:��7��7���������������������������������������A��� ��������������������������������������������������*7�����������7�:��!��:E�

���������."#####�##"���������������4�(�#�6�������������."#####��#"���������������4�(���6����5��,!�����������."#######�"���������������4�(�3�6�F���+�����D-����������."#######�"���������������4�(�<�6�F���+3����D-����������."#######�"���������������4�(�)�6�F���+<����D-����������."#######�"���������������4�(�D�6�F���+)����D-����������."#######�"���������������4�(���6�F���+D����D-����������."######�#"���������������4�(���G��,!��

������������� ����������7 �&����������� ������

����������� ��@�������������������������������������������/�������������������������������������������7������88���&�6���"��F�3�##9"��������

����@�����48= AB �#��������������8��!��������������(���������������������� �#���������������:��7����(�������!����(���

���/������"�" ��4�� �<����������4/�����:��7�����(��+#6�-������������������������������������9;�����'���(���

��(�������48= �����.���������������(>��/�����?������������.�

����(���������������������������&��'������������(��*��,�

����������.����������7 �&�������������4)"�8"5!�&��9����5.����6

Page 39: Teach-in-2010: Ladder Logic Programming with PIC

4 Everyday Practical Electronics, March 2010

Teach-In 2010

���������������������������� ���� ���� �������� �� � ���� ��������� ������� $��� 7� ��� �� � � �� �!� "� ������ ������� ������������ ��������� 4� � �� �������� ����� � ����� � ���� ���������������>!F!"����������������� ������ � ��

����������� 4� � ���$����1����������� ����� � �� ��� � ���� ������ �� �������� �� ���������A����$����.!�"���� �� ������������ �� ��������������������������� �� 4� � ���������� �� 4� � ������ �� � ���� ������ �����!�"� �� 4� � ����� ������� � �����

����� �/� 4*����������������������� ����@ ��� ������� �� 4� � �2���������� ����� � ������ �� � ���� ������� �������$���7������ �� �� �3!�?���������������� ����� ���� ������ �� 4� � ����� ������� �,�Q�� ����� ������������������ ����������������1������ �/����*������!'�����4��� ������ �����������������

��������� ������� � ������������������� 4� � ������������������>!B!�'�������� ���� �/� 4� � ������ �*������������/,�Q<':��A*����������� �� ���� �� ��� ���� �� � �� � ����� ����� �� 4� � �!�.���������� �� 4� � ����� �� ��2� ��� ����������� ������ �3�������� ������������ ��� ��� ��������� ����!�"����� � ����� �� 4� � ����������� �� 4� � ������ ����!"� � � 4� � �� � ��� � ��� � ���

���� �� ��� ���������� ��� � 4�������� �� �� � �������#��� ���������� � ���� ��������� � 4� � � ��� ���� �� �� ����� ������� ����!�'������ �( ���� ����� ������ 4��� ���� ��/��� ���� ����� *����� ��� �� ������� ������������ �������� �������� � ����� ��������������������������� ������������� �� �� �!

���������� ������������ ��������� � ���� �� 4� � ������

���������� ������������� � ����� ���������� � ���������������� 4� � ����!�.������ �������������������������� ��� ����� ���� ������������ ��� ����� �������� �!'�������� ������ ����� ���������

���������������� ��� ��������8��� ���������������������$���>������ �� �� �R��������� ���������� � ������ ��� ����� ���� ��������� ������!�6��� ������� ���� � ���� � �������� ����� ��/+7!A!7S<�� �*����� ��� � �!�"�������� ������������� ��� ������ � ���� ����������� �� ������ ���������� ��� �������������� 4� � ������ ����� �� � � � ��� � 4� � ����� �� ���� �� � $'%7;<==���������

����� ��� �����������������>!>!:���� �������$C?-��������� ��� ��

���� �� ����������� ������������� ��� ������ ����� ������� @7AA!� "� ������� 4� � ���������������� ������� ����������� �� ����� ������ ������������������ ������ ��� �� ������� ������������ 4� � �������������!�.����������� ����� ������������ �

� ������� �� ���� ������� ��� �������������� ����� ������� �� ����������������� ����� ��������� �� ���� ��!� "� � � 4� � �� ����� �� �� � ����������� ��� �� ����������� � ������������� �A��� ���� ������� ���������������� ������ ���������!.� ������ � ������ ������ ������� ���

��� ����������>!;���������� ������ ����� �� � $'%7;<==� ����� ���� ����� ����������� �� �!:���� � ���� ��������� �� �����

���� � �� �������������� �� ���������� ��� �����# ����� ���� A� ��� $���� .!� 2"� � ���� �������� � ������ �� �� + ����� 7!A!7������������ �� 4� � ����������� ������������ ������# ����� ����������� ���������� ��� ������ �� � � ��� �!3C � ��������$��� ���+,-�������

���������� ��������������� ���� /������ ������*� ����� �� ��� �� �����������������������<��!>!=!�<������ ���� �� � ������� ��� ����� � ���� �� ��� ��� �� ������� �� ������ � ���������� �� ������ �� � �� ����������� �� � ������ �������������� ������ ����� �T.� �� � ����� � ���� � ���� �� �

� � ��������� ���� �� ���� ���� ����� �� ��� ������� � ���� ��� ������������� �� � ���������� 2������������� ���� ��� �� ����3!� 6���������� ��# � ��� ���#� ��� ��� �� ����������� ��� � 4� � ���� �������� � ������� ����� �� � �������!�� � ���� �� ��� �� ���� ��� ��������������� �������� � ��������� ��� ���������������� �����

�� ��� ��� ���������� �� ��� ������ ����������� �� �����#����!

������+) ��� ���� � ���������������������

��������������������� �� �������� ��� ���������� ���� ������������� ��� ��� ���� � �� ������������� � � ����� � � 4� � ���� ������ ��!�, � �������� � �������������� � ��� ������ � ����������������� �� �� ���������������������������������������� ������� !

:�-��#����'��� ������������� �� �� ��� ������

��� ���� �� ��� ������� �� ���������� �$�%������� ���� ���������� ��� ��������� ����� ��!�"����������� ���� �� ���� ��� ������� �������������� ��� �� � ������ !� "����������� � ������������ 0�

•�%��������� ��� ��������2�������� ������������������ ���������������������� ���� ��� �����3!

•�%���������������� ��&� � ������������#������� ������������������� !

•�N�������#������ ��������� ����� �����&���� ������������� ��������������� ���������2�� ���4� ���������������������� ��� �������� �������������3!

•� <��� � ��� � ���� � &� �� ������� ��� ����� �� ( ���� � ��� ��� ������ ��!

"� � � �� ����� ����� �� � �������������� ��� ����������� �� ��� ������������%������������ ��� ��������������� �� � ������������ ������������������� ��� � �������L������ !�) ����������� �������� �������������

���������� �������� ��� ������������������ ���� ����� ����������� ������ � ��( �������������� ����� �� � � 4� � ���� ��� ����������� � ����� !

!�����;�� ���� �����������7 �&������ ���������������������)�#

Page 40: Teach-in-2010: Ladder Logic Programming with PIC

HandsOn Technology

http://www.handsontec.com

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

Page 41: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, April 2010 45

Teach-In 2010

By Walter Ditch

Part 6: Customising and Extending the Software

T����������������� ������������� �������������������������� �-������������������� �����������

����� ����������� �������������� ��� ���� ������������� ����������������������������� �������������� ���������������������������������������������������������������������� ������������������������������� ���������������������� ������������������� ���� ��-������� ����������

����������������������� ���������������� �������!����������� ��������������������"����������� ����������-������ ���� ����������� #���� ��������������������������������������������������������������������������������� �������� ��� ����������� ���������� ������ ��� ������ ������������ ��� �������������

$����������������������������������-��������%��������������� �������� ���������������������������������!����-���� ���� �� ������� #����� ���������������� ���� ������� ����� ���� �������������������������&'���(��������������������� ������

�� �������������)��*��������������������+��,!������������������ ������

#��� ����� ����� ��� ����� ���� ������ �����������������������������������!�����������������������������

.�����"������������������ ���������������������������� ����������������

/� #��������� �������� � � ���� 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������������������������!�������������������#����������������!�����

TEACH-IN 2010LADDER LOGIC PROGRAMMING FOR THE PIC MICRO

Page 42: Teach-in-2010: Ladder Logic Programming with PIC

46 Everyday Practical Electronics, April 2010

Teach-In 2010

PIC16F627A, PIC16F628A, PIC-'5=5M>.�N��������������������*�-#�*:���:#�*:����,'������6�*:�������������'5=>>� N� ������������� ������'�����)��*�#�*:���:#�*:��*9�-�*:�� 99��*:�� �6�*:�� .:9,������.8�*:4�������������'5=>>?� N� ������������� ������'�����)��*�#�*:���:#�*:����,'���6�*:�� ��*:�� .:9,��� $�(7������*�7����������.������� ������ ���� ����� ��� ��-

���� ���� ������� ������ �������� ���������� ������������������������;������� ����������#������������������������������������ ��������� ������� ���� ��-����������������������������������������������������#�����'�)�0�����'1��#������������� ������������ ������ ���� �����-���� �������������� ���� �����������������������������

��������� �� ������ ����������� ��-������ ����������������� ���� ���������������������������������� �������

������� �������� ����� ��������� ����������� ����-�������� ���� .<8� ������-�����@������������������������������������ ��� �������!������������O

��� ���� ����� ����� ����� �������� ���� ��� ������� ��� ��������� ����-������ ����� ����������� ������������������� ��� �� ����� �������� ��� ���� �����������������������������������#�������������� ��������� ���� ����� �� %��� ����� ���������������������������������������� �������������������� ��������������������������

#���� ����� �������� ���� ���������� �������������� ���� ���� ������� �������� ��������������������#�����!�� ���� ����������� �� ������� � ������� ������"���� ������ ���� �������������%������������������������ ���������������� �������#������������� �������������������������������������� ��� ���%���� ��� ���� �����-����� � � ������� �!��������� ��� ���������� ������

Optimising program code#���� �������� ���������� ����� ����-

������ �������� ������� ����� ��� ���-����������������������������&

� A�����������������Q�

� �����������������������������

� ���6�!��������������������������� �������������

� ����������������������������������� �������� ����������!����������������

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)?.�� ��� �!��������� '>��� ����� ��� ���������� ��� �������������������������������� ������������ ����� ��� ���� ����� ���� ��� ����������������.��������%�����������'%��

setports movlw 0x1f ; Set bits 0-4 as inputs (1 = input, 0 = output) movwf TRISA ; Set TRISA register (Port A = all inputs) movlw 0x00 ; Set bits 0-7 as outputs movwf TRISB ; Set TRISB register (Port B = all outputs)

����������� ������������������ ���������� ��

0#��������������������� ����������������������� ������������������ �������R�������S�������1

��������� ��� ��� ���� ���� �� ������ ���������� ���� �� ����� ���� ��������� U����������������������������������������� ��������� ��������� ����������� �����"������� @������� ���� ������� ���������%��������������������������;���������%����������������� ������������������������������<*���������������07���A,+�����������'5=>>?�� ����!������������� ��� ���������� ��� �� ��������������������1

Using the watchdog timer6��������������������� ������������

��� ������������� ������ ���������������������������������������� ����� ������R�����S�� ��������� ���� ����� �� ����������������������������������������������������������������@����������������-���� ������ 0$8#1� ������� ������� ����� ������%�����������������������-��������������������������������������� ���� ��������������������������������������������

#���������������������������������-�������������������������������R��������������������S�������������������

� ���������������������M6@Q���-���������0'µ�����������������������1�������������!���������� ��������������������������������'���

(������������������������������������������ ���� $8#�� ��� ��������� ������������� ��� ���������� �������������� ��� ��������� $8#� �� ������� ��� �������� ������ ��������� ���� ���������� ��� $8#� �������� ��� ����� � �����-������������ ���� �� ���������� $8#������������������������@������������������������������������������������������ ����������� �� ���������� ��� ����$8#��������������� �������������� ����������� �����S�������������������-�������������0*9�@1�

Modifying device � �������� �� ��� ��

,��������������������������������� ��� ������������������������������������������������������������������;��-����� ��������#����!���������������-��������� ������������������������������������������������������������������� R������������� �����S�� ��� R�-����S� ������������������������������-���� �����������A�������������������������������������������������������&

Page 43: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, April 2010 4

Teach-In 2010

Methods of reducing program size

Even the simplest of lad-der logic programs is likely to use 130 to 180 program words when assembled, due mainly to the over-head introduced by the ������� ����� #���� �������not be a problem in most scenarios, since supported PIC microcontrollers are available with program memory sizes in the range '����>%�������0A� ������%����#�����'�)� ������������ �����������������Q���1

A simple way to keep track of program memory usage is to read the summary information at the end of the ����������R�������S�����0���������������� R����S� ���� �!�������1�� .�� �!�����is shown below for the PIC16F887 ����������������Program Memory Words Used: 181Program Memory Words Free: 8011

While it is vital to keep track of the size of your assembled machine code program, it is equally impor-tant to keep your source code files ������������������������������������It is always a good idea to make liberal use of comments, in order ��� �!����� ���� ��������� � � �������������#�����������������������others to understand your programs, and in any case will be removed at ��������������

#��� ������ ������� � � ������ �����-������ ��� ����������������������������any effect on the program size, as these will only be assembled if they are actu-�����������@��������������������������that additional customisation features ����������� ����� 3������� '�'�4� � � ������ ������ ���� ������ ���!��������80 program words to the minimum program size, due mainly to the use of lookup tables ������������������0������������������1�

One possibility for code ������������� ������ ���the use of a single byte-ori-ented command in place of several bit-oriented ����������.��������R���S�or ‘putr’ command, for �!������ ������ �� ����the same task as several ‘ld’ and ‘out’ instructions 0�� ��� ������ � � ����1��.��

��� �!������ �������� 5�)� ������ ����alternative ways to transfer data from ����������������������������

Another possibility for moderate ����� ������������� ��� �����%���������use of the output produced by a previ-���������������������������������!���#�����������������������������������-der logic programs, but can also offer an alternative to manually reading the ����������������� ������������������

#���%��������������������������-proach is to realise that the majority of commands leave their result, or their �������������������$��%�������������0$1�� ����������������#���������������������������������������������!�����������������������������������������.����-������!������ ��������������������‘ld’ command, which simply leaves its ������������������������������������������ �����$�����������.��������������‘out’ command takes this value from the W register, sending it to the speci-��������������������������������������commands such as counters, timers and shift registers all offer similar functionality, giving the possibility of �������������� ����� ���� ��� ���������� �����������

A������� ����!�������������������+�>�0^���S'41�����������������"���������%����

‘chain’ multiple shift registers, with the data shifted out by a previous command being left in the W regis-ter, automatically becoming the data ��� ���� ��� ��� ���� ��!�� ��������� .������������������������������������M�M�0=���S'41�������������������������were cascaded to create a custom �������<������

A potential disadvantage of this technique is the possibility of making program operation rather cryptic, so it should perhaps be used sparingly, �������������������!���������������� ����� ����������

��������������������������������� �� �����!� ����������� ���-

nario, the software’s default alloca-������ ���������!�����������������.(_4���� .(_?� 0���������� 5M� ����1� ������ ��� ���� ��������=��������������������������- �����������������������������������������������������������������������

Currently, allocated general purpose ��������������������������������������� � ���� ��������� ������� ����� ������������ ����������58N?�� 0��!�����-���1������������������������ �3�������'�'�4��9���������������"���������-��������������������������������� ������������������������������������ ���

include "16F887.PLC" ; Defines PLC instructions

putr PORTA, PORTC ; Transfer Port A to Port C

ld PORTB, 0 ; Read Port B bit 0 out PORTD, 0 ; Output to Port D bit 0 ld PORTB, 1 ; Read Port B bit 1 out PORTD, 1 ; Output to Port D bit 1 ld PORTB, 2 ; Read Port B bit 2 out PORTD, 2 ; Output to Port D bit2

; etc.

endp ; End of PLC program

����������� �����������������!��� ���������� ������ ���� ���"���#����$�

; Unused Ram locations 6DH – 74H

TEMP0 EQU H'75' ; Block of eight user defined variables (start) TEMP1 EQU H'76' TEMP2 EQU H'77' TEMP3 EQU H'78' TEMP4 EQU H'79' TEMP5 EQU H'7A' TEMP6 EQU H'7B' TEMP7 EQU H'7C' ; Block of eight user defined variables (end)

STEMP EQU H'7D' ; Stores Status register value during an Interrupt ; Service Routine (ISR) WTEMP EQU H'7E' ; Stores W register value during an ISR LOGIC EQU H'7F'LASTRAM EQU H'7F'

Defining a block of eight user defined variables.��������%�&����������� �'� (����)�����������������������

Page 44: Teach-in-2010: Ladder Logic Programming with PIC

4 Everyday Practical Electronics, April 2010

Teach-In 2010

be ‘nested’ up to eight levels deep. (However, bear in mind that the PLC software makes use of inter-rupts, hence using the stack to hold return addresses from interrupt service routines. This means that you should not nest subroutines more than seven levels deep with the PLC software.)

The subroutine is called from the main program, with the subrou-����� ���������� ��� �� ������ ������ ���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��������S�(trying to return from a subroutine which hasn’t actually been called in the proper way). This is achieved by placing a ‘goto loop’ statement after the main program, but before the sub-��������������������#���������������statement must still be the ‘endp’ macro statement, which contains an additional ‘goto loop’ statement, plus the required ‘END’ of program assem-bler directive.

While this example does dem-onstrate the possibilities of mixing assembly language and ladder logic, it is structurally rather clumsy. The following section on customisation will answer this potential criticism, beginning by developing a custom extension facility for conditional and unconditional subroutine execution. This will provide us with enhanced structured programming, plus the ability to make ‘if…then…else’ style decisions.

Adding custom extensions to the software

This section will con-sider three different cus-tomisation scenarios, each of which will add a sig-nificant new capability to the software. Topics considered will be:

Conditional program execution Code conversion Finite state machine.

(Recall from the introduction that these new features are included with the updated version of the PLC soft-�������������������������������� �the series.)

Scenario 1 – conditional code execution

In the previous section, we saw just how easy it is to add subroutines to our ladder logic programs. The ‘call’ and ‘return’ assembly language state-ments, when used appropriately, allow the use of subroutines within ladder logic programs. On the downside, we had the added complexity of ‘labels’ in the left margin, plus the need to add a ‘jp loop’ statement at the end of the main program, and before the ����������������������

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���

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 un-derstand 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 ‘subdef’ �������� ��� ����� ��� ������ �� ���-routine, which may then be called in the normal way. The macro accepts a single parameter, which is the name of the subroutine. Notice that this argu-ment is automatically placed into the left margin by text substitution, thus eliminating the need to place your own labels. The second feature of the

����������������������������������-������������#����!������ ���������5�+�creates an additional eight auxiliary registers called TEMP0–TEMP7, hence increasing the number of available ��!�������������� ����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 assem-bly language statements and ladder logic in a single source code program, provided that the actions performed are themselves compatible. A simple but useful example would be the use of subroutine ‘call’ and ‘return’ instructions, which would allow a more structured approach to program �������� �������� 5�M� ������ �� ������example.

The program may be seen to contain three assembly language statements which are, in order ‘call’, ‘goto’ and ‘re-turn’, plus two ladder logic statements ‘puti’ and ‘endp’. There is also the ‘include’ assembler directive, plus the 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 pro-gram, optionally returning a result in the W register. Return addresses are stored in a dedicated area of memory called the stack. Supported PIC micros have an eight-level-deep stack, allowing subroutine calls to

include "16F627.PLC" ; Defines PLC instructions

; Start of main program

call SUB1 ; Call subroutine 1 unconditionall

goto loop ; Go to start of scan loop

; Put subroutine definitions after main ; program, but before 'endp' statement.

; Subroutine 1 (called al a s) SUB1 puti b'00110011', PORTB ; Displa 33H on Port B return ; Return to main program

endp ; End of PLC program

Listing 6.4. Mixing assembly language and ladder logic (Lst6_4.asm)

Page 45: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, April 2010 4

Teach-In 2010

macro is a ‘jp loop’ command, which is automatically placed at the start of each subroutine, hence forcing the ����������� ����������� ��� ��� ��������of the main scan loop. Thus, we have eliminated both of the previously mentioned subroutine issues, by use of an extremely simple macro.

The second ‘ccall’ macro provides a conditional subroutine call feature, which is an alternative to the uncon-ditional subroutine call discussed previously. The idea is that the result of a previous command, such as a ‘ld’ or ‘ld_not’, is tested by the ccall statement, with the subroutine being called, only if the command returns a true result (as indicated by a logic '������������������������������ �����$�register).

The example of Listing 6.6 illus-������� ���� ���� � � ���� ������ �������‘ccall’ and ‘subdef’ macros, plus pre-viously considered ‘call’ and ‘return’ assembly language commands, to implement conditional and uncondi-tional 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 complemen-tary, based on the state of bit 0 of Port A, so only one conditional subroutine call will be made in a single scan loop.

This logical structure is important, as will now be discussed.

Tips for using subroutines with ladder logic

In a typical high level programming language, subroutines are de-signed to be called many times from the main program, thus offering a reusable li-brary of pre-tested code.

The purpose is slightly different in our ladder logic implementation, with subroutines offering a more structured program layout, plus the ability to conditionally execute a block of code if a tested condition is true.

In general, some care is needed when designing subroutine-based ladder logic programs, to ensure that individual register bits, such as inputs and outputs, are only updated once per scan cycle. For example, if an output is set to 1 at the start of the scan loop and later set to 0, the output will appear to oscillate as the scan cycle repeatedly executes. Thus, any ‘complemen-tary’ actions contained within subroutines should be called by mutually ex-clusive test conditions, as

found in an if…then…else program structure.

Available subroutine related com-mands are summarised in Table 6.1.

Scenario 2 – code conversionThe ‘retlw’ assembly language in-

struction may be used as an alternative to the ‘return’ statement seen earlier, offering the facility to place a literal ������������$�����������������������from a subroutine. This feature com-monly allows subroutines to return a result to the calling program, or pos-sibly a success/failure result code. However, with some clever coding, the retlw command may be persuaded to perform code conversion, transform-ing binary values into a variety of other

; The 'subdef' macro defines a subroutine ; ( hich should end ith a 'return' statement) subdef macro subdef arg1 goto loop ; Go to start of scan loop subdef arg1 ; Put label in left margin for call instruction endm ; End of subroutine definition macro

; The 'ccall' macro conditionall calls a ; subroutine, but onl if the previous command ; returns a 1 in the LSB of the W register ccall macro ccall arg1 andl 0 01 ; Test least significant bit of W reg. btfss STATUS, ; Skip subroutine if LSB is clear call ccall arg1 ; Call subroutine endm ; End of macro

��������,�� ����� �������� ���������� �������� ��

include "16F887.PLC" ; Defines PLC instructions

; Start of main program

call SUB1 ; Call subroutine 1 unconditionall

ld PORTA, 0 ccall SUB2 ; Call subroutine 2 if bit 0 of Port A 1

ld not PORTA, 0 ccall SUB3 ; Call subroutine 3 if bit 0 of Port A 0

; End of main program

; Put subroutine definitions after main ; program, but before 'endp' statement.

subdef SUB1 ; Subroutine 1 is called al a s puti b'00110011', PORTC ; Displa 0 33 on Port C return ; Return to main program

subdef SUB2 ; Subroutine 2 is called if PORTA,0 1 puti b'00001111', PORTD ; Displa 0 0F on Port D return ; Return to main program

subdef SUB3 ; Subroutine 3 is called if PORTA,0 0 puti b'11110000', PORTD ; Displa 0 F0 on Port D return ; Return to main program

endp ; End of PLC program

Listing 6.6. A simple conditional subroutine program (Lst6_6.asm)

Page 46: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, April 2010

Teach-In 2010

upper four bits of the binary value to zero, thus prevent-ing a potential table overflow.

One slightly un-desirable feature of this technique is that the lookup table subroutine becomes a permanent feature of the assembled program, even if the associated macro is not used. This inevitably leads to a small increase in the minimum size of assembled machine code programs, but this should not be �� ����������� �������given that up to 8k of program memory is available in sup-ported PIC micro-controllers. It should also be noted that any lookup table subroutines must be placed in the first 256 locations of program memory, in order to prevent memory page errors when the W register is added to the lower byte of the program counter.

Fig.6.1 shows a potential application of this technique to drive a single 7-seg-

ment display, with the associated pro-gram shown in Listing 6.8.

As can be seen, the resulting binary to 7-segment display program is re-markably simple, from a programming perspective at least, consisting of a single line of code. The real complex-ity is hidden in the lookup table and ���������������������������

Clearly, the method used here with 7-segment displays may easily be applied to other code conversion scenarios. With this in mind, a diverse selection of code conversion macros has been developed, covering topics including position measurement (Gray code), stepper motor control, plus bi-nary encoders and decoders, as given in Table 6.2.

Command Function call SUBROUTINE Call a named subroutine unconditionally (assembly language

statement).

return Return to the main program, at the line following the subroutine call (assembly language statement).

ccall SUBROUTINE Call a named subroutine conditionally, if the previous command returns a true result (in least significant bit of W register).

subdef SUBROUTINE Define a named subroutine.

Table 6.1. Subroutine-related commands

representations. This is an extremely powerful technique, with potential applications including:

7-segment displays

Gray code (position measurement)

Stepper motor control

Binary encoders and decoders.

The basic idea is to create a sub-routine which contains a lookup table consisting of a series of retlw statements, each of which will re-turn a particular value to the calling program. We then place our initial binary value (to be converted) into the W register prior to calling the subroutine. The subroutine begins by adding the value contained in the W register to the program counter

register, which causes the PIC micro to jump forwards in program memory ��������������� ��������������������hence returning the converted value in the W register.

The example of Listing 6.7 shows a subroutine used to convert a 4-bit binary value to a format capable of driving a directly connected 7-segment display, plus the associated macro ����������

This example creates a new ‘bin-27seg’ (binary to seven segment) macro definition, which in turn calls the ‘bin27seg_sub1’ subroutine to perform the actual code conver-sion. Notice the use of bit masking at the start of the subroutine as a data validation check, forcing the

; The 'bin27seg' macro calls the follo ing subroutine hich must be placed in ; the first 256 locations of program memor

; 7 segment displa look up table; subroutine

bin27seg sub1 andl 0 0f ; Mask off upper 4 bits of W to prevent table; overflo

add f PCL ; Add W to LSB of program counter and return; ith look up value in W

retl b'00111111' ; Displa '0'retl b'00000110' ; Displa '1'retl b'01011011' ; Displa '2'retl b'01001111' ; Displa '3'retl b'01100110' ; Displa '4'retl b'01101101' ; Displa '5'retl b'01111101' ; Displa '6'retl b'00000111' ; Displa '7'retl b'01111111' ; Displa '8'retl b'01100111' ; Displa '9'retl b'01110111' ; Displa 'A'retl b'01111100' ; Displa 'B'retl b'00111001' ; Displa 'C'retl b'01011110' ; Displa 'D'retl b'01111001' ; Displa 'E'retl b'01110001' ; Displa 'F'

; Macro definition for binar to segment displa conversion.

bin27seg macro bin27seg arg1, bin27seg arg2movf bin27seg arg1, W ; Put binar value into Wcall bin27seg sub1 ; Call lookup subroutinemov f bin27seg arg2 ; Put result in destination registerendm ; End of Binar to 7 segment

; displa converter macroListing 6.7. inary to seven segment display subroutine and macro.Listing 6.7. Binary-to-7-segment display subroutine and macro

Page 47: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, April 2010

Teach-In 2010

First, the priority encoder (pencode) macro provides the inverse opera-tion to the decoder command, and is implemented as a series of bit tests, rather than as a lookup table. Second, the swap nibbles (swap) macro is provided mainly for use with 7-segment displays, since it allows the upper nibble of a display buffer register to be swapped, prior to outputting to a connected 7-seg-ment display. The latter command allows ‘packed’ binary values to be used with 7-segment displays, as illustrated by the example program of Listing 6.9.

Multiplexed 7-segment displayThe main problem with the program

� ���������5�T����������� ������������ �output port bits, since it requires two

8-bit output ports, just to drive a pair of 7-segment dis-plays. A multiplexed 7-segment display is ����������� �������in its use of output port bits, as illus-trated by Fig.6.2.

Unfor tunate ly, increased I/O effi-ciency comes at the price of increased complexity of the software. As dis-cussed last month, a multiplexed display operates by briefly activating each digit in a rapidly repeating sequence, thus giving the illusion that all digits are simultane-ously illuminated. A suitable control program is shown in Listing 6.10.

Don’t worry if this seems complex, since the program can be broken down into a number of smaller sub-sections, each of which is relatively simple to understand.

First, registers AUX0 and AUX1 are used as a display buffer, holding the four digits in packed binary form. Bit 0 of Port A acts as a display en-able input, causing the output to be

Command Function bin27seg SRC_REG, DST_REG Use a 4-bit binary value to drive a directly connected seven segment

display.

bin2gray SRC_REG, DST_REG Convert a 1–4 bit binary value to Gray code.

gray2bin SRC_REG, DST_REG Convert a 1–4 bit Gray code value to binary.

decode SRC_REG, DST_REG Use a 1–3 bit binary code to set a single output bit (0–7).

pencode SRC_REG, DST_REG Produce a priority encoded 3-bit binary value, equivalent to the highest set input bit (0–7).

step SRC_REG, DST_REG Use a 2-bit binary value to drive a 2-pole stepper motor in full step mode.

hstep SRC_REG, DST_REG Use a 3-bit binary value to drive a 2-pole stepper motor in half step mode.

swap SRC_REG, DST_REG Swap nibbles between source and destination registers.

Table 6.2. Available code conversation macros and related commands

include "16F627.PLC" ; Defines PLC instructions

bin27seg PORTA, PORTB ; Displa binar code from PORTA bits 0 3 ; on 7 segment displa connected to ; Port B bits 0 6 (bit 7 is unused)

endp ; End of PLC program

Listing 6.8. A simple binary-to-7-segment display program (Lst6_8.asm)

include "16F887.PLC" ; Defines PLC instructions

puti 0 AB, AU 0 ; Packed digit displa buffer

bin27seg AU 0, PORTC ; Displa lo er nibble on Port C s ap AU 0, AU 1 ; S ap nibbles from displa buffer bin27seg AU 1, PORTD ; Displa upper nibble on Port D

endp ; End of PLC program

Listing 6.9. Using packed binary values with 7-segment displays (Lst6_9.asm)

Fig.6.1. Displaying a binary value on a 7-segment display

Most of these new commands make the same use of lookup tables as the bin27seg command, differing mainly in the number of input bits allowed, and the binary values returned. You

can review details of their implemen-tation by viewing the appropriate ������������������!����������@�������note that a couple of these new mac-ros are coded slightly differently:

Page 48: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, April 2010

Teach-In 2010

; Multiple ed LED Displa

include "16F887.PLC" ; Defines PLC instructions

; AU 0 AU 1 hold 4 digits to be displa ed puti 0 12, AU 0 ; AU 0 L.H. 2 digits of displa puti 0 34, AU 1 ; AU 1 R.H. 2 digits of displa

; AU 2 bits 0 1 aveforms are decoded to produce ; digit scan pulses (see also 'SCA ROW' subroutine) ld OSCH, 4 ; Read 8 ms aveform out AU 2, 0 ; Send to bit 0 of register AU 2 ld OSCH, 5 ; Read 16 ms aveform out AU 2, 1 ; Send to bit 1 of register AU 2

; Conditional subroutine calls ld PORTA, 0 ccall SCA ROW ; Scan ro s if bit 0 of Port A 1

ld not PORTA, 0 ccall BLA ED ; Disable ro scan if bit 0 of Port A 0

ld PORTD, 0 ccall DIGIT1 ; Displa digit 1 if enabled

ld PORTD, 1 ccall DIGIT2 ; Displa digit 2 if enabled

ld PORTD, 2 ccall DIGIT3 ; Displa digit 3 if enabled

ld PORTD, 3 ccall DIGIT4 ; Displa digit 4 if enabled

; Subroutine definitions subdef SCA ROW decode AU 2, PORTD ; Send digit enable pulses to Port D return

subdef BLA ED ; Turn off displa driver transistors puti 0 00, PORTD ; Blank 7 segment displa return

subdef DIGIT1 ; Displa digit 1 subroutine s ap AU 0, AU 3 ; S ap nibbles of AU 0 into AU 3 bin27seg AU 3, PORTC ; Send to 7 segment displa return ; Return from subroutine

subdef DIGIT2 ; Displa digit 2 subroutine bin27seg AU 0, PORTC ; Send to 7 segment displa return ; Return from subroutine

subdef DIGIT3 ; Displa digit 3 subroutine s ap AU 1, AU 3 ; S ap nibbles of AU 1 into AU 3 bin27seg AU 3, PORTC ; Send to 7 segment displa return ; Return from subroutine

subdef DIGIT4 ; Displa digit 4 subroutine bin27seg AU 1, PORTC ; Send to 7 segment displa return ; Return from subroutine

endp ; End of PLC program

Listing 6.10. A multiplexed 7-segment display driver program with blanking control

blanked when it is low, or enabled when high.

The next section of the program cop-ies two of the higher order oscillator bits to register AUX2, which will be used to enable the four display digits

in a repeating sequence. These oscilla-tor bits produce a two-bit binary count (00, 01, 10, 11, 00, ...) which repeats more than 50 times per second. This count is ‘decoded’ by the SCANROW subroutine, to enable each of the

four display driver transistors, one after another, but note that the SCANROW sub-routine is only called if the display is ena-bled – as controlled by bit 0 of Port A. When the enable input is zero, then a display blanking subroutine is called instead, which turns off the four tran-sistors (Fig.6.2), thus disabling the display.

Dur ing normal operation, the ‘de-code’ macro within the SCANROW sub-routine enables each transistor in turn by sending the repeating sequence 0001, 0010, 0100, 1000, 0001 … to Port D. In addition to enabling the display driver transistors, the output bits of Port D are also used to condition-ally call a further four subroutines (DIGIT1, DIGIT2, DIGIT3 and DIGIT4), which en-sures that the correct binary digit is output to Port C. (Notice also that the display driver subroutines make use of the ‘bin27seg’ and ‘swap’ macros consid-ered earlier.)

Controlling stepper motors

Two new macros have been provided to control two-pole stepper motors, in either full-step or half -step mode. The ‘step’ command takes a two-bit binary input, us-ing it to output the sequence 0011, 0110, 1100, 1001. Similarly, the ‘hstep’ macro uses

a three-bit input code to generate the sequence 0001, 0011, 0010, 0110, 0100, 1100, 1001. As its name suggests, half-step mode uses intermediate states, causing the motor to move in smaller angular increments.

Page 49: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, April 2010

Teach-In 2010

with suitable opto-coupler hardware.

Gray code uses a spe-cial binary counting sequence, such that only one bit changes at any time as the disc rotates. This property elimi-nates the potential for unwanted intermediate states as the disc rotates.

The latest version of the PLC software provides two new com-mands related to Gray code. The ‘bin2gray’ command generates a Gray code value based on a binary input, while the correspond-ing ‘gray2bin’ routine generates a binary code

based on a Gray-coded input. It is this latter command which is used to measure the position of an output shaft, as illustrated by the example of Listing 6.13.

In this case, a four-bit Gray code on Port A is converted to binary, before being output as a binary value on Port B. Bit masking techniques may option-ally be used to reduce the number of input bits, if required.

3������ �%�5������������� machine

You may recall from Part 5, last month, that a simple sequencer was used to generate one-off or repeat-ing output sequences. This feature was seen to be ideal for generation of timed output sequences, such as those

�����;���������<�������������������!

include "16F627.PLC" ; Defines PLC instructions

s ap OSCL, AU 0 ; S ap nibbles from OSCL to AU 0 step AU 0, PORTB ; Send step se uence to bits 0 3 of Port B

endp ; Marks end of PLC program

�����������=������ ��� �� (������������ � ��"���#�����$

A simple full-step program is shown in Listing 6.11.

#�������� ����������� ���� ������� ��-quency half of oscillator register OSCL into register AUX0, prior to using this value to drive the stepper motor. (It is also possible to use register OSCL directly to drive the stepper motor, but the speed of operation is then consider-ably faster.)

A more sophisticated control pro-gram is shown in Listing 6.12, with the output of an up/down counter used to provide forward and reverse control, combined with position con-trol based on the running count value.

Hardware connections to inputs and outputs are shown in Fig.6.3.

(Users of Proteus VSM may wish to add a Watch window variable for

include "16F627.PLC" ; Defines PLC instructions

ld PORTA, 0 ; Read Port A bit 0 (Count do n input) or PORTA,1 ; OR ith Port A bit 1 (Count up input) and OSCL,1 ; Clock input to up do n counter ctr ud 0, d'7', PORTA, 1, PORTA, 2 ; Up do n counter 0, final value 7 ; Direction Port A bit 1 ; Reset Port A bit 2 ; Up do n counter orking register CUD0

hstep CUD0, PORTB ; Send half step se uence to bits 0 3 of Port B

endp ; Marks end of PLC program

�����������=��������� ����� ��� �� (������������ � ��"���#�����$

register CUD0 (address 0x5C), which will allow the desired position of the stepper motor to be observed in real time.)

&�������� ���� ��������������">��!�� ��$

The example of Listing 6.12 illustrat-ed the possibility of open loop position control of a stepper motor. However, stepper motors can easily slip due to their low output torque, so the desired position and the actual position are not always the same thing. The only way to really be sure of the actual shaft posi-tion is to measure it, and Gray code is ideally suited to this purpose.

Fig.6.4 shows a 3-bit Gray-coded disc, which may be used to measure rotary shaft position, when combined

Page 50: Teach-in-2010: Ladder Logic Programming with PIC

4 Everyday Practical Electronics, April 2010

Teach-In 2010

generated by electronic toys, displays, ���������������� ����������

@�������������"���������������������������������������������������������������������!���������������������������������������������������������������������� �����������������������������!������������������������������ ���������������� �������������������������������������������������������������������������������������������������������������������������������

.������������������������������������������� ��� ������ ��� ���� ������� � �������� �������� R�����S� �������������������������������������������������������R����S������������� ����!������������������������������������!��������������������������

=������������������������������������������������������������������ ����������������������������������������������������� ������������ .�� ��� �!�������������������� �������������� �����������"������������������#�����5�+�

.�������������������������������������������������������������������������������R�����S����������������������������������5�'M�

#���������������� ������������������������N�;���������%����������N���%������������ ���������������������#�����������������������������������������!������������������������������������������������������������������������ �������#�����������������������������������������������������������������*A#.��4�0������

Fig.6.3. Using an up/down counter to control the position of a stepper motor

���������������'��������������������������������!�������1������������������������������������������������������������� � �������������� ������������ ������������%������������������������������������������������������������������������������������������������������������������������������

#��������� �������������������������������� ��������9#.#,����������������������������������������������������������� �������� R�����S������������ 0����������1��#�������������������������������������4���������������������������������������������� �����������������������������������������������������"������

#��� ������� ������� � � ���� ��� �����������������������������������������

�������� 5�'��� ����� ������������� ��� ���� '5=>>�����������������

#��� ������� ��� ��������������������������������������� ����� ���� ����������� ���� ������ ������

include "16F627.PLC" ; Defines PLC instructions

gra 2bin PORTA, PORTB ; Read a 4 bit Gra coded disc connected to ; Port A, outputting the position to Port B

endp ; Marks end of PLC program Listing 6.13. Measuring shaft position with a Gray coded disc (Lst6_13.asm)

Fig.6.4. Using a Gray-coded disc to measure rotary position

nt tat t tat an ition nt ut ut

0 1 utomatic (power up state)

ll outputs off

1 2 2 second delay ed

2 3 1 second delay ed mber

3 4 10 second delay Green

4 1 1 second delay mber

@�����%�;��������������������������������������(������)����H�����

Page 51: Teach-in-2010: Ladder Logic Programming with PIC

Everyday Practical Electronics, April 2010

Teach-In 2010

state macro state arg1, state arg2, state arg3, state arg4, state arg5 movl state arg1 ; Move state number to W or f STATE, W ; OR ith current state ( ero result ; if the are e ual) btfss STATUS, ; Check if state arg1 current state goto st v(state arg1) ; o, so goto end call state arg5 ; es, so call subroutine btfss state arg3, state arg4 ; check if state transition condition ; is true (1) goto st v(state arg1) ; o so goto end movl state arg2 ; Cop ne t state to STATE register mov f STATE st v(state arg1) endm ; End of Finite state machine macro

���������I�@)������ ��J�����K����� �������!��)�����������������)���

itself. Notice that a LOGIC, 1 value causes an auto-matic transition from state 0 to state 1, with time delay status bits causing all sub-sequent state transitions.

The second section uses ‘eqi’ comparison opera-tors to enable each timer once the STATE register is equal to the tested value. The timer output bit be-comes set on completion of the active time delay, causing a transition to the next state, at which point the next timer is enabled, and the previous timer is cleared.

#���������������������-tion contains the subrou-������������������������������������������������� ���light values to Port B.

;��������!The main aims of this

series have been to make microcontroller program-ming accessible to the widest possible audience, and to make it a rewarding experience in the process. I hope I have encouraged you to experiment and to learn more about micro-electronics.

The ladder logic soft-ware used in the series has been placed into the public domain by the author, so you are free to ���� ����������������������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 con-struction projects to EPE in the future. EPE

; Traffic Lights Finite State Machine

include "16F88 L.PLC" ; Defines PLC instructions

; First section Define state se uence

state 0, 1, LOGIC, 1, ERO ; Automatic transition from state 0 1 ; after po er up

state 1, 2, TIML, 0, O E ; Red state 2, 3, TIML, 1, TWO ; Red Amber state 3, 4, TIML, 2, THREE ; Green state 4, 1, TIML, 3, FOUR ; Amber (then back to Red)

; Second Section State transitions

e i STATE, 1 ; 2 second timeout state 1 2 timl 0, 2

e i STATE, 2 ; 1 second timeout state 2 3 timl 1, 1

e i STATE, 3 ; 10 second timeout state 3 4 timl 2, d'10'

e i STATE, 4 ; 1 second timeout state 4 1 timl 3, 1

; Third section Actions performed

subdef ERO ; All lights off after po er up puti b'00000000', PORTB return

subdef O E ; Displa Red puti b'00000001', PORTB return

subdef TWO ; Displa Red Amber puti b'00000011', PORTB return

subdef THREE ; Displa Green puti b'00000100', PORTB return

subdef FOUR ; Displa Amber puti b'00000010', PORTB return

endp ; End of PLC program Listing 6.1 . A simple traffic light finite state machine.���������,�;�����������(������)�����������������)����"���#�,���$

Page 52: Teach-in-2010: Ladder Logic Programming with PIC

HandsOn Technology http://www.handsontec.com

1

ISP to ICP Programming Bridge: HT-ICP200In-Circuit-Programming (ICP) for P89LPC900 Series of 8051 Flash μController…

…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 bootloader…

That the 80C51-based controllers are extremely popular is nothing new, certainly when considering the large number of designs thatcan be found on the web. The reason may well be the fact that the tools (both hardware and software)that are available for this controller are very affordable and there is an enormous amount of information readily available. In addition, a very active forum provides answers to many questions. One of the most significant features of the P89LPC900 Family is that the core now requires only 2-clock Cycles Per Instruction (CPI). 8051 experts will already know that this used to be 12 or 6 cycles until now. In practice, this means that the crystal frequency can be drastically lowered to achieve the same processing speed as their classic counter parts.

ISP Programming is only available for 20, 28 and 44pin parts. IAP is only available once your IAP program has been loaded in to the LPC900 part. ICP -can be used to program all the LPC900 parts.

The LPC90x devices can only be programmed using a ICP programming method. In contrast to some of the larger LPC900 family members, the LPC90x devices do not offer other programming methods like Parallel Programming, In-System Programming (ISP) or complete In-Application Programming (IAP). HOWEVER - ICP requires hardware control/ signaling of the LPC900 to be programmed.In some high-end applications, there may be a need to replace the code in the microcontroller without replacing the IC itself. This article described in detail the operation of the In-Circuit-Programming (ICP) capability which allows these microcontrollers to be programmed while mounted in the end product.

P89LPC9xx parts (affectionately know as the LPC900 series of micro-controllers) can be programmed 4 ways...

1. ISP (In-System-Programmed) using the UART of the LPC900.2. IAP (In-Application-Programmed) .. or "self programmed" by reprogramming the flash under code execution.3. ICP (In-Circuit-Programming)... using "Synchronous Serial".... Similar to SPI signaling - each data bit is clocked

in/out under clock signal control.4. Parallel Programmer, available in expensive industry grade tools.

1. INTRODUCTION

HT-ICP200 P89LPC900 Target Application Board

To communicate between a PC (running Flash Magic) and the LPC900 Micro-Controller to be programmed an "ICP Bridge" circuit is required as shown in Figure 1.

Figure 1: Hooking up ICP to the P89LPC900 Application Board