pic plc

93
PLC WITH PIC16F648A MICROCONTROLLER (PART 1) PLC/MCU www.electronicsworld.co.uk Electronics World - November 08 21 Feature The Series The articles to be published are as follows: 1. The Hardware: Run in this issue. 2. The Basic Software: This article explains the basic software structure of the UZAM_PLC. A PLC scan cycle includes the following: 1. obtain the inputs, 2. run the user program, 3. update the outputs. In addition, it is also necessary to define and initialise all variables used within a PLC. Necessary functions are all described as PIC Assembly macros to be used in UZAM_PLC. The macros described in this article could be summarised as follows: “HC165” (for handling the inputs), “HC595” (for sending the outputs), “dbncr” (for debouncing the inputs), “initialise”, “get_inputs”, “send_outputs”. 3. Contact and Relay Based Macros: The following contact and relay based macros are described in this article: ld (load), ld_not (load_not), not, or, or_not, nor, and, and_not, nand, xor, xor_not, xnor, out, out_not, in_out, inv_out, set, reset. These macros are defined to operate on one bit variables. 4. Flip-Flop Based Macros: The following flip-flop based macros are described in this article: r_edge (rising_edge), f_edge (falling_edge), latch0, latch1, dff_r (rising edge triggered D flip-flop), dff_f (falling edge triggered D flip-flop), tff_r (rising edge triggered T flip-flop), tff_f (falling edge triggered T flip-flop), jkff_r (rising edge triggered JK flip- flop), jkff_f (falling edge triggered JK flip-flop). 5. Timer Macros: The following timer macros are described in this article: TON_8 (ON delay timer), TOF_8 (OFF delay timer), TEP_8 (Extended Puls timer), TOS_8 (Oscillator timer). 6. Counter Macros: The following counter macros are described in this article: CTU_8 (Up Counter), CTD_8 (Down Counter), CTUD_8 (Up/Down Counter). 7. Comparison Macros: The following comparison macros are described in this article: The contents of two registers (R1 and R2) are compared according to the following: GT (Greater Than – “>”), GE (Greater than or Equal to – “≥”), EQ (EQual to – “=”), LT (Less Than – “<”), LE (Less than or Equal to – “≤”), NE (Not Equal to – “≠”). Similar comparison macros are also described for comparing the contents of an 8 bit register (R) with an 8 bit constant (K). 8. Arithmetical Macros: The following arithmetical macros are described in this article: The following operators are applied to the contents of two registers (R1 and R2): ADD, SUB (subtract), INC (increment), DEC (decrement). Similar arithmetical macros are also described to be used with the contents of an 8 bit register (R) and an 8 bit constant (K). 9. Logical Macros: The following logical macros are described in this article: inv_R, AND, NAND, OR, NOR, XOR, XNOR. These macros are applied to an 8 bit register (R1) with another register (R2) or an 8 bit constant (K). 10. Shift&Rotate Macros: The following Shift&Rotate macros are described in this article: SHIFT_R (shift right the contents of register R), SHIFT_L (shift left the contents of register R), ROTATE_R (rotate right the contents of register R), ROTATE_L (rotate left the contents of register R), SWAP (swap the nibbles of the register). 11. Multiplexer Macros: The following multiplexer macros are described in this article: mux_2_1 (2x1 MUX), mux_2_1_E (2x1 MUX with Enable input), mux_4_1 (4x1 MUX), mux_4_1_E (4x1 MUX with Enable input), mux_8_1 (8x1 MUX), mux_8_1_E (8x1 MUX with Enable input). 12. DeMultiplexer Macros: The following demultiplexer macros are described in this article: Dmux_1_2 (1x2 DMUX), Dmux_1_2_E (1x2 DMUX with Enable input), Dmux_1_4 (1x4 DMUX), Dmux_1_4_E (1x4 DMUX with Enable input), Dmux_1_8 (1x8 DMUX), Dmux_1_8_E (1x8 DMUX with Enable input). 13. Decoder Macros: The following decoder macros are described in this article: decod_1_2 (1x2 decoder), decod_1_2_E (1x2 decoder with Enable input), decod_2_4 (2x4 decoder), decod_2_4_E (2x4 decoder with Enable input), decod_3_8 (3x8 decoder), decod_3_8_E (3x8 decoder with Enable input). 14. Priority Encoder Macros: The following priority encoder macros are described in this article: encod_4_2_p (4x2 priority encoder), encod_4_2_p_E (4x2 priority encoder with Enable input), encod_8_3_p (8x3 priority encoder), encod_8_3_p_E (8x3 priority encoder with Enable input), encod_dec_bcd_p {decimal to BCD (Binary Coded Decimal) priority encoder}, encod_dec_bcd_p_E (decimal to BCD priority encoder with Enable input). 15. An Example: This article describes an example of a remotely- controlled model gate system and makes use of UZAM_PLC to control it for different control scenarios. The reader is expected to be familiar with PLCs, PIC microcontrollers and PIC Assembly language. UZAM_PLC macros are developed by using PIC Assembly language. The program development environment used is that of MPLAB IDE (www.microchip.com). ASSOCIATE PROFESSOR DR MURAT UZAM FROM NIGDE UNIVERSITY IN TURKEY KICK-STARTS A SERIES OF ARTICLES ON A PROJECT THAT FOCUSES ON A MICROCONTROLLER-PLC

Upload: milekitic2005

Post on 18-Apr-2015

77 views

Category:

Documents


1 download

DESCRIPTION

How to buil plc

TRANSCRIPT

Page 1: PIC PLC

PLC WITH PIC16F648AMICROCONTROLLER(PART 1)

PLC/MCU

www.electronicsworld.co.uk Electronics World - November 08 ❙ 21

Feature

The SeriesThe articles to be published are asfollows:

1. The Hardware: Run in this issue.2. The Basic Software: This article explains the basic softwarestructure of the UZAM_PLC. A PLC scan cycle includes the following:1. obtain the inputs, 2. run the user program, 3. update the outputs.In addition, it is also necessary to define and initialise all variablesused within a PLC. Necessary functions are all described as PICAssembly macros to be used in UZAM_PLC. The macros described inthis article could be summarised as follows: “HC165” (for handling theinputs), “HC595” (for sending the outputs), “dbncr” (for debouncing theinputs), “initialise”, “get_inputs”, “send_outputs”.3. Contact and Relay Based Macros: The following contact and relaybased macros are described in this article: ld (load), ld_not (load_not),not, or, or_not, nor, and, and_not, nand, xor, xor_not, xnor, out, out_not,in_out, inv_out, set, reset. These macros are defined to operate on onebit variables.4. Flip-Flop Based Macros: The following flip-flop based macros aredescribed in this article: r_edge (rising_edge), f_edge (falling_edge),latch0, latch1, dff_r (rising edge triggered D flip-flop), dff_f (fallingedge triggered D flip-flop), tff_r (rising edge triggered T flip-flop), tff_f(falling edge triggered T flip-flop), jkff_r (rising edge triggered JK flip-flop), jkff_f (falling edge triggered JK flip-flop).5. Timer Macros: The following timer macros are described in thisarticle: TON_8 (ON delay timer), TOF_8 (OFF delay timer), TEP_8(Extended Puls timer), TOS_8 (Oscillator timer).6. Counter Macros: The following counter macros are described in thisarticle: CTU_8 (Up Counter), CTD_8 (Down Counter), CTUD_8 (Up/DownCounter).7. Comparison Macros: The following comparison macros aredescribed in this article: The contents of two registers (R1 and R2) arecompared according to the following: GT (Greater Than – “>”), GE(Greater than or Equal to – “≥”), EQ (EQual to – “=”), LT (Less Than –“<”), LE (Less than or Equal to – “≤”), NE (Not Equal to – “≠”). Similarcomparison macros are also described for comparing the contents ofan 8 bit register (R) with an 8 bit constant (K).8. Arithmetical Macros: The following arithmetical macros aredescribed in this article: The following operators are applied to thecontents of two registers (R1 and R2): ADD, SUB (subtract), INC(increment), DEC (decrement). Similar arithmetical macros are alsodescribed to be used with the contents of an 8 bit register (R) and an 8bit constant (K).

9. Logical Macros: The following logical macros are described in thisarticle: inv_R, AND, NAND, OR, NOR, XOR, XNOR. These macros areapplied to an 8 bit register (R1) with another register (R2) or an 8 bitconstant (K).10. Shift&Rotate Macros: The following Shift&Rotate macros aredescribed in this article: SHIFT_R (shift right the contents of register R),SHIFT_L (shift left the contents of register R), ROTATE_R (rotate rightthe contents of register R), ROTATE_L (rotate left the contents ofregister R), SWAP (swap the nibbles of the register).11. Multiplexer Macros: The following multiplexer macros aredescribed in this article: mux_2_1 (2x1 MUX), mux_2_1_E (2x1 MUXwith Enable input), mux_4_1 (4x1 MUX), mux_4_1_E (4x1 MUX withEnable input), mux_8_1 (8x1 MUX), mux_8_1_E (8x1 MUX with Enableinput).12. DeMultiplexer Macros: The following demultiplexer macros aredescribed in this article: Dmux_1_2 (1x2 DMUX), Dmux_1_2_E (1x2DMUX with Enable input), Dmux_1_4 (1x4 DMUX), Dmux_1_4_E (1x4DMUX with Enable input), Dmux_1_8 (1x8 DMUX), Dmux_1_8_E (1x8DMUX with Enable input).13. Decoder Macros: The following decoder macros are described inthis article: decod_1_2 (1x2 decoder), decod_1_2_E (1x2 decoder withEnable input), decod_2_4 (2x4 decoder), decod_2_4_E (2x4 decoderwith Enable input), decod_3_8 (3x8 decoder), decod_3_8_E (3x8decoder with Enable input).14. Priority Encoder Macros: The following priority encoder macrosare described in this article: encod_4_2_p (4x2 priority encoder),encod_4_2_p_E (4x2 priority encoder with Enable input), encod_8_3_p(8x3 priority encoder), encod_8_3_p_E (8x3 priority encoder withEnable input), encod_dec_bcd_p {decimal to BCD (Binary CodedDecimal) priority encoder}, encod_dec_bcd_p_E (decimal to BCDpriority encoder with Enable input).15. An Example: This article describes an example of a remotely-controlled model gate system and makes use of UZAM_PLC to controlit for different control scenarios.

The reader is expected to be familiar with PLCs, PIC microcontrollersand PIC Assembly language. UZAM_PLC macros are developed by usingPIC Assembly language. The program development environment used isthat of MPLAB IDE (www.microchip.com).

ASSOCIATE PROFESSOR DR MURAT UZAMFROM NIGDE UNIVERSITY IN TURKEY KICK-STARTS A SERIES OF ARTICLES ON APROJECT THAT FOCUSES ON AMICROCONTROLLER-PLC

UZAM 16/9/08 10:25 Page 36

Page 2: PIC PLC

Programmable Logic Controllers(PLCs) have been extensively usedin industry for the past five or six

decades. PLC manufacturers offer differentdevices in terms of functions, programmemories and the number ofinputs/outputs (I/O), ranging from a few tothousands of I/Os.

The design and implementation of PLCshave long been a secret of the PLCmanufacturers. As a microprocessor-basedtechnology, the functionality of a PLC iswell known from the end-user/programmerpoint of view, but by now no serious workhas been reported to describe amicroprocessor/microcontroller basedimplementation of a PLC.

With a series of articles I aim to describea PIC microcontroller based design andimplementation of a PLC, called

UZAM_PLC with PIC16F648A. First in theseries is this article, which describes thehardware of UZAM_PLC with PIC16F648A.

DESIGN ANDIMPLEMENTATIONThis project has been completed in searchfor how to design and implement a PLC.Some ideas can be found in the freelyavailable PLC project called “PICBIT” fromaround 10 years ago. An Internet searchfor the keyword “PICBIT” leads to thisproject.

PICBIT describes a PIC16F84microcontroller based PLC with fivediscrete inputs and eight discrete outputs.The file called “picbit.inc” of the PICBITcontains the basic PLC macro definitions.

The UZAM_PLC project has beencompleted by the inspiration of these

macros. In addition, many new featureshave been included within UZAM_PLCproject to make it more of an engulfingPLC. However, this project does not includegraphical interface PC software as in PICBITor in other PLCs for developing PLCprograms. Rather, PLC programs aredeveloped by using macros as done in theInstruction List (IL) PLC programminglanguage. An interested and skilled readercould well – and encouraged to – developgraphical interface PC software for easyuse of UZAM_PLC.

THE HARDWARE WITHPIC16F648AThe hardware of UZAM_PLC withPIC16F648A consists of two parts: “mainboard” and “I/O extension board”. Theschematic diagram of UZAM_PLC main

Figure 1: The schematic diagram of the UZAM_PLC main board

PLC/MCU

22 ❙ November 08 - Electronics World www.electronicsworld.co.uk

Feature

UZAM 16/9/08 10:25 Page 37

Page 3: PIC PLC

board is shown in Figure 1. The mainboard contains mainly five sections: power,programming, CPU (Central ProcessorUnit), inputs and outputs.

The power section accepts 12V AC inputand produces as outputs 12V DC to beused as the operating voltage of relays,and 5 V DC to be used for ICs, inputs, etc.The programming section deals with theprogramming of PIC16F648Amicrocontroller. For programming thePIC16F648A in circuit, it is necessary to usea PIC programmer hardware and softwarewith ICSP (In Circuit Serial Programming)capability. For those who have a PC withserial port, PCB files for a PIC programmerhardware, called JDM programmer, andrelated software can be downloaded(please contact the editorial office of

Electronics World for details). For other types of USB or parallel port

PIC programmers the reader is expected tomake necessary arrangements. ICSPconnector takes the lines VPP(MCLR), VDD,VSS(GND), DATA (RB7), CLOCK (RB6) fromthe PIC programmer hardware through aproperly prepared cable and it serves themto a 4PDT (four pole double throw) switch.

There are two positions of the 4PDTswitch. As seen in Figure 1, in one positionof 4PDT switch, PIC16F648A is ready to beprogrammed and in the other position theloaded program is run. For properlyprogramming the PIC16F648A by means ofa PIC programmer and the 4PDT switch, itis also a necessity to switch off the powerswitch.

The CPU section consists of the

PIC16F648A microcontroller. Although itcan run up to 20MHz, in UZAM_PLC it isfixed to run at 4MHz with its internaloscillator. This frequency is fixed becausetime-delays are calculated based on thisspeed. However, by means of twoswitches, namely SW1 and SW2, it is alsopossible to use an external oscillator withdifferent crystal frequencies. When doingso, time-delay functions must be calculatedaccordingly. SW3 directs the RA5 pin eitherto one pole of 4PDT switch or to the futureextension connector.

PROGRAMMING PICSWhen programming PIC16F648A, RA5should be connected to 4PDT switch. RB0,RB6 and RB7 pins are all reserved to beused for an 8-bit parallel to serial converter

PLC/MCU

www.electronicsworld.co.uk Electronics World - November 08 ❙ 23

Feature

Figure 2: The schematic diagram of the UZAM_PLC I/O extension board

UZAM 16/9/08 10:25 Page 38

Page 4: PIC PLC

FeaturePLC/MCU

register 74HC/LS165. Through these threepins and with added 74HC/LS165 registerswe can describe as many inputs as wewish. RB0, RB6, and RB7 are the “data in”,the “clock in” and the “shift/load” pins,respectively.

Similarly, RB3, RB4 and RB5 pins are allreserved to be used for 8-bit serial toparallel converter register/driver TPIC6B595.Through these three pins and with addedTPIC6B595 registers we can describe asmany outputs as we wish. RB3, RB4 andRB5 are the “clock out”, the “data out”and the “latch out” pins, respectively. Theremaining unused pins of the PIC16F648Aare connected to the “future extensionconnector”.

PIC16F648A provides the following:4096 words of Flash program memory; 256bytes of RAM data memory and 256 bytesof EEPROM data memory. The UZAM_PLCmacros make use of registers defined inRAM data memory. Note that it may bepossible to use PIC16F628A as the CPU,but one has to bear in mind thatPIC16F628A provides the following: 2048words of Flash program memory; 224 bytesof RAM data memory and 128 bytes ofEEPROM data memory.

In this case it is necessary to take care ofthe usage of RAM data memory. Theinputs section introduces 8 discrete inputsfor the UZAM_PLC, called I0.0, I0.1, ...,I0.7. Each input can accept 5V DC or 24V

DC signals. These external input signals areisolated from the other parts of thehardware by using NPN type opto-couplers(e.g. 4N25). For simulating input signals,one can use on board push-buttons astemporary inputs and slide switches aspermanent inputs.

In the beginning of each PLC scan cycle(get_inputs) 74HC/LS165 is loaded (RB7(shift/load) = 0) with the level of 8 inputsand then this data is serially clocked in(when RB7 = 1; through RB0 “data in” andRB6 “clock in” pins). If there is no I/Oextension board used, then 8 clock_insignals are enough to get the 8 inputsignals. For each I/O extension board, 8more clock_in signals are necessary.

Figure 3: Photographs of (a) the UZAM_PLC main board, (b) UZAM_PLC I/O extension board, (c) UZAM_PLC main board with a PICprogrammer, (d) UZAM_PLC main board plus an I/O extension board and a USB PIC programmer, (e) UZAM_PLC main board plus twoI/O extension boards and a USB PIC programmer

A

D E

B C

UZAM 16/9/08 10:25 Page 39

Page 5: PIC PLC

T he basic software of thisprogrammable logiccontroller (PLC) called

UZAM_PLC makes use of generalpurpose 8-bit registers of RAMdata memory of PIC16F648A. Forthe sake of simplicity, we restrictourselves to use only BANK 0, i.e. allmacros, including the basic definitionsexplained here, to be defined by meansof 8-bit registers of BANK 0.

The file “definitions.inc” (all the filesexplained here including “definitions.inc”can be downloaded fromhttp://host.nigde.edu.tr/muzam/). Itcontains all of the basic macros anddefinitions necessary for UZAM_PLC. Inthis article we will explain the contentsof this file. First of all, let’s have a look atthe file called “UZAM_plc_8i8o_1.asm”shown in Figure 1. It is well-known that

the PLC’s scan cycle includes thefollowing: obtain the inputs, run the userprogram, update the outputs. This cyclerepeats as long as the PLC runs.

Before getting into the endless PLCscan cycles, the initial conditions of thePLC are set up in the initialisation stage.These main steps can be seen fromFigure 1, where “initialise” is a macro forsetting up the initial conditions;“get_inputs” is a macro for getting theinputs; and “send_outputs” is a macrofor updating the outputs. The “user PLCprogram” must be placed between

“get_inputs” and “send_outputs”. Theendless PLC scan cycles are obtained bymeans of the label “scan” and theinstruction “goto scan”.

UZAM_PLC is fixed to run at 4MHzwith PIC16F648A’s internal oscillator. Thewatchdog timer is used to prevent user-program lock-ups. As will be explainedlater, the hardware timer TMR0 is utilisedto obtain free-running reference timingsignals.

FILE DEFINITIONSNext, let’s consider the inside of the file“definitions.inc”. The definition of 8-bitvariables to be used for the basicsoftware and their allocation in BANK 0of RAM data memory are shown inFigure 2a and 2b respectively. Althoughwe can define as many inputs andoutputs as we want, for the sake ofsimplicity we define four 8-bit inputregisters and four 8-bit output registers(Q0, Q1, Q2, Q3).

It is well-known that inputs taken from

PLC/MCU

www.electronicsworld.co.uk

Feature

Figure 1: The view of the file “UZAM_plc_8i8o_1.asm”

PLC WITH PIC16F648AMICROCONTROLLERPART 2 ASSOCIATE PROFESSOR DR MURAT UZAM FROM NIGDE

UNIVERSITY IN TURKEY PRESENTS A SERIES OF ARTICLESON A PROJECT THAT FOCUSES ON A MICROCONTROLLER-BASED PLC. THIS IS THE SECOND ARTICLE OF THE SERIESAND IT COVERS THE BASIC SOFTWARE STRUCTURE OFTHE UZAM_PLC

It is also necessary to define andinitialise all variables used within aPLC. Necessary functions are alldescribed as PIC Assembly macros tobe used in UZAM_PLC. The macrosdescribed in this article could besummarised as follows: “HC165”(for handling the inputs), “HC595”(for sending the outputs), “dbncr”(for debouncing the inputs),“initialise”, “get_inputs”,“send_outputs”.

Electronics World - December 08 ❙ 29

Page 6: PIC PLC

contacts always suffer from “contact bouncing”. To circumventthis problem we will define a “debouncing” mechanism for theinputs and this will be explained later. In the “get_inputs” stageof the PLC scan cycle, the input signals are serially taken from therelated 74HC/LS165 registers and stored in the registers. As aresult, bI0, bI1, bI2 and bI3 will hold these bouncing inputsignals. After applying the “debouncing” mechanism to theregisters bI0, bI1, bI2 and bI3, we obtain “debounced” inputsignals and they are stored in registers I0, I1, I2 and I3respectively.

We don’t have to use all of these registers. For example, if weuse just the “main board”, then we have 8 inputs and thereforewe can just use bI0 and I0. Similarly, if we use the “main board”with an “I/O extension board”, then we have 16 inputs and,therefore, we must use bI0, bI1 and I0, I1. Currently, for the sakeof simplicity we restrict ourselves to the main board and,therefore, we need to use bI0 and I0.

In the “send_outputs” stage of the PLC scan cycle, the outputinformation stored in the 8-bit registers Q0, Q1, Q2, Q3 areserially sent out to and stored in the related TPIC6B595 registers.This means that Q0, Q1, Q2, Q3 registers will hold outputinformation and they will be copied into the TPIC6B595 registersat the end of each PLC scan cycle. We don’t have use all of theseoutput registers. For example, if we use just the “main board”,then we have 8 outputs and, therefore, we can use just Q0.

Similarly, if we use the “main board” with an “I/O extensionboard”, then we have 16 outputs and, so, we must use both Q0and Q1. Currently, for the sake of simplicity we restrict ourselvesto the main board and therefore we need to use only Q0. Four 8-bit registers, namely M0, M1, M2 and M3, are defined forobtaining 32 memory bits (internal relays, in PLC jargon).

To be used for the debouncer macro we define eight 8-bitregisters (DBNCR, DBNCR+1, ..., DBNCR+7). In addition, theregister DBNCRRED is also defined to be used for the debouncermacro. Temp_1 is a general temporary register declared to beused in the macros. Temp_2 is declared to be used especially forobtaining special memory bits as will be explained later. Timer_2is defined for storing high byte of the free-running timing signals.

PLC/MCU

30 ❙ December 08 - Electronics World www.electronicsworld.co.uk

Feature

Figure 2: (a) above – The definition of 8-bit variables to beused for the basic software, (b) below – Their allocation in BANK 0 of RAM data memory

Figure 3: BANK macros

Page 7: PIC PLC

The low byte of free-running timingsignals is stored in TMR0 (recalled asTimer_1).

For accessing the RAM data memoryeasily, BANK macros are defined as shownin Figure 3. The definitions of one bitvariables are depicted in Figure 4. Thefollowing definitions are self explanatory:74HC165, TPIC6B595, 8 INPUTS, 8OUTPUTS, 32 Memory Bits. Let us nowhave a look at the others.

OTHER VARIABLESThe variable “LOGIC0” is defined to holdlogical “0” value throughout the PLCoperation. At the initialisation stage it isdeposited with this value. Similarly, thevariable “LOGIC1” is defined to holdlogical “1” value throughout the PLCoperation. At the initialisation stage it isdeposited with this value.

The special memory bit “FRSTSCN” isarranged to hold the value of “1” at thefirst PLC scan cycle only. In the other PLCscan cycles following the first one it isreset. The other special memory bit“SCNOSC” is arranged to work as a “scanoscillator”. This means that in one PLCscan cycle this special bit will hold thevalue of “0”, in the next one the value of“1”, in the next one the value of “0” etc.This will keep on going for every PLC scancycle. Let us now consider the 16reference timing signals.

As seen later, TMR0 of PIC16F648A isset up to count the 1/4 of 4MHz internaloscillator signal, i.e. 1MHz with a prescalerarranged to divide the signal to 256. As aresult by means of TMR0 bits (also calledTimer_1) we obtain eight free-runningreference timing signals with the “T”timing periods starting from 0.512ms to65.536ms. We’ll see later that the register“Timer_2” is incremented on Timer_1overflow. This also gives us (by means ofTimer_2 bits) eight more free-runningreference timing signals with the “T”timing periods starting from 131.072ms to

16777.216ms. Timing diagram of the free-running

reference timing signals is depicted inFigure 5. Note that the evaluation ofTMR0 (Timer_1) is independent from PLCscan cycles, but Timer_2 is incrementedwithin the “get_inputs” stage of PLC scancycle on Timer_1 overflow. This is justifiedas long as the PLC scan cycle takes lessthan 65.536ms.

THE MACROSThe macro “HC165” is shown in Figure 6.The input signals are serially taken fromthe related 74HC/LS165 registers andstored in the registers such as bI0, bI1, bI2and bI3 by means of this macro. The“num” defines the number of74HC/LS165 registers to be considered.This means that with this macro we canobtain inputs from as many 74HC/LS165registers as we wish.

However, as explained before, werestrict this number to be 4 at most for thesake of simplicity; “var0” is the beginningof the registers to which the state ofinputs taken from 74HC/LS165 registerswill be stored. This implies that thereshould be enough RAM locations reservedafter “var0” and, also, there should beenough 74HC/LS165 registers to get theinputs from. There are some explanationswithin the macro to describe how it works.

As can be seen, this macro makes use ofpreviously defined “data_in”, “clock_in”and “sfht_ld” bits to obtain the input

PLC/MCU

www.electronicsworld.co.uk Electronics World - December 08 ❙ 31

Feature

Figure 6: The macro “HC165”

Figure 4: Definitions of one-bit variables

Figure 5: Timing diagram of the free-running reference timing signals (T = 0.512, 1.024... 16777.216ms)

Page 8: PIC PLC

FeaturePLC/MCU

signals from 74HC/LS165 registers.The macro “HC595” is shown in Figure

7. The output signals are stored in the 8-bit registers such as Q0, Q1, Q2 and Q3 in

RAM locations, and serially sent out to andstored in the related TPIC6B595 registersby means of this macro. The “num”defines the number of TPIC6B595 registers

to be used. This means that with thismacro we can send output data serially toas many TPIC6B595 registers as we wish.

However, as explained before, werestrict this number to be 4 at most for thesake of simplicity; “var0” is the beginningof the 8-bit registers such as Q0 in RAMfrom which the state of outputs are takenand serially sent to TPIC6B595 registers.This implies that there should be enoughRAM locations reserved after “var0” and,also, there should be enough TPIC6B595registers to hold the outputs.

There are some explanations within themacro to describe how it works. As can beseen, this macro makes use of previouslydefined “data_out”, “clock_out” and“latch_out” bits to send the output signalsserially to TPIC6B595 registers.

The macro “dbncr” is shown in Figure8. It can be used for debouncing eightindependent buttons, switches, relay orcontactor contacts etc. The timing diagramof one channel of this debouncer isprovided in Figure 9. It can be seen thatthe output changes its state only after theinput becomes stable and waits in thestable state for the predefined debouncingtime “dt1” or “dt2”. The debouncing isapplied to both rising and falling edges ofthe input signal.

In this macro, each channel is intendedfor a “normally open contact” connectedto the PIC by means of a pull-downresistor, as this is the case withUZAM_PLC. It can also be used withoutany problem for a “normally closedcontact” connected to the PIC by meansof a pull-up resistor.

The “debouncing times” such as 20ms,50ms or 100ms can be selected asrequired depending on the application. Itis possible to pick up different debouncingtimes for each channel. It is also possibleto choose different debouncing times forrising and falling edges of the same inputsignal, if necessary. This gives a good dealof flexibility. This is simply done bychancing the related time constant“tcnst_01” or “tcnst_10” defining thedebouncing time delay for each channeland for both edges within the assemblyprogram.

Note that if the state-change-of-the-contact is shorter than the predefined“debouncing time”, this will also beregarded as bouncing and it will not betaken into account. Therefore, no state-

32 ❙ December 08 - Electronics World www.electronicsworld.co.uk

Figure 7: The macro “HC595”

Figure 8: The macro “dbncr”

Page 9: PIC PLC

change will be issued in this case. Each ofthe eight input channels of the debouncermay be used independently from otherchannels. The activity of one channel doesnot affect the other channels.

THE MACRO “DBNCR”Let us now briefly consider how the macro“dbncr” works. First of all, one of thepreviously defined reference timing signalsis chosen as “t_reg,t_bit” to be used

within this macro. Then, we can set upboth debouncing times dt1 and dt2 bymeans of time constants “tcnst_01” and“tcnst_10” as dt1 = (t_reg,t_bit) xtcnst_01 and dt2 = (t_reg,t_bit) x tcnst_10 respectively.

If the input signal (regi,biti) = 0 and theoutput signal (rego,bito) = 0 or the inputsignal (regi,biti) = 1 and the output signal(rego,bito) = 1, then the related counter“DBNCR+num” is loaded with “00h” and

no state-change is issued. If the outputsignal (rego,bito) = 0 and the input signal(regi,biti) = 1, then with each “risingedge” of the reference timing signal“t_reg,t_bit” the related counter“DBNCR+num” is incremented by one. Inthis case, when the count value of“DBNCR+num” is equal to the number“tcnst_01”, this means that the inputsignal is debounced properly and thenstate-change from 0 to 1 is issued for theoutput signal (rego,bito).

Similarly, if the output signal (rego,bito)= 1 and the input signal (regi,biti) = 0,then with each “rising edge” of thereference timing signal “t_reg,t_bit” therelated counter “DBNCR+num” isincremented by one. In this case, whenthe count value of “DBNCR+num” isequal to the number “tcnst_10”, thismeans that the input signal is debouncedproperly and then state-change from 1 to0 is issued for the output signal(rego,bito). For this macro it is necessaryto define the following 8-bit variables inRAM: Temp_1, and DBNCRRED. Inaddition, it is also necessary to defineeight 8-bit variables in successive RAMlocations, the first of which is to bedefined as “DBNCR”. It is not necessaryto name the other seven variables. Eachbit of the variable DBNCRRED is used todetect the “rising edge” of the referencetiming signal “t_reg,t_bit” for the relatedchannel.

THE MACRO “INITIALISE”The macro “initialise” is shown in Figure10. There are mainly two tasks carried outwithin this macro. In the former, firstTMR0 is set up as a free-running hardwaretimer with the 1/4 of 4MHz internaloscillator signal, i.e. 1MHz, and with aprescaler arranged to divide the signal to256. In addition, PORTB is initialised tomake RB0 (data in) as input and thefollowing as outputs: RB3 (clock out), RB4(data out), RB5 (latch out), RB6 (clock in),RB7 (shift/load). In the latter, all utilisedRAM registers are loaded with initial “safevalues”. In other words, all utilised RAMregisters are cleared (loaded with 00h)except for Temp_2, which is loaded with06h. As explained before, Temp_2 holdssome special memory bits, therefore, theinitial values of these special memory bitsare put into Temp_2 within this macro. Asa result, these special memory bits are

PLC/MCU

www.electronicsworld.co.uk Electronics World - December 08 ❙ 33

Feature

Figure 9: Timing diagram of one channel of the debouncer

Figure 10: The macro “initialise”

Page 10: PIC PLC

loaded with the following initial values:LOGIC0 (Temp_2,0) = 0, LOGIC1(Temp_2,1) = 1, FRSTSCN (Temp_2,2) = 1,SCNOSC (Temp_2,3) = 0.

THE MACRO “GET_INPUTS”The macro “get_inputs” is shown inFigure 11. There are mainly three taskscarried out within this macro. In the firstone, the macro “HC165” is called withthe parameters “.1” and “bI0”. Thismeans that we will use only the “mainboard” and, therefore, the macro“HC165” is called with the parameter“.1”. As explained before, the inputinformation taken from the macro is ratedas “bouncing” information and,therefore, this information is stored in“bI0” register. For example if we decideto use the “main board” connected tothree of the “I/O extension board” thenwe must call the macro “HC165” asfollows: “HC165 .4,bI0”. This will takefour 8-bit bouncing input informationfrom the 74HC/LS165 ICs and will putthem to the four successive registersstarting with the register bI0.

In the second task within this macro,each bit of bI0, i (i = 0, 1… 7) isdebounced by the macro “dbncr” andeach debounced input signal is stored inthe related bit I0, i (i = 0, 1… 7). Ingeneral, 20ms time delay is enough fordebouncing both rising and falling edgesof an input signal. Therefore, to achievethese time delays, the reference timingsignal, obtained from Timer_1, is chosenas T00 (0.512ms period) and both“tcnst_01” and “tcnst_10” are chosen tobe “40”. Then we obtain the following:dt1 = T00 x tcnst_01 = (0.512ms) x 40 =20.48ms, dt2 = T00 x tcnst_10 =(0.512ms) x 40 = 20.48ms.

Note that in this series of articles forthe sake of simplicity we use just 8 inputsand 8 outputs. If we want to add moreinputs and to debounce these inputs,then we must organise the macro“dbncr” and locate necessary number ofregisters within the RAM.

The last task is about incrementing theTimer_2 on overflow of Timer_1. In thistask, “Timer_2” is incremented by onewhen the falling edge of the bit“Timer_1,7” is detected. In order todetect the falling edge of the bit“Timer_1,7”, “Temp_2,4” bit is utilised.

FeaturePLC/MCU

Figure 11: The macro “get_inputs”

Figure 12: The macro “send_outputs”

Figure 13: A fraction of the first example program “UZAM_plc_8i8o_ex1.asm”

Figure 14: A fraction of the second example program“UZAM_plc_8i8o_ex2.asm”

34 ❙ December 08 - Electronics World www.electronicsworld.co.uk

Page 11: PIC PLC

FeaturePLC/MCU

THE MACRO “GET_OUTPUTS”The macro “send_outputs” is shown inFigure 12. There are mainly four taskscarried out within this macro. In the firstone, the macro “HC595” is called with theparameters “.1” and “Q0”. This meansthat we will use only the “main board”and, therefore, the macro “HC595” iscalled with the parameter “.1”.

As explained before, the outputinformation is taken from the register Q0and this macro sends the bits of Q0 seriallyto TPIC6B595 register. For example, if wedecide to use the “main board” connectedto three of the “I/O extension board” thenwe must call the macro “HC595” asfollows: “HC595 .4,Q0”. Then, the macro“HC595” will take four 8-bit outputinformation stored in Q3, Q2, Q1 and Q0and send them serially to the fourTPIC6B595 register ICs respectively.

In the second task within this macro, thewatchdog timer is cleared. In the third task,the “FRSTSCN” special memory bit is reset.As the final task, within this macro the“SCNOSC” special memory bit is toggledafter a program scan, i.e. when it is “1” itis reset, when it is “0” it is set.

EXAMPLESUp to now we have seen the hardwareand basic software necessary forUZAM_PLC. It is now time to consider afew examples. Before you can run the twosimple examples considered here, you areexpected to construct your ownUZAM_PLC hardware by using thenecessary PCB files and producing PCBswith its components.

For the first example, include the userprogram shown in Figure 13 within the“UZAM_PLC_8i8o_1.asm” and then saveit as “UZAM_PLC_8i8o_ex1.asm”. Thenext thing to do is to open it by MPLABIDE and to compile it. After that, by usingthe PIC programmer software take thecompiled file “UZAM_PLC_8i8o_ex1.hex”and by your PIC programmer hardware,send it to the program memory ofPIC16F648A microcontroller within theUZAM_PLC.

After loading the“UZAM_PLC_8i8o_ex1.hex”, switch the4PDT in “RUN” and the power switch in“ON” position. Now, you are ready to testthe first example program. You can seethat all the inputs are transferred to the

respected outputs. That is to say that ifI0.0 = 0 then Q0.0 = 0 and, similarly, ifI0.0 = 1 then Q0.0 = 1. This applies to all8 inputs and 8 outputs.

For the second example, please includethe user program shown in Figure 14within the “UZAM_PLC_8i8o_1.asm” andthen save it as“UZAM_PLC_8i8o_ex2.asm”. Next open itby MPLAB IDE and compile it. After thatby using the PIC programmer softwaretake the compiled file“UZAM_PLC_8i8o_ex2.hex” and by yourPIC programmer hardware send it to theprogram memory of PIC16F648Amicrocontroller within the UZAM_PLC.

After loading the“UZAM_PLC_8i8o_ex2.hex”, switch the4PDT in “RUN” and the power switch in“ON” position. Now, you are ready to testthe second example program. In this casethe contents of “Timer_2” register aretransferred to 8 outputs.

Of course, in these two examples theuser programs include only PIC Assemblyinstructions, but we will start using ourown macro-based PLC instructions in thenext article. ■

Page 12: PIC PLC

PLC/MCU

30 ❙ January 09 - Electronics World

IN THIS ARTICLE the following contactand relay-based macros are described: ld (load),ld_not (load_not), not, or, or_not, nor, and,and_not, nand, xor, xor_not, xnor, out, out_not,in_out, inv_out, set, reset. These macros aredefined to operate on Boolean (one bit) variables.

All contact and relay-based macros are shownin Table 1, where the first column shows themacros, the second column provides the truthtable of the respected macros, the third and forthcolumns show the ladder logic and schematicsymbols of the macros respectively.

Let us now briefly explain these macros: 1. ld (load) – this macro has a Boolean input

variable passed into it as “reg,bit” and aBoolean output variable passed out through“W”. In ladder logic, this macro is representedby a normally open (NO) contact. When theinput variable is 0 (respectively 1) the output(W) is forced to 0 (respectively to 1).

2. ld_not (load_not) – this macro has a Booleaninput variable passed into it as “reg,bit” and aBoolean output variable passed out through“W”. In ladder logic, this macro is representedby a normally closed (NC) contact. When theinput variable is 0 (respectively 1) the output(W) is forced to 1 (respectively to 0).

3. not – this macro is used as a logical NOT gate.The input is taken from W and the output issend out by W.

4. or – this macro is used as a two-input-logical-OR gate. One input is taken from W and theother is taken from “reg,bit”. The result is putinto W.

5. or_not – this macro is also used as a two-input-logical-OR gate, but this time one of the inputsis inverted. One input is taken from W and theinverted input is taken from “reg,bit”. Theresult is put into W.

6. nor – this macro is used as a two-input-logical-NOR-gate. One input is taken from W and theother input is taken from “reg,bit”. The resultis put into W.

7. and – this macro is used as a two-input-logical-AND gate. One input is taken from Wand the other input is taken from “reg,bit”.The result is put into W.

8. and_not – this macro is also used as a two-input-logical-AND gate, but this time one ofthe inputs is inverted. One input is taken fromW and the inverted input is taken from“reg,bit”. The result is put into W.

9. nand – this macro is used as a two-input-logical-NAND gate. One input is taken fromW and the other input is taken from“reg,bit”. The result is put into W.

10. xor – this macro is used as a two-input-logical-EXOR gate. One input is taken from Wand the other input is taken from “reg,bit”.The result is put into W.

11. xor_not – this macro is also used as a two-input-logical-EXOR gate, but this time one ofthe inputs is inverted. One input is taken fromW and the inverted input is taken from“reg,bit”. The result is put into W.

12. xnor – this macro is used as a two-input-logical-EXNOR gate. One input is taken fromW and the other input is taken from“reg,bit”. The result is put into W.

13. out – this macro has a Boolean input variablepassed into it by W and a Boolean outputvariable passed out through “reg,bit”. Inladder logic, this macro is represented by anoutput relay (internal or external relay). Whenthe input variable is 0 (respectively 1) theoutput (W) is forced to 0 (respectively to 1).

14. out_not – this macro has a Boolean inputvariable passed into it by W and a Booleanoutput variable passed out through “reg,bit”.In ladder logic, this macro is represented byan output relay (internal or external relay).When the input variable is 0 (respectively 1)the output (W) is forced to 1 (respectively to0).

15. in_out – this macro has a Boolean inputvariable passed into it by “regi,biti” and a

Boolean output variable passed out through“rego,bito”. When the input variable“regi,biti” is 0 (respectively 1) the outputvariable “rego,bito” is forced to 0 (respectivelyto 1)

16. inv_out – this macro has a Boolean inputvariable passed into it by “regi,biti” and aBoolean output variable passed out through“rego,bito”. When the input variable“regi,biti” is 0 (respectively 1) the outputvariable “rego,bito” is forced to 1 (respectivelyto 0).

17. set – this macro has a Boolean input variablepassed into it by W and a Boolean outputvariable passed out through “reg,bit”. Whenthe input variable is 0, no action is taken, butwhen the input variable is 1, the outputvariable “reg,bit” is set to 1.

18. reset – this macro has a Boolean inputvariable passed into it by W and a Booleanoutput variable passed out through “reg,bit”.When the input variable is 0, no action istaken, but when the input variable is 1, theoutput variable “reg,bit” is reset.

ExamplesIn this section, we will consider four examples,

namely UZAM_plc_8i8o_exN.asm, N = 3, 4, 5, 6,to show the usage of contact and relay-basedmacros. These examples can be tested bydownloading the files from http://host.nigde.edu.tr/muzam/ and then opening theUZAM_plc_8i8o_exN.asm, N = 3, 4, 5, 6,program with MPLAB IDE and compiling it. Afterthat by using the PIC programmer software, takethe compiled file “UZAM_PLC_8i8o_exN.hex”and by your PIC programmer hardware send it tothe program memory of PIC16F648Amicrocontroller within the UZAM_PLC. Afterloading the “UZAM_PLC_8i8o_exN.hex” switchthe 4PDT in “RUN” and the power switch in“ON” position. Check each program’s accuracyby cross-referencing it with Table 1.

Associate Professor Dr Murat Uzam from Nigde University in Turkey presents a series of

articles on a project of how to develop a microcontroller-based PLC. This is the third article of

the series focusing on the contacts and relay-based macros of the UZAM_PLC structure

PLC with PIC16F648A

Page 13: PIC PLC

PLC/MCU

Microcontroller Part 3

Table 1: Contact andrelay-based macrosContinues on the next page

www.electronicsworld.co.uk ❙ 31

Page 14: PIC PLC

PLC/MCU

32 ❙ January 09 - Electronics World

Let us now consider these fourexample programs. The firstexample program,“UZAM_plc_8i8o_ex3.asm”, isshown in Figure 1. It shows theusage of the following contact andrelay-based macros: ld, ld_not,not, out, out_not, in_out, inv_out.The schematic and ladderdiagrams of the program aredepicted in Figures 2a and 2b.

The second example program,“UZAM_plc_8i8o_ex4.asm”, isshown in Figure 3. It shows theusage of the following contact andrelay-based macros: ld, out, or,or_not, nor. The schematic andladder diagrams of this programare depicted in Figures 4aand 4b.

Continues from the previous page

Table 1: Contact and relay-based macros

Figure 1: The user programof UZAM_plc_8i8o_ex3.asm

Page 15: PIC PLC

PLC/MCU

The third example program,“UZAM_plc_8i8o_ex5.asm”, is shown in Figure5. It shows the usage of the following contactand relay-based macros: ld, out, and, and_not,nand. Its schematic and ladder diagrams aredepicted in Figures 6a and 6b.

The forth example program,“UZAM_plc_8i8o_ex6.asm”, is shown in Figure7. It shows the usage of the following contactand relay-based macros: ld, out, xor, xor_not,xnor, _set, _reset. The schematic and ladderdiagrams are depicted in Figures 8a and 8b. ■

www.electronicsworld.co.uk ❙ 33

Figure 2:(a) above; Schematic diagram (b) below; Ladder diagramfor the user program ofUZAM_plc_8i8o_ex3.asm

Figure 3:The user program ofUZAM_plc_8i8o_ex4.asm

Figure 4:(a) left; Schematic diagramand (b) right; Ladder diagramfor the user program ofUZAM_plc_8i8o_ex4.asm

Page 16: PIC PLC

PLC/MCU

34 ❙ January 09 - Electronics World

Figure 5: The user programof UZAM_plc_8i8o_ex5.asm

Figure 7: The user programof UZAM_plc_8i8o_ex6.asm

Figure 8:(a) above; Schematic diagramand (b) below; Ladderdiagram for the user programof UZAM_plc_8i8o_ex6.asmFigure 6:

(a) left; Schematic diagramand (b) right; Ladder diagramfor the user program ofUZAM_plc_8i8o_ex5.asm

Page 17: PIC PLC

PLC/MCU

34 ❙ February 09 - Electronics World

IN THIS ARTICLE, the followingflip-flop based macros are described:r_edge (rising edge detector), f_edge(falling edge detector), latch0, latch1,dff_r (rising edge triggered D flip-flop),dff_f (falling edge triggered D flip-flop),tff_r (rising edge triggered T flip-flop),tff_f (falling edge triggered T flip-flop),jkff_r (rising edge triggered JK flip-flop),jkff_f (falling edge triggered JK flip-flop).

Each macro defined here requires anedge detection mechanism, except forlatch0 and latch1. The following 8-bitvariables are used for this purpose: RED −Rising Edge Detector, FED − Falling EdgeDetector, DFF_RED − Rising Edge Detectorfor D flip-flop, DFF_FED − Falling EdgeDetector for D flip-flop, TFF_RED − RisingEdge Detector for T flip-flop, TFF_FED −Falling Edge Detector for T flip-flop,JKFF_RED − Rising Edge Detector for JKflip-flop, JKFF_FED − Falling Edge Detectorfor JK flip-flop.

They are declared within the RAM datamemory as shown in Figure 1. Each 8-bitvariable enables us to declare and use 8different functions defined by the relatedmacro. The macros latch0 and latch1 are

exception for this, which means that wecan use as many latches of latch0 orlatch1 as we wish. The file“ff_mcr_def.inc” (all the files considered

in this article including “ff_mcr_def.inc”can be downloaded from(http://host.nigde.edu.tr/muzam/)contains all flip-flop based macros definedfor UZAM_PLC.

Macro “r_edge” (Rising EdgeDetector)

The macro “r_edge” defines eight risingedge detector functions (or contacts),selected with the num = 0, 1...7. It has aBoolean input variable, namely IN, passedinto the macro through “W” and aBoolean output variable, namely OUT,passed out through “W”. This means thatthe input signal IN should be loaded intoW before this macro is run, and theoutput signal OUT will be provided within

Associate Professor Dr Murat Uzam from Nigde University in Turkey presents aseries of articles on a project that focuses on a microcontroller-based PLC. This isthe fourth article of the series describing the flip-flop based macros

PLC with PIC16F648A Micro

Figure 1: (a) The definition of 8-bit variables to be used for the flip-flop based macros(b) Their allocation in BANK 0 of RAM data memory

Table 1: The macro “r_edge” (rising edge detector), symbols and timing diagram of “r_edge”

Page 18: PIC PLC

PLC/MCU

the W at the end of the macro. Table 1shows the macro “r_edge”, its symbolsand timing diagram.

In ladder logic, this macro is representedby a normally open (NO) contact with theidentifier “P”, meaning positive transition-sensing contact. As can be seen from thetiming diagram the OUT is ON (1) for onlyone scan time when the IN changes statefrom OFF (0) to ON (1). In the otherinstances the OUT remains OFF (0).

Macro “f_edge” (Falling EdgeDetector)

The macro “f_edge” defines eightfalling edge detector functions (orcontacts) selected with the num = 0, 1...7.It has a Boolean input variable, namely IN,passed into the macro through “W” and aBoolean output variable, namely OUT,passed out through “W”. This means thatthe input signal IN should be loaded intoW before this macro is run and the outputsignal OUT will be provided within the Wat the end of the macro. Table 2 showsthe macro “f_edge”, its symbols andtiming diagram.

In ladder logic, this macro is representedby a normally open (NO) contact with theidentifier “N”, meaning negativetransition-sensing contact. As can be seenfrom the timing diagram the OUT is ON (1)for only one scan time when the INchanges state from ON (1) to OFF (0). Inthe other instances the OUT remains OFF(0).

Macro “latch1” (D Latch with Active High Enable)

The macro “latch1” defines a D latchfunction with active high enable. Unlikethe edge triggered flip-flops and the edge

www.electronicsworld.co.uk ❙ 35

controller – Part 4

Table 2: The macro “f_edge” (falling edge detector), and the symbols and timing diagramof “f_edge”

Table 3: The macro “latch1” (D latch with active high enable), and the symboland truth table of “latch1”

Page 19: PIC PLC

PLC/MCU

36 ❙ February 09 - Electronics World

detector macros, in which eight functionsare described, this function defines onlyone D latch function. However, we arefree to use this macro as many times aswe need, with different input/outputvariables.

The macro “latch1” has two Booleaninput variables, namely EN: passed intothe macro through “W” and D: regi,biti;and a single Boolean output variable, Q:rego,bito. The input signal EN (active highenable input) should be loaded into Wbefore this macro is run.

Table 3 shows the macro “latch1”,together with its symbol and truth table.When the active high enable input EN isOFF (0), no state change is issued for the

output Q and it holds its current state.When the active high enable input EN isON (1), the output Q is loaded with thestate of the input D.

Macro “latch0” (D Latch with Active Low Enable)

The macro “latch0” defines a D latchfunction with active low enable. Unlikethe edge triggered flip-flops and the edgedetector macros, in which eight functionsare described, this function defines onlyone D latch function. However, we arefree to use this macro as many times asneeded, with different input/outputvariables.

The macro “latch0” has two Boolean

input variables, namely EN: passed intothe macro through “W” and D: regi,biti;and a single Boolean output variable, Q:rego,bito.

The input signal EN (active low enableinput) should be loaded into W before thismacro is run. Table 4 shows the macro“latch0”, together with its symbol andtruth table. When the active low enableinput EN is ON (1), no state change isissued for the output Q and it holds itscurrent state. When the active low enableinput EN is OFF (0), the output Q is loadedwith the state of the input D.

Macro “dff_r” (Rising Edge Triggered D Flip-Flop)

The macro “dff_r” defines eight risingedge triggered D flip-flop functions,selected with the num = 0, 1...7. It hastwo Boolean input variables, namely clockinput C: passed into the macro through“W” and data input D: regi,biti; and asingle Boolean output variable, flip-flopoutput Q: rego,bito.

The clock input signal C should beloaded into W before this macro is run.Table 5 shows the macro “dff_r”,together with its symbol and truth table.When the clock input signal C is ON (1),or OFF (0), or changes state from ON toOFF (↓), no state change is issued for theoutput Q and it holds its current state.When the state of clock input signal C ischanged from OFF to ON (↑), the output Qis loaded with the state of the input D.

Macro “dff_f” (Falling Edge Triggered D Flip-Flop)

The macro “dff_f” defines eight fallingedge triggered D flip-flop functionsselected with the num = 0, 1...7. It hastwo Boolean input variables, namely clockinput C: passed into the macro through“W” and data input D: regi,biti; and asingle Boolean output variable, flip-flopoutput Q: rego,bito.

The clock input signal C should beloaded into W before this macro is run.Table 6 shows the macro “dff_f”,

Table 5: The macro “dff_r” (rising edge triggered D flip-flop), and the symboland truth table of “dff_r”

Table 4: The macro “latch0” (D latch with active low enable), and the symboland truth table of “latch0”

Page 20: PIC PLC

PLC/MCU

together with its symbol and truth table. When the clock input signal C is ON (1),

or OFF (0), or changes state from ON toOFF (↑), no state change is issued for theoutput Q and it holds its current state.When the state of clock input signal C ischanged from ON to OFF (↓), the output Qis loaded with the state of the input D.

Macro “tff_r” (Rising Edge Triggered T Flip-Flop)

The macro “tff_r” defines eight risingedge triggered T flip-flop functions,selected with the num = 0, 1...7. It hastwo Boolean input variables, namely clockinput C: passed into the macro through“W” and toggle input T: regi,biti; and asingle Boolean output variable, flip-flopoutput Q: rego,bito. The clock input signalC should be loaded into W before thismacro is run.

Table 7 shows the macro “tff_r”,together with its symbol and truth table.When the clock input signal C is ON (1),or OFF (0), or changes state from ON toOFF (↓), no state change is issued for theoutput Q and it holds its current state.When the state of clock input signal C ischanged from OFF to ON (↑), if T = 0,then no state change is issued for theoutput Q and it holds its current state.When the state of clock input signal C ischanged from OFF to ON (↑), if T = 1,then the output Q is toggled.

Macro “tff_f” (Falling Edge Triggered T Flip-Flop)

The macro “tff_f” defines eight fallingedge triggered T flip-flop functionsselected with the num = 0, 1...7. It hastwo Boolean input variables, namely clockinput C: passed into the macro through“W” and toggle input T: regi,biti; and asingle Boolean output variable, flip-flopoutput Q: rego,bito. The clock input signalC should be loaded into W before thismacro is run. Table 8 shows the macro“tff_f”, together with its symbol and truthtable.

When the clock input signal C is ON (1),

or OFF (0), or changes state from OFF toON (↑), no state change is issued for theoutput Q and it holds its current state.When the state of clock input signal C ischanged from ON to OFF (↓) then if T = 0no state change is issued for the outputQ; if T = 1, then the output Q is toggled.

Macro “jkff_r” (Rising Edge Triggered JK Flip-Flop)

The macro “jkff_r” defines eight risingedge triggered JK flip-flop functions,selected with the num = 0, 1...7. It hasthree Boolean input variables, namelyclock input C: passed into the macrothrough “W”, data inputs J: regj,bitj andK: regk,bitk; and a single Boolean output

www.electronicsworld.co.uk ❙ 37

Table 6: The macro “dff_f” (falling edge triggered D flip-flop), and its symbol andtruth table of “dff_f”

Table 7: The macro “tff_r”(rising edge triggered T flip-flop), and the symbol andtruth table of “tff_r”

Page 21: PIC PLC

PLC/MCU

38 ❙ February 09 - Electronics World

variable, flip-flop output Q: rego,bito. Theclock input signal C should be loaded intoW before this macro is run. Table 9 showsthe macro “jkff_r”, together with itssymbol and truth table.

When the clock input signal C is ON (1),or OFF (0), or changes state from ON toOFF (↓), no state change is issued for theoutput Q and it holds its current state.When the state of clock input signal C ischanged from OFF to ON (↑): if JK = 00,then no state change is issued; if JK = 01,then Q is reset; if JK = 10, then Q is set;and finally if JK = 11, then Q is toggled.

Macro “jkff_f” (Falling Edge Triggered JK Flip-Flop)

The macro “jkff_f” defines eight fallingedge triggered JK flip-flop functions,selected with the num = 0, 1...7. It hasthree Boolean input variables, namelyclock input C: passed into the macrothrough “W”, data inputs J: regj,bitj andK: regk,bitk; and a single Boolean outputvariable, flip-flop output Q: rego,bito. Theclock input signal C should be loaded intoW before this macro is run. Table 10shows the macro “jkff_f”, together withits symbol and truth table.

When the clock input signal C is ON (1),or OFF (0), or changes state from OFF toON (↑), no state change is issued for theoutput Q and it holds its current state.When the state of clock input signal C ischanged from ON to OFF (↓): if JK = 00,then no state change is issued; if JK = 01,then Q is reset; if JK = 10, then Q is set;and finally if JK = 11, then Q is toggled.

Flip-Flop Based Macro ExamplesIn this section we will consider four

examples, namelyUZAM_plc_8i8o_exN.asm, N = 7, 8, 9, 10,to show the usage of flip-flop basedmacros. In order to test these examples,you can download the files fromhttp://host.nigde.edu.tr/muzam/. Theprogram UZAM_plc_8i8o_exN.asm, N = 7,8, 9, 10, by MPLAB IDE will need to becompiled. After that, with the PICprogramming software, take the compiledfile “UZAM_PLC_8i8o_exN.hex” and sendit to the program memory of PIC16F648Amicrocontroller within the UZAM_PLC, byusing your own PIC programminghardware. After loading the

Table 8: The macro “tff_f” (falling edge triggered T flip-flop), and the symbol andtruth table of “tff_f”

Table 9: The macro “jkff_r” (rising edge triggered JK flip-flop), and the symboland truth table of “jkff_r”

Page 22: PIC PLC

PLC/MCU

“UZAM_PLC_8i8o_exN.hex”, switch the4PDT in “RUN” and the power “ON”.Finally, you are ready to test the exampleprograms. To check the correctness ofeach program you are referred to therelated information for each of thefunction discussed here.

The first example program,“UZAM_plc_8i8o_ex7.asm” is shown inFigure 2. It shows the usage of thefollowing flip-flop based macros: r_edge,f_edge, latch1, latch0. The schematic andladder diagrams of this program aredepicted in Figures 3a and in 3b. Notethat it is not possible to observe theeffects of r_edge and f_edge shown inrungs 1 and 2 due to the time delayscaused by the macro HC595, as explainedin Part 2 of this article series, which run inthe last issue of Electronics World.

On the other hand you can observe theireffects from the rungs 5 and 6respectively, where r_edge and f_edge areboth used together with the macro latch1.Observe that in rung 5 we obtain a risingedge triggered D flip-flop by using ar_edge and a latch1. Similarly, in rung 6we obtain a falling edge triggered D flip-flop by using a f_edge and a latch1.

The second example program,“UZAM_plc_8i8o_ex8.asm”, is shown inFigure 4. It shows the usage of thefollowing flip-flop based macros: dff_r,dff_f. The schematic and ladder diagramsof this program are shown in Figures 5aand in 5b. Note that in this example, _setand _reset functions are both used asasynchronous SET and RESET inputs forthe D type flip-flops.

www.electronicsworld.co.uk ❙ 39

Table 10: The macro “jkff_f” (falling edge triggered JK flip-flop), and the symboland truth table of “jkff_f”

Figure 3: (a) Schematic diagram and (b) Ladder diagram for the userprogram of UZAM_plc_8i8o_ex7.asmFigure 2: The user program of UZAM_plc_8i8o_ex7.asm

Page 23: PIC PLC

PLC/MCU

40 ❙ February 09 - Electronics World

The third example program, “UZAM_plc_ 8i8o_ex9.asm” isshown in Figure 6. It shows the usage of the following flip-flopbased macros: tff_r, tff_f. The schematic and ladder diagrams ofthis program are depicted in Figures 7a and in 7b. Note that inthis example, _set and _reset functions are both used asasynchronous SET and RESET inputs for the T type flip-flops.

The forth example program, “UZAM_plc_8i8o_ex10.asm” isshown in Figure 8. It shows the usage of the following flip-flopbased macros: jkff_r, jkff_f. The schematic and ladder diagramsare shown in Figures 9a and in 9b. Note that in this example,_set and _reset functions are both used as asynchronous SET andRESET inputs for the rising edge triggered JK flip-flop. ■

Figure 4: The user program of UZAM_plc_8i8o_ex8.asm

Figure 6: The user program of UZAM_plc_8i8o_ex9.asm

Figure 8: The user program of UZAM_plc_8i8o_ex10.asm

Figure 5: (a) Schematic diagram and (b) Ladder diagram for the userprogram of UZAM_plc_8i8o_ex8.asm

Figure 7: (a) Schematic diagram and (b) Ladder diagram for the userprogram of UZAM_plc_8i8o_ex9.asm

Figure 9: (a) Schematic diagram and (b) Ladder diagram for the userprogram of UZAM_plc_8i8o_ex10.asm

Page 24: PIC PLC

PLC/MCU

30 ❙ March 09 - Electronics World

IN THIS ARTICLE, the followingtimer macros are described: TON_8 (ONdelay timer) and TOF_8 (OFF delay timer).The remaining timer macros, namely TEP_8(Extended Pulse timer) and TOS_8(Oscillator timer) will appear in the nextarticle.

Timer MacrosTimers can be used in a wide range of

applications where a time delay function isrequired based on an input signal. In thisarticle, four different timer functions,namely on delay timer, off delay timer,pulse timer and oscillator timer, aredescribed.

The definition of 8-bit variables to beused for the timer macros and theirallocation in BANK 0 of RAM data memoryare both shown in Figures 1a and 1brespectively. The status bits of all of thesetimers are defined as shown in Figure 2a.

All the 8-bit variables defined for timersmust be cleared at the beginning of thePLC operation for a proper operation. Forthis purpose, the macro “init_tmrs” isdefined as shown in Figure 2b. Thismacro must be run after the macro“initialize” explained in the follow-uparticle in the next issue of ElectronicsWorld. The file “tmr_mcr_def.inc” (all thefiles considered in this article including“tmr_mcr_def.inc” can be downloadedfrom http://host.nigde.edu.tr/muzam/)contains all timer macros defined forUZAM_PLC.

On Delay Timer (TON)The on-delay timer can be used to delay

setting an output true (ON – 1) for a fixedperiod of time after an input signalbecomes true (ON – 1). The symbol andtiming diagram of the on-delay timer(TON) are both shown in Figure 3.

As the input signal IN goes true (ON –1), the timing function is started and,therefore, the elapsed time ET starts toincrease. When the elapsed time ETreaches the time specified by the presettime input PT, the output Q goes true (ON– 1) and the elapsed time is held. Theoutput Q remains true (ON – 1) until theinput signal IN goes false (OFF – 0). If theinput signal IN is not true (ON – 1) longerthan the delay time specified in PT, theoutput Q remains false (OFF – 0). Thefollowing section explains theimplementation of eight of 8-bit on-delaytimers for UZAM_PLC.

Macro “TON_8” (8-bit ON Delay Timer)

The macro “TON_8” defines 8 on-delaytimers selected with the num = 0, 1…7.

Associate Professor Dr Murat Uzam from Nigde University in Turkey presents aseries of articles on a project that focuses on a microcontroller-based PLC. This isthe fifth article of the series describing the first set of timer macros

PLC with PIC16F648A Micro

Figure 1: (a) The definition of 8-bit variables to be used for the timer macros(b) Their allocation in BANK 0 of RAM data memory

(b)

(a)

Page 25: PIC PLC

PLC/MCU

Table 1 shows the macro “TON_8” and itssymbol. IN (input signal), Q (output signal= timer status bit) and CLK {free runningtiming signals – ticks:T00(0.512ms)…T15(16777.216ms)} are alldefined as Boolean variables.

The time constant “tcnst” is an integerconstant (here for 8-bit resolution, it ischosen as any number in the range 1-255)and is used to define preset time PT,which is obtained by the formula: PT =tcnst × CLK, where CLK should be used asthe period of the free-running timingsignals – ticks.

The on-delay timer outputs arerepresented by the status bits:TON8_Q,num (num = 0, 1…7), namelyTON8_Q0, TON8_Q1…TON8_Q7, asshown in Figure 2a. We use a Booleanvariable, or TON8_RED,num (num = 0,1…7), as a rising edge detector foridentifying the rising edges of the chosenCLK. An 8-bit integer variable TON8+num(num = 0, 1...7) is used to count the risingedges of the CLK. The count value ofTON8+num (num = 0, 1...7) defines theelapsed time ET as follows: ET = CLK ×count value of TON8+num (either of 0,1...7).

Let us now briefly consider how themacro “TON_8” works. First of all, presettime PT, is defined by means of areference timing signal “CLK =t_reg,t_bit” and a time constant “tcnst”.If the input signal IN, taken into the macroby means of W is false (OFF – 0), then theoutput signal TON8_Q,num (num = 0,1...7) is forced to be false (OFF – 0) andthe counter TON8+num (num = 0, 1...7) isloaded with “00h”.

If the input signal IN is true (ON – 1)and the output signal Q, i.e. the status bit

www.electronicsworld.co.uk ❙ 31

controller – Part 5

Figure 2: (a) The definition of status bits of timer macros(b) The initialization of all variables of timer macros defined as a macro “init_tmrs”

(b)(a)

Page 26: PIC PLC

PLC/MCU

TON8_Q,num (num = 0, 1...7), is false(OFF – 0), then with each “rising edge” ofthe reference timing signal “CLK =t_reg,t_bit” the related counter“TON8+num” is incremented by one. Inthis case, when the count value of“TON8+num” is equal to the number“tcnst”, then state-change from 0 to 1 isissued for the output signal (timer statusbit) TON8_Q,num (num = 0, 1...7).

If the input signal IN and the outputsignal Q, i.e. the status bit TON8_Q,num(num = 0, 1...7) are both true (ON – 1),then no action is taken and the elapsedtime ET is held. In this macro a previouslydefined 8-bit variable “Temp_1” is alsoutilized.

Off Delay Timer (TOF)The off-delay timer can be used to delay

setting an output false (OFF – 0) for afixed period of time after an input signalgoes false (OFF – 0), i.e. the output is heldON for a given period longer than theinput. The symbol and timing diagram ofthe off-delay timer (TOF) are both shownin Figure 4.

As the input signal IN goes true (ON –1), the output Q follows and remains true(ON – 1), until the input signal IN is false(OFF – 0) for the period specified in presettime input PT. As the input signal IN goesfalse (OFF – 0), the elapsed time ET startsto increase. It continues to increase until itreaches the preset time input PT, at whichpoint the output Q is set false (OFF – 0)and the elapsed time is held. If the inputsignal IN is only false (OFF – 0) for aperiod shorter than the input PT, theoutput Q remains true (ON – 1). Thefollowing section explains theimplementation of eight of 8-bit off-delaytimers for UZAM_PLC.

Macro “TOF_8” (8-bit OFF Delay Timer)

The macro “TOF_8” defines 8 off-delaytimers selected with the num = 0, 1…7.Table 2 shows the macro “TOF_8” and itssymbol. IN (input signal), Q (output signalTable 1: The macro “TON_8” and its symbol

Figure 3: The symbol and timing diagram of the on-delay timer (TON)

Macro Symbol

32 ❙ March 09 - Electronics World

Page 27: PIC PLC

PLC/MCU

= timer status bit) and CLK {free runningtiming signals – ticks:T00(0.512ms)…T15(16777.216ms)} are alldefined as Boolean variables.

The time constant “tcnst” is an integerconstant (here for 8-bit resolution it ischosen as any number in the range 1-255)and is used to define preset time PT,which is obtained by the formula: PT =tcnst × CLK, where CLK should be used asthe period of the free-running timingsignals – ticks. The off-delay timer outputsare represented by the status bits:TOF8_Q,num (num = 0, 1...7), namelyTOF8_Q0, TOF8_Q1…TOF8_Q7, as shownin Figure 2a.

We use a Boolean variable, namelyTOF8_RED,num (num = 0, 1...7), as arising edge detector for identifying therising edges of the chosen CLK. An 8-bitinteger variable TOF8+num (num = 0,1...7) is used to count the rising edges ofthe CLK. The count value of TOF8+num(num = 0, 1...7) defines the elapsed timeET as follows: ET = CLK × count value ofTOF8+num (either of 0, 1...7).

Let us now briefly consider how themacro “TOF_8” works. First of all, presettime PT, is defined by means of areference timing signal “CLK =t_reg,t_bit” and a time constant “tcnst”.If the input signal IN, taken into the macroby means of W, is true (ON – 1), then theoutput signal TOF8_Q,num (num = 0,1...7) is forced to be true (ON – 1) and thecounter TOF8+num (num = 0, 1...7) isloaded with “00h”.

When IN = 1 and TOF8_Q,num = 1, if INgoes false (OFF – 0), then with each“rising edge” of the reference timingsignal “CLK = t_reg,t_bit” the relatedcounter “TOF8+num” is incremented byone. In this case, when the count value of“TOF8+num” is equal to the number“tcnst”, then a state-change from 1 to 0is issued for the output signal (timer statusbit) TOF8_Q,num (num = 0, 1...7). In thismacro a previously defined 8-bit variable“Temp_1” is also utilized. ■

www.electronicsworld.co.uk ❙ 33

Table 2: The macro “TON_8” and its symbol

Macro Symbol

Figure 4: The symbol and timing diagram of the off-delay timer (TOF)

Page 28: PIC PLC

PLC/MCU

26 ❙ April 09 - Electronics World

THE PULSE timer can be used togenerate output pulses of a given timeduration. The symbol and timing diagram ofthe pulse timer (TP) are both shown inFigure 1. As the input signal IN goes true(ON – 1), the output Q follows and remainstrue (ON – 1), for the pulse duration asspecified by the preset time input PT.

While the pulse output Q is true (ON – 1),the elapsed time ET is increased. On thetermination of the pulse, the elapsed timeET is reset. The output Q will remain true(ON – 1) until the pulse time has elapsed,irrespective of the state of the input signalIN. Extended pulse timer (TEP) differs fromthe pulse timer in one point that with everystate-change of the input signal from 0 to 1

the elapsed time is re-started from thebeginning and, thus, extending the pulseduration with another PT.

The symbol and timing diagram of theextended pulse timer (TEP) are both shownin Figure 2, from where the differencefrom the pulse timer (TP) can easily be seen.In UZAM_PLC, only the extended pulsetimer (TEP) is implemented. The followingsection explains the implementation of eightof 8-bit extended pulse timers (TEP) forUZAM_PLC.

Macro “TEP_8” (8-bit Extended Pulse Timer)

The macro “TEP_8” defines 8 extendedpulse timers selected with the num = 0,

1...7. Table 1 shows the macro “TEP_8”and its symbol.

IN (input signal), Q (output signal = timerstatus bit) and CLK {free-running timingsignals – ticks: T00(0.512ms)…T15(16777.216ms)} are all defined as Booleanvariables. The time constant “tcnst” is aninteger constant (here for 8-bit resolution itis chosen any number in the range 1-255)and is used to define preset time PT, whichis obtained by the formula: PT = tcnst ×CLK, where CLK should be used as theperiod of the free-running timing signals –ticks.

The extended pulse timer outputs arerepresented by the status bits: TEP8_Q,num(num = 0, 1…7), namely TEP8_Q0,TEP8_Q1…TEP8_Q7, as shown in Figure 2a.A Boolean variable, namely TEP8_RED1,num(num = 0, 1…7), is used as a rising edgedetector for identifying the rising edges ofthe chosen CLK. Similarly, another Booleanvariable, namely TEP8_RED2,num (num = 0,1…7), is used as a rising edge detector foridentifying the rising edges of the inputsignal IN, taken into the macro by means ofW. An 8-bit integer variable TEP8+num(num = 0, 1…7) is used to count the risingedges of the CLK. The count value ofTEP8+num (num = 0, 1…7) defines theelapsed time ET as follows: ET = CLK ×count value of TEP8+num (either of 0,1…7).

Let us now briefly consider how themacro “TEP_8” works. First of all, presettime PT is defined by means of a referencetiming signal “CLK = t_reg,t_bit” and atime constant “tcnst”. If the rising edge ofthe input signal IN is detected, by means ofTEP8_RED2,num, then the output signalTEP8_Q,num (num = 0, 1…7) is forced tobe true (ON – 1), and at the same time the

Associate Professor Dr Murat Uzam from Nigde University in Turkey presents aseries of articles on a project that focuses on a microcontroller-based PLC. This isthe sixth article of the series describing the first set of timer macros

PLC with PIC16F648A Micro

Figure 1: The symbol and timing diagram of the pulse timer (TP)

Page 29: PIC PLC

PLC/MCU

counter TEP8+num (num = 0, 1…7) iscleared. After the output becomes true, i.e.TEP8_Q,num = 1, the related counter“TEP8+num” is incremented by one witheach “rising edge” of the reference timingsignal “CLK = t_reg,t_bit” detected bymeans of TEP8_RED1,num. When the countvalue of “TEP8+num” is equal to thenumber “tcnst”, then state-change from 1to 0 is issued for the output signal (timerstatus bit) TEP8_Q,num (num = 0, 1…7). Inthis macro a previously defined 8-bitvariable “Temp_1” is also utilized.

Oscillator Timer (TOS) The oscillator timer can be used to

generate pulse trains with given durationsfor true (ON) and false (OFF) times.

Therefore, the oscillator timer can be usedin PWM (Pulse Width Modulation)applications.

The symbol and timing diagram of theoscillator timer (TOS) are both shown inFigure 3. PT0 (respectively PT1) defines thefalse (OFF) time {respectively true (ON) time}of the pulse. As the input signal IN goesand remains true (ON – 1), the OFF timingfunction is started and, therefore, theelapsed time ET0 is increased. When theelapsed time ET0 reaches the time specifiedby the preset time input PT0, the output Qgoes true (ON – 1) and ET0 is cleared. Atthe same time, as long as the input signalIN remains true (ON – 1), the ON timingfunction is started and, therefore, theelapsed time ET1 is increased. When the

elapsed time ET1 reaches the time specifiedby the preset time input PT1, the output Qgoes false (OFF – 1) and ET1 is cleared.Then it is time for next operation for OFFand ON times.

This operation will carry on as long as theinput signal IN remains true (ON – 1),generating the pulse trains based on PT0and PT1. If the input signal IN goes andremains false (OFF – 0), then the output Q isforced to be false (OFF – 0). The followingsection explains the implementation of eightof 8-bit oscillator timers (TOS) forUZAM_PLC.

Macro “TOS_8” (8-bit Oscillator Timer)

The macro “TOS_8” defines 8 oscillatortimers selected with the num = 0, 1...7.Table 2 shows the macro “TOS_8” and itssymbol. IN (input signal), Q (output signal =timer status bit) and CLK {free-runningtiming signals – ticks: T00(0.512ms)…T15(16777.216ms)} are all defined as Booleanvariables.

The time constant “tcnst0” is an integerconstant (here for 8-bit resolution it ischosen any number in the range 1-255) andis used to define preset time PT0, which isobtained by the formula: PT0 = tcnst0 ×CLK, where CLK should be used as theperiod of the free-running timing signals –ticks. The time constant “tcnst1” is aninteger constant (here for 8-bit resolution itis chosen any number in the range 1-255)and is used to define preset time PT1, whichis obtained by the formula: PT1 = tcnst1 ×CLK, where CLK should be used as theperiod of the free-running timing signals –ticks.

The oscillator timer outputs arerepresented by the status bits: TOS8_Q,num

www.electronicsworld.co.uk ❙ 27

controller – Part 6

Figure 2: The symbol and timing diagram of the extended pulse timer (TEP)

Page 30: PIC PLC

PLC/MCU

(num = 0, 1…7), namely TOS8_Q0,TOS8_Q1…TOS8_Q7, as shown in Figure2a. We use a Boolean variable, namelyTOS8_RED,num (num = 0, 1…7), as a risingedge detector for identifying the risingedges of the chosen CLK.

An 8-bit integer variable TOS8+num (num= 0, 1…7) is used to count the rising edgesof the CLK. Note that we use the samecounter TOS8+num (num = 0, 1…7) toobtain the time delays for both OFF and ONtimes, as these durations are mutuallyexclusive. The count value of TOS8+num(num = 0, 1…7) defines the elapsed timeET0 or ET1 as follows: ET(0 or 1) = CLK ×count value of TOS8+num (either of 0,1…7).

Let us now briefly consider how themacro “TOS_8” works. First of all, presettime PT0 (respectively PT1), is defined bymeans of a reference timing signal “CLK =t_reg,t_bit” and a time constant “tcnst0”(respectively “tcnst1”). If the input signalIN, taken into the macro by means of W, isfalse (OFF – 0), then the output signal

TOS8_Q,num (num = 0, 1…7) is forced tobe false (OFF – 0) and the counterTOS8+num (num = 0, 1…7) is loaded with“00h”.

If the input signal IN is true (ON – 1) andthe output signal Q, i.e. the status bitTON8_Q,num (num = 0, 1…7) is false (OFF– 0), then with each “rising edge” of thereference timing signal “CLK = t_reg,t_bit”the related counter “TON8+num” isincremented by one. In this case, when thecount value of “TON8+num” is equal to thenumber “tcnst0”, then “TON8+num” iscleared and a state-change from 0 to 1 isissued for the output signal (timer statusbit) TON8_Q,num (num = 0, 1…7). If boththe input signal IN is and the output signalQ, i.e. the status bit TON8_Q,num (num =0, 1…7), are true (ON – 1), then with each“rising edge” of the reference timing signal“CLK = t_reg,t_bit” the related counter“TON8+num” is incremented by one.

In this case, when the count value of“TON8+num” is equal to the numberTable 1: The macro “TEP_8” and its symbol

Figure 3: The symbol and timing diagram of the oscillator timer (TOS)

Macro Symbol

28 ❙ April 09 - Electronics World

Page 31: PIC PLC

PLC/MCU

“tcnst1”, then “TON8+num” is cleared anda state-change from 1 to 0 is issued for theoutput signal (timer status bit)TON8_Q,num (num = 0, 1 …7). This processwill continue as long as the input signal INremains true (ON – 1). In this macro apreviously defined 8-bit variable “Temp_1”is also utilized.

Timer Macros ExampleLet’s consider an example, namely

UZAM_plc_8i8o_ex11.asm, to show theusage of timer macros. In order to test thisexample please download the related filesfrom http://host.nigde.edu.tr/muzam/ andthen open the programUZAM_plc_8i8o_ex11.asm by MPLAB IDEand compile it.

Following that, by using the PICprogrammer software, take the compiledfile “UZAM_PLC_8i8o_ex11.hex” and byyour PIC programmer hardware send it tothe program memory of PIC16F648Amicrocontroller within the UZAM_PLC. Afterloading the “UZAM_PLC_8i8o_ex11.hex”,switch the 4PDT in “RUN” and the powerswitch in “ON” position.

Finally, you are ready to test the exampleprogram. To check the correctness of theprogram you are referred to the relatedinformation for the each timer functionprovided above.

The example program,“UZAM_plc_8i8o_ex11.asm” is shown inFigure 4. It shows the usage of all timermacros described here.

The schematic and ladder diagrams of theuser program of“UZAM_plc_8i8o_ex11.asm” shown inFigure 4 are depicted in Figures 5a and 5brespectively.

In the first two rungs, an on-delay timer“TON_8” is implemented as follows: theinput signal IN is taken from I0.0. num = 0and therefore we choose the first on-delaytimer, whose timer status bit (or output Q)is TON8_Q0. The preset time PT = tcnst ×CLK = 50 × 65.536ms (T07) = 3276.8ms =3.2768s. As can be seen from the secondrung, the timer status bit TON8_Q0 is sent

www.electronicsworld.co.uk ❙ 29

Table 2: The macro “TOS_8” and its symbol

Macro Symbol

Figure 4: The user program of UZAM_plc_8i8o_ex11.asm

Page 32: PIC PLC

PLC/MCU

30 ❙ April 09 - Electronics World

to output Q0.0. In the rungs 3 and 4, an off-delay timer

“TOF_8” is implemented as follows: theinput signal IN is taken from I0.2. num = 2and therefore we choose the third off-delaytimer, whose timer status bit (or output Q)is TOF8_Q2. The preset time PT = tcnst ×CLK = 50 × 65.536ms (T07) = 3276.8ms =3.2768s. As can be seen from the rung 4,the timer status bit TOF8_Q2 is sent tooutput Q0.2.

In the rungs 5 and 6, an extended pulsetimer “TEP_8” is implemented as follows:the input signal IN is taken from I0.4. num= 4 and therefore we choose the fifthextended pulse timer, whose timer statusbit (or output Q) is TEP8_Q4. The preset

time PT = tcnst × CLK = 50 × 65.536ms(T07) = 3276.8ms = 3.2768s. As can beseen from the rung 6, the timer status bitTEP8_Q4 is sent to output Q0.4.

In the rungs 7 and 8, an oscillator timer“TOS_8” is implemented as follows: theinput signal IN is taken from I0.6. num = 6and therefore we choose the seventhoscillator timer, whose timer status bit (oroutput Q) is TOS8_Q6. The preset time PT0= tcnst0 × CLK = 50 × 65.536ms (T07) =3276.8ms = 3.2768s. The preset time PT1 =tcnst1 × CLK = 50 × 65.536ms (T07) =3276.8ms = 3.2768s.

In this set-up, the pulse trains we willobtain has a 50% duty cycle with the timeperiod of T = 100 × 65.536ms = 6.5536s.

As can be seen from the rung 8, the timerstatus bit TOS8_Q6 is sent to output Q0.6.

In the rungs 9 and 10, another oscillatortimer “TOS_8” is implemented as follows:the input signal IN is taken from I0.7. num= 1 and therefore we choose the secondoscillator timer, whose timer status bit (oroutput Q) is TOS8_Q1. The preset time PT0= tcnst0 × CLK = 30 × 65.536ms (T07) =1966.08ms = 1.96608s. The preset time PT1= tcnst1 × CLK = 10 × 65.536ms (T07) =655.36ms = 0.65536s. In this set-up, thepulse trains we will obtain has a 33.34%duty cycle with the time period of T = 40 ×65.536ms = 2.62144s. As can be seen fromthe rung 10, the timer status bit TOS8_Q1is sent to output Q0.7. ■

Figure 5: (a) Schematic diagram and (b) Ladder diagram for the user program of UZAM_plc_8i8o_ex11.asm

(b)(a)

Page 33: PIC PLC

PLC/MCU

30 ❙ May 09 - Electronics World

COUNTERS can be used in a widerange of applications. In this article, threecounter functions, namely up counter downcounter and up/down counter, aredescribed.

The definition of 8-bit variables to beused for the counter macros and theirallocation in BANK 0 of RAM data memoryare both shown in Figure 1a and brespectively. Here, it is important to notethat as we restrict ourselves to use theBANK0, where there is not enoughregisters left, we cannot define differentsets of 8-bit variables to be used incounting process for each counter type.Rather, we define eight of 8-bit variablesand share them for each counter type. As aresult, in total, we can define 8 differentcounters at most, irrespective of thecounter type. The status bits of all countersare defined as shown in Figure 2a.

All of the 8-bit variables defined for a

counter must be cleared at the beginningof the PLC operation for a properoperation. For this purpose the macro“init_cnts” is defined as shown in Figure2b. This macro must be run after the macro“initialize” explained in Part 2 of the series.The file “cnt_mcr_def.inc” (all filesconsidered in this article including“tmr_mcr_def.inc” can be downloadedfrom http://host.nigde.edu.tr/muzam/)contains the entire counter macros definedfor UZAM_PLC.

Let us now consider the counter macros.In the following, first of all a generaldescription will be given for the consideredcounter function and then itsimplementation in UZAM_PLC will beprovided.

Up Counter (CTU)The up counter (CTU) can be used to

signal when a count has reached a

maximum value. The symbol of the upcounter (CTU) is shown in Figure 3, whileits truth table is given in Table 1.

The up counter counts the number of“rising edges” (↑) detected at the inputCU. PV defines the maximum value for thecounter. Each time the counter is calledwith a new rising edge (↑) on CU, thecount value CV is incremented by one.When the counter reaches the PV value,the counter output Q is set true (ON – 1)and the counting stops.

The reset input R can be used to set theoutput Q false (OFF – 0) and clear thecount value CV to zero. The followingsection explains the implementation ofeight of 8-bit up counters for UZAM_PLC.

Macro “CTU_8” (8-bit Up Counter)

The macro “CTU_8” defines 8 up-counters selected with the num = 0, 1...7.Table 2 shows the macro “CTU_8” and itssymbol.

CU (count up input), Q (output signal =counter status bit) and R (reset input) areall defined as Boolean variables. The PV(preset value) is an integer constant (here,for an 8-bit resolution, it is chosen as anynumber in the range 1-255) and is used todefine a maximum count value for thecounter. The counter outputs arerepresented by the counter status bits:CTU8_Q,num (num = 0, 1…7), namelyCTU8_Q0, CTU8_Q1…CTU8_Q7, as shownin Figure 2a.

We use a Boolean variable, namelyCTU8_RED,num (num = 0, 1…7) as a risingedge detector for identifying the risingedges of the CU. An 8-bit integer variableCV_8+num (num = 0, 1…7) is used tocount the rising edges of the CU.

Associate Professor Dr Murat Uzam from Nigde University in Turkey presentsa series of articles on a project that focuses on a microcontroller-based PLC.This is the seventh article in the series describing the counter macros CTU_8(Up Counter) and CTD_8 (Down Counter)

PLC with PIC16F648A Micro

Figure 1: (a) The definition of 8-bit variables to be used for the counter macros(b) Their allocation in BANK 0 of RAM data memory

(b)

(a)

Page 34: PIC PLC

PLC/MCU

Let us now briefly consider how themacro “CTU_8” works. If the input signal Ris true (ON – 1), then the output signalCTU8_Q,num (num = 0, 1…7) is forced tobe false (OFF – 0) and the counterCV_8+num (num = 0, 1…7) is loaded with“00h”. If the input signal R is false (OFF –0), then with each “rising edge” of the CU,the related counter “CV_8+num” isincremented by one. In this case, when thecount value of “CV_8+num” is equal to thePV, then state-change from 0 to 1 is issuedfor the output signal (counter status bit)CTU8_Q,num (num = 0, 1…7) and thecounting stops.

Down Counter (CTD)The down counter (CTD) can be used to

signal when a count has reached zero oncounting down from a preset value. Thesymbol of the down counter (CTD) isshown in Figure 4, while its truth table isgiven in Table 3.

The down counter counts down thenumber of “rising edges” (↑) detected atthe input CD. PV defines starting value forthe counter. Each time the counter is calledwith a new rising edge (↑) on CD, thecount value CV is decremented by one.When the counter reaches zero, thecounter output Q is set true (ON – 1) andthe counting stops.

The load input LD can be used to clearthe output Q to false (OFF – 0) and loadthe count value CV with the preset valuePV. The following section explains theimplementation of eight of 8-bit downcounters for UZAM_PLC.

Macro “CTD_8” (8-bit Down Counter)

The macro “CTD_8” defines 8 down

www.electronicsworld.co.uk ❙ 31

controller – Part 7

Figure 2: (a) The definition of status bits of counter macros(b) The initialization of all variables of counter macros defined as a macro “init_cnts”

Figure 3: The up counter (CTU)

(b)(a)

Table 1: The truth table of the up-counter (CTU)

CU R Operation× 1 1. set the output Q false (OFF – 0)

2. clear the count value CV to zero

0 0 NOP (No Operation is done)

1 0 NOP

↓ 0 NOP

↑ 0 If CV < PV, then increment CV (i.e. CV = CV + 1)

If CV = PV, then hold CV and set the output Q true (ON – 1)

× : don’t care

Page 35: PIC PLC

PLC/MCU

counters selected with the num = 0, 1...7.Table 4 shows the macro “CTD_8” and itssymbol. CD (count down input), Q (outputsignal = counter status bit) and LD (loadinput) are all defined as Boolean variables.The PV (preset value) is an integer constant(here, for an 8-bit resolution, any numberin the range 1-255 is selected) and is usedto define a starting value for the counter.The counter outputs are represented by thecounter status bits: CTD8_Q,num (num = 0,1…7), namely CTD8_Q0,CTD8_Q1…CTD8_Q7, as shown in Figure

2a. We use a Boolean variable, orCTD8_RED,num (num = 0, 1…7)as a rising edge detector foridentifying the rising edges of theCD. An 8-bit integer variableCV_8+num (num = 0, 1…7) isused to count the rising edges ofthe CD.

Let us now briefly consider howthe macro “CTD_8” works. If theinput signal LD is true (ON – 1),then the output signalCTU8_Q,num (num = 0, 1…7) is

forced to be false (OFF – 0) and the counterCV_8+num (num = 0, 1…7) is loaded withPV. If the input signal LD is false (OFF – 0)then with each “rising edge” of the CD,the related counter “CV_8+num” isdecremented by one. In this case, when thecount value of “CV_8+num” is equal tozero, then state-change from 0 to 1 isissued for the output signal (counter statusbit) CTU8_Q,num (num = 0, 1…7) and thecounting stops. ■

Figure 4: The down counter (CTD)

Macro Symbol

32 ❙ May 09 - Electronics World

Table 2: The macro “CTU_8” and its symbol

Table 3: The truth table of the down counter (CTD)

CD LD Operation× 1 1. clear the output Q to false (OFF – 0)

2. load the count value CV with the preset value PV

0 0 NOP (No Operation is done)

1 0 NOP

↓ 0 NOP

↑ 0 If CV > 0, then decrement CV (i.e. CV = CV - 1)

If CV = 0, then hold CV and set the output Q true (ON – 1)

× : don’t care

Macro

Symbol

Table 4: The macro “CTD8” and its symbol

Page 36: PIC PLC

PLC/MCU

30 ❙ June 09 - Electronics World

THE UP/DOWN counter (CTUD) hastwo inputs CU and CD. It can be used toboth, count up on one input and countdown on the other. The symbol of theup/down counter (CTUD) is shown inFigure 1, while its truth table is given inTable 1.

The up/down counter counts up thenumber of “rising edges” (↑) detected atthe input CU. The up/down counter countsdown the number of “rising edges” (↑)detected at the input CD. PV defines themaximum value for the counter. When thecounter reaches the PV value, the counteroutput Q is set true (ON – 1) and thecounting up stops. The reset input R canbe used to set the output Q false (OFF – 0)and clear the count value CV to zero. Theload input LD can be used to load thecount value CV with the preset value PV.When the counter reaches zero, thecounting down stops.

The following section explains theimplementation of eight of 8-bit up/downcounters for UZAM_PLC.

Macro “CTUD_8” (8-bit Down Counter)

The macro “CTUD_8” defines 8 up/down

counters selected with the num = 0, 1...7.Table 2 shows the macro “CTUD_8” andits symbol.

CU (count up input), CD (count downinput), Q (output signal = counter statusbit), R (reset input) and LD (load input) areall defined as Boolean variables. The PV(preset value) is an integer constant (herefor 8-bit resolution it is chosen any numberin the range 1-255) and is used to define a

maximum count value for the counter. Thecounter outputs are represented by thecounter status bits: CTUD8_Q,num (num = 0, 1…7), namely CTUD8_Q0,CTUD8_Q1…CTUD8_Q7, as shown inFigure 2a.

We use a Boolean variable, namelyCTUD8_RED,num (num = 0, 1…7), as arising edge detector for identifying therising edges of the inputs CU or CD. Tocarry out logical operations within themacro “CTUD_8” we use a Booleanvariable, namely CTUD8_FLG,num (num =0, 1…7). An 8-bit integer variableCV_8+num (num = 0, 1…7) is used tocount up the rising edges of the CU andcount down the rising edges of the CD.

Let us now briefly consider how the macro“CTUD_8” works. If the input signal R is true(ON – 1), then the output signalCTU8_Q,num (num = 0, 1…7) is forced to befalse (OFF – 0) and the counter CV_8+num(num = 0, 1…7) is loaded with “00h”.

Associate Professor Dr Murat Uzam from Nigde University in Turkey presentsa series of articles on a project that focuses on a microcontroller-based PLC.This is the eighth article in the series, describing the counter macro CTUD_8(up/down)

PLC with PIC16F648A Micro

Figure 1: The up/down counter (CTUD)

Table 1: The truth table of the up/down counter (CTUD)

CU CD R LD Operation

× × 1 ×1. set the output Q false (OFF – 0)

2. clear the count value CV to zero

× × 0 1 load the count value CV with the preset value PV

0 0 0 0 NOP (No Operation is done)

0 1 0 0 NOP

1 0 0 0 NOP

1 1 0 0 NOP

1 ↑ 0 0 NOP

↑ 1 0 0 NOP

× ↓ 0 0 NOP

↓ × 0 0 NOP

↑ 0 0 0If CV < PV, then increment CV

If CV = PV, then hold CV and set the output Q true (ON – 1)

0 ↑ 0 0 If CV > 0, then decrement CV

Page 37: PIC PLC

PLC/MCU

If the input signal R is false (OFF – 0)and the input signal LD is true (ON – 1),then the counter CV_8+num (num = 0,1…7) is loaded with PV. If the inputsignal R is false (OFF – 0), the input signalLD is false (OFF – 0) and the CD is false(OFF – 0), then with each “rising edge” ofthe CU, the related counter “CV_8+num”is incremented by one.

In this case, when the count value of“CV_8+num” is equal to the PV, thenstate-change from 0 to 1 is issued for theoutput signal (counter status bit)CTU8_Q,num (num = 0, 1…7) and thecounting up stops. If the input signal R isfalse (OFF – 0), the input signal LD is false(OFF – 0) and the CU is false (OFF – 0),then with each “rising edge” of the CD,the related counter “CV_8+num” isdecremented by one. The counting downstops when the CV reaches zero.

Example For Counter MacrosIn this section, we will consider an

example, namelyUZAM_plc_8i8o_ex12.asm to show theusage of counter macros. In order to testthis example please download the relatedfiles from http://host.nigde.edu.tr/muzam/and then open the programUZAM_plc_8i8o_ex12.asm by MPLAB IDEand compile it.

After that, by using the PICprogrammer software, take the compiledfile “UZAM_PLC_8i8o_ex12.hex” and byyour PIC programmer hardware send it tothe program memory of PIC16F648Amicrocontroller within UZAM_PLC. Afterloading the “UZAM_PLC_8i8o_ex12.hex”,switch the 4PDT in “RUN” and the powerswitch in “ON” position. Finally, you areready to test the example program.

www.electronicsworld.co.uk ❙ 31

controller – Part 8(b)(a)

Table 2: The macro “CTUD8” and its symbol

Page 38: PIC PLC

PLC/MCU

To check the correctness of theprogram you are referred to the relatedinformation for each counter functionprovided.

The example program, “UZAM_plc_8i8o_ex12.asm” is shown in Figure 2. It showsthe usage of all counter macros describedin Table 2. The schematic and ladderdiagrams of the user program of“UZAM_plc_8i8o_ex12.asm” shown inFigure 2 are depicted in Figure 3.

In the first two rungs, an up counter“CTU_8” is implemented as follows: thecount up input CU is taken from I0.0,while reset input R is taken from I0.1.num = 0 and, therefore, we choose thefirst up counter, whose counter status bit(or output Q) is CTU8_Q0. The presetvalue PV = 5. As can be seen from thesecond rung, the counter status bitCTU8_Q0 is sent to output Q0.0.

In the rungs 3 and 4, a down counter“CTD_8” is implemented as follows: thecount down input CD is taken from I0.2,while load input LD is taken from I0.3.num = 4 and, therefore, we choose thefifth down counter, whose counter statusbit (or output Q) is CTU8_Q4. The presetvalue PV = 10. As can be seen from theforth rung, the counter status bitCTU8_Q4 is sent to output Q0.4.

In the rungs 5 and 6, an up/downcounter “CTUD_8” is implemented asfollows: CU, CD, R and LD inputs are alltaken from the inputs I0.4, I0.5, I0.6 andI0.7 respectively. Num = 7 and, therefore,we choose the eighth up/down counter,whose counter status bit (or output Q) isCTU8_Q7. The preset value PV = 15. Ascan be seen from the sixth rung, thecounter status bit CTU8_Q7 is sent tooutput Q0.7. ■

If you’ve missed any of the previousarticles in this series, you can now order iton line at www.electronicsworld.co.uk

Figure 2: The user program of UZAM_plc_8i8o_ex12.asm

32 ❙ June 09 - Electronics World

Figure 3: (a) Schematic diagram and (b) Ladder diagram for the user program ofUZAM_plc_8i8o_ex12.asm

(b)(a)

Page 39: PIC PLC

PLC/MCU

www.electronicsworld.co.uk ❙ 29

IN THIS ARTICLE, the followingare described: The contents of tworegisters (R1 and R2) are comparedaccording to the following: GT (GreaterThan – “>”), GE (Greater than or Equal to– “≥”, in the article represented by “>=”),

EQ (EQual to – “=”), LT (Less Than – “<”),LE (Less than or Equal to – “≤”, in thearticle represented by “<=”), NE (NotEqual to – “≠”, in the article representedby “<>”).

Similar comparison macros are also

described for comparing the content of an8-bit register (R) with an 8-bit constant(K). In addition two macros, namely“move_R” and “load_R”, are described fordata transfer.

Move and Load MacrosIn a PLC, numbers are often required to

be moved from one location to another; atimer preset value may be required to bechanged according to plant conditions, orthe result of some calculations may beused in another part of a program.

To satisfy this need for 8-bit variables, inUZAM_PLC we define the macro“move_R”. Similarly, the macro “load_R”is also described to load an 8-bit numberinto an 8-bit variable. These macros areshown in Table 1, together with theiralgorithms and symbols.

In these macros, EN is a Boolean inputvariable taken into the macro through W,and ENO is a Boolean output variable sentout from the macro through W. OutputENO follows the input EN. This means thatwhen EN=0, ENO is forced to be 0 andwhen EN=1, ENO is forced to be 1. This isespecially useful if we want to carry outmore than one move or load operationsbased on a single input condition. WhenEN=1, the macro “move_R” transfers thedata from the 8-bit input variable IN, to

Associate Professor Dr Murat Uzam from Nigde University in Turkey presentsa series of articles on a project that focuses on a microcontroller-based PLC.This is the ninth article in the series describing comparison macros

PLC with PIC16F648AMicrocontroller –Part 9

Table 1: The macros “move_R” and “load_R”, together with their algorithms and symbols

Page 40: PIC PLC

the 8-bit output variable OUT. Similarly,when EN=1, the macro “load_R” transfersthe 8-bit constant data IN, within the 8-bitoutput variable OUT.

The file “mv_ld_mcr_def.inc” includingthe macros “move_R” and “load_R”, canbe downloaded fromhttp://host.nigde.edu.tr/muzam/.

Comparison MacrosNumerical values often need to be

compared in PLC programs; typicalexamples are a batch counter stating therequired number of items that has beendelivered, or alarm circuits indicating, forexample, a temperature has gone abovesome safety level. These comparisons areperformed by elements which have thegeneralized form of Figure 1, with twonumerical inputs A and B corresponding tothe values to be compared, and a Boolean(on/off) output which is true if the specifiedcondition is met. The comparisons providedin this article are as follows:

A greater than B (A > B)A greater than or equal to B (A >= B)A equal to B (A = B)A less than B (A < B)A less than or equal to B (A <= B)A not equal to B (A <> B)

where A and B are 8-bit numerical data. In this article, two groups of comparison

macros are described for UZAM_PLC. In theformer, the contents of two registers (R1and R2) are compared according to thefollowing: GT (Greater Than – “>”), GE(Greater than or Equal to – “>=”), EQ(EQual to – “=”), LT (Less Than – “<”), LE(Less than or Equal to – “<=”), NE (NotEqual to – “<>”). These six macros areshown in Table 2, together with theirdescriptions, algorithms and symbols.

In the latter, similar comparison macrosare also described for comparing thecontents of an 8-bit register (R) with an 8-bit constant (K). The six macros comparingthe contents of an 8-bit register (R) withan 8-bit constant (K) are shown in Table3, together with their descriptions,algorithms and symbols. The file“cmpr_mcr_def.inc” including the 16comparison macros shown in Table 2 andTable 3 can be downloaded fromhttp://host.nigde.edu.tr/muzam/.

Comparison Macros Examples We will consider two examples, namely

UZAM_plc_8i8o_exN.asm, N = 13, 14 toshow the usage of comparison macros. Inorder to test the respected example pleasedownload the files fromhttp://host.nigde.edu.tr/muzam/ and thenopen the UZAM_plc_8i8o_exN.asmprogram, N = 13, 14 by MPLAB IDE andcompile it.

Following that, by using the PICprogrammer software, take the compiledfile “UZAM_PLC_8i8o_exN.hex” and withyour PIC programmer hardware send it tothe program memory of PIC16F648Amicrocontroller within the UZAM_PLC.After loading the “UZAM_PLC_8i8o_exN.hex”, switch the 4PDT in “RUN” andthe power switch in “ON” position.Finally, you are ready to test this programexample.

To check the correctness of eachprogram you are referred to the relatedinformation for each comparison functionprovided in Table 2 and Table 3. Whenstudying these two examples, note thatthe input register I0 is made up of the 8bits: I0.7, I0.6…I0.0 and that I0.7 is themost significant bit (MSB), while I0.0 isthe least significant bit (LSB).

The first example program,

“UZAM_plc_8i8o_ex13.asm” is shown inFigure 2. It shows the usage of all sixcomparison macros for comparing thecontents of two registers as described inTable 2. The schematic and ladder diagramsof the user program of“UZAM_plc_8i8o_ex13.asm” shown inFigure 2 are depicted in Figure 3a and 3b.

In the first rung, 8-bit numerical data“0Fh” is loaded to 8-bit variable M3, (forM3 you should go back to the second partof this article series), by using both themacros “move_R” and “load_R”. Thisprocess is carried out only once at the firstprogram scan by using the “FRSTSCN” NOcontact.

In the rest of the PLC rungs, namelyrungs 2, 3…7, we use six differentcomparison macros as described in Table 2to compare the contents of two 8-bitvariables M3 and I0. As we have M3 loadedwith the numerical 8-bit data “0Fh” theoutputs Q0.0, Q0.1…Q0.5 will be true orfalse based on the input data entered fromthe input bits I0.7, I0.6…I0.0.

The second example program,“UZAM_plc_8i8o_ex14.asm” is shown inFigure 4. It shows the usage of all sixcomparison macros for comparing thecontent of an 8-bit register (R) with an 8-bit constant (K) as described in Table 3. Theschematic and ladder diagrams of the userprogram of “UZAM_plc_8i8o_ex14.asm”shown in Figure 4 are depicted in Figure5a and 5b.

There are six PLC rungs 1, 3…6, each ofwhich is dedicated to one comparisonmacro of Table 3. In these macros, the 8-bitregister (R) is I0 and the 8-bit constant (K) is“0Fh”. As in the previous example, the PLCoutputs Q0.0, Q0.1…Q0.5 will be true orfalse based on the input data entered fromthe input bits I0.7, I0.6…I0.0. (See the restof the tables and figures on the next fewpages). ■

If you’ve missed any of the previousarticles in this series, you can now order iton line at www.electronicsworld.co.uk

PLC/MCU

30 ❙ July 09 - Electronics World

Figure 1: The generalized form of data comparison

Page 41: PIC PLC

PLC/MCU

Tab

le 2

: The

com

paris

on m

acro

s de

scrib

ed f

or c

ompa

ring

the

cont

ents

of

two

8-bi

t re

gist

ers

R1 a

nd R

2, t

oget

her

with

the

ir de

scrip

tions

, alg

orith

ms

and

sym

bols

www.electronicsworld.co.uk ❙ 31

Page 42: PIC PLC

PLC/MCU

Table 3: The com

parison macros described for com

paring the contents of two 8-bit registers R1 and R2, together w

ith their descriptions, algorithms and sym

bols

32 ❙ July 09 - Electronics World

Page 43: PIC PLC

PLC/MCU

www.electronicsworld.co.uk ❙ 33

Figure 2: The user program UZAM_plc_8i8o_ex13.asm

Figure 3: (a) Schematic diagram and (b) Ladder diagram for the user program UZAM_plc_8i8o_ex13.asm

(a)

(b)

Page 44: PIC PLC

PLC/MCU

34 ❙ July 09 - Electronics World

Figure 4: The user program UZAM_plc_8i8o_ex14.asm

Figure 5: (a) Schematic diagram and (b) Ladder diagram for the user program UZAM_plc_8i8o_ex14.asm

(b)

(a)

Page 45: PIC PLC

PLC/MCU

www.electronicsworld.co.uk ❙ 29

IN THIS ARTICLE, six arithmeticalmacros are described. The followingoperators are applied to the contents of tworegisters (R1 and R2): ADD, SUB (subtract),INC (increment), DEC (decrement).

Similar arithmetical macros are alsodescribed to be used with the contents of an8-bit register (R) and an 8-bit constant (K).

Arithmetical MacrosNumerical data implies the ability to do

arithmetical operations, and almost all PLCsprovide some arithmetical operations such asadd, subtract, multiply and divide. Arithmeticalfunctions will retrieve one or more values,perform an operation and store the result inmemory. As an example, Figure 1 shows anADD function that will retrieve and “add” twovalues from sources labelled source A andsource B, and will store the result indestination C. The list of arithmetical functions(macros) described for UZAM_PLC follows. Theincrement and decrement functions are unary,so there is only one source.

ADD (source value 1, source value 2,destination) – add two source values andput the result in the destination.

SUB (source value1, source value 2,destination) – subtract the second sourcevalue from the first one and put the resultin the destination.

INC (source value, destination) –increment the source and put the result inthe destination.

DEC (source value, destination) –decrement the source and put the result inthe destination.

The six arithmetical macros described forUZAM_PLC are shown in Table 1. In thesemacros, EN is a Boolean input variable takeninto the macro through W, and ENO is aBoolean output variable sent out from themacro through W. Output ENO follows theinput EN. This means that when EN = 0,ENO is forced to be 0 and when EN = 1,ENO is forced to be 1.

This is especially useful if we want tocarry out more than one operation based on

a single input condition. “IN”, “R”, “R1”and “R2” refer to 8-bit source variablesfrom where the source values are taken intothe related macro, while “OUT” refers to an8-bit destination variable to which the resultof the related macro is stored. “K”represents an 8-bit constant data to be usedwithin the related macro.

When EN = 1, the macro “R1addR2”adds the contents of two 8-bit variables R1and R2, and stores the result into the 8-bitoutput variable OUT. Similarly, when EN =1, the macro “RaddK” adds the content ofan 8-bit variable R and 8-bit constant dataK, and stores the result into the 8-bitoutput variable OUT.

When EN = 1, the macro “R1subR2”subtracts the contents of 8-bit variable R2from the contents of 8-bit variable R1, andstores the result into the 8-bit outputvariable OUT. Similarly, when EN = 1, themacro “RsubK” subtracts the 8-bit constantdata K from the contents of 8-bit variable R,and stores the result into the 8-bit outputvariable OUT.

When EN = 1, the macro “incR”increments the contents of the 8-bitvariables IN, and stores the result into the8-bit output variable OUT. Finally, when EN= 1, the macro “decR” decrements thecontents of the 8-bit variables IN, and storesthe result into the 8-bit output variableOUT. The file “arthm_mcr_def.inc”including the 6 arithmetical macros shown in

Associate Professor Dr Murat Uzam from Nigde University in Turkey presentsa series of articles on a project that focuses on a microcontroller-based PLC.This is the tenth article in the series describing arithmetical macros

PLC with PIC16F648AMicrocontroller –Part 10

Figure 1: The ADD function

Page 46: PIC PLC

Table 1 can be downloaded fromhttp://host.nigde.edu.tr/muzam/

ExamplesWe will now consider three examples,

namely UZAM_plc_8i8o_exN.asm, with N =15, 16, 17, to show the usage ofarithmetical macros. In order to test theprogram, please download the files fromhttp://host.nigde.edu.tr/muzam/ and thenopen UZAM_plc_8i8o_exN.asm. Make N =15, 16, 17 and compile it. After that byusing the PIC programmer software, takethe compiled file“UZAM_PLC_8i8o_exN.hex” and by yourPIC programmer hardware send it to theprogram memory of PIC16F648Amicrocontroller within the UZAM_PLC. Afterloading the “UZAM_PLC_8i8o_exN.hex”,switch the 4PDT in “RUN” and the powerswitch in “ON” position. Finally, you areready to test the program.

When studying these three examples,note that the output register Q0 is made upof the 8 bits: Q0.7, Q0.6…Q0.0 and thatQ0.7 is the most significant bit (MSB), whileQ0.0 is the least significant bit (LSB). Thethree examples considered here make useof the previously described macros“load_R” and “r_edge” and, therefore, thefiles “mv_ld_mcr_def.inc” and“ff_mcr_def.inc” are included in theseexamples. Also, bI0.1 (respectively bI0.4) isthe bouncing input bit I0.1 (respectivelyI0.4). For more details on the bouncing anddebounced inputs please consider the Part 2article of this series.

The first example program,“UZAM_plc_8i8o_ex15.asm” is shown inFigure 2. It shows the usage of twoarithmetical macros – “R1addR2” and“R1subR2”. The ladder diagram of the userprogram of “UZAM_plc_8i8o_ex15.asm”shown in Figure 2 is depicted in Figure 3.In the first rung, Q0 is cleared, 8-bitnumerical data “02h” is loaded to 8-bitvariable M1 and 8-bit numerical data “03h”is loaded to 8-bit variable M2 (for M1 andM2 please consider the article Part 2) byusing the macro “load_R”. This process is

PLC/MCU

30 ❙ August 09 - Electronics World

Table 1: The arithmetical macros, together with their algorithms and symbols

Page 47: PIC PLC

PLC/MCU

carried out once at the first program scanby using the “FRSTSCN” NO contact.Another condition to carry out the sameprocess is the NO contact of the input I0.0.This means that when this program is run,during the normal PLC operation if we forcethe input I0.0 to be true, then the abovementioned process will take place.

In the PLC rungs 2, 3 and 4, we see howthe arithmetical macro “R1addR2” could beused. In the rung 2, the addition process Q0= Q0 + M1 is carried out, when bI0.1 goestrue. With this rung if bI0.1 goes and staystrue, the Q0 will be added the content ofM1, i.e. numerical data “02h”, on everyPLC scan.

Similar is applicable to the rung 3, wherethe addition process Q0 = Q0 + M1 iscarried out when I0.2 goes true. Again,with this rung if I0.2 goes and stays true,Q0 will be added the content of M1, i.e.numerical data “02h”, on every PLC scan.

Rung 4 provides a little bit different usageof the arithmetical macro “R1addR2”. Here,we use a “rising edge detector” macro inorder to detect the state change of input

I0.3 from OFF to ON. So this time, theaddition process Q0 = Q0 + M1 is carriedout only at the rising edges of I0.3.

In the PLC rungs 5, 6 and 7 we see howthe arithmetical macro “R1subR2” could beused. In the rung 5, the subtraction processQ0 = Q0 – M2 is carried out when bI0.4goes true. With this rung if bI0.4 goes andstays true, the content of M2, i.e. numericaldata “03h”, will be subtracted from thecontent of Q0 on every PLC scan. Similar isapplicable to rung 6, where the subtractionprocess Q0 = Q0 – M2 is carried out whenI0.5 goes true.

Again, with this rung if I0.5 goes andstays true, the content of M2, i.e. numericaldata “03h”, will be subtracted from thecontent of Q0, on every PLC scan. Rung 7provides a little bit different usage of thearithmetical macro “R1subR2”. Here, weuse a “rising edge detector” macro in orderto detect the state change of input I0.6 fromOFF to ON. So this time, the subtractionprocess Q0 = Q0 – M2 is carried out only atthe rising edges of I0.6.

Second ExampleThe second example program,

“UZAM_plc_8i8o_ex16.asm”, is shown inFigure 4. It shows the usage of twoarithmetical macros “RaddK” and “RsubK”.The ladder diagram of the user program of“UZAM_plc_8i8o_ex16.asm” shown inFigure 4 is depicted in Figure 5.

In the first rung Q0 is cleared, by using themacro “load_R”. This process is carried outonce at the first program scan by using the“FRSTSCN” NO contact.

Another condition to carry out the sameprocess is the NO contact of the input I0.0.This means that when this program is run,during the normal PLC operation if we forcethe input I0.0 to be true, then Q0 is cleared.

In the PLC rungs 2, 3 and 4 we see howthe arithmetical macro “RaddK” could beused. In rung 2 the addition process Q0 = Q0+ 2 is carried out when bI0.1 goes true. Withthis rung if bI0.1 goes and stays true, the Q0will be added the numerical data “02h” onevery PLC scan. Similar is applicable to rung3, where the addition process Q0 = Q0 + 2 iscarried out when I0.2 goes true. Again withthis rung, if I0.2 goes and stays true, the Q0will be added the numerical data “02h” onevery PLC scan.

Rung 4 provides a little bit different usageof the arithmetical macro “RaddK”. Here, weuse a “rising edge detector” macro in orderto detect the state change of input I0.3 fromOFF to ON. So this time the addition processQ0 = Q0 + 2 is carried out only at the risingedges of I0.3.

In the PLC rungs 5, 6 and 7 we see howthe arithmetical macro “RsubK” could beused. In rung 5 the subtraction process Q0 =Q0 – 3 is carried out when bI0.4 goes true.With this rung if bI0.4 goes and stays true,the numerical data “03h” will be subtractedfrom the content of Q0 on every PLC scan.Similar is applicable to rung 6, where thesubtraction process Q0 = Q0 – 3 is carriedout when I0.5 goes true. Again with thisrung if I0.5 goes and stays true, thenumerical data “03h” will be subtractedfrom the content of Q0 on every PLC scan.

Rung 7 provides a little bit different usage

www.electronicsworld.co.uk ❙ 31

Figure 2: The user program of UZAM_plc_8i8o_ex15.asm

Page 48: PIC PLC

of the arithmetical macro “RsubK”. Here, weuse a “rising edge detector” macro in orderto detect the state change of input I0.6 fromOFF to ON. So this time the subtractionprocess Q0 = Q0 – 3 is carried out only atthe rising edges of I0.6.

Third ExampleThe third and last example program,

“UZAM_plc_8i8o_ex17.asm”, is shown inFigure 6. It shows the usage of twoarithmetical macros “incR” and “decR”. The ladder diagram of the user program of“UZAM_plc_8i8o_ex16.asm” shown inFigure 6 is depicted in Figure 7.

In the first rung Q0 is cleared by usingthe macro “load_R”. This process iscarried out once at the first program scanby using the “FRSTSCN” NO contact.

Another condition to carry out the sameprocess is the NO contact of the inputI0.0. This means that when this program isrun, during the normal PLC operation ifwe force the input I0.0 to be true, thenQ0 is cleared. In the PLC rungs 2, 3 and 4,we see how the arithmetical macro “incR”could be used. In the rung 2, Q0 isincremented by one, i.e. the process Q0 =Q0 + 1 is carried out, when bI0.1 goestrue. With this rung if bI0.1 goes and staystrue, then Q0 is incremented by one on

PLC/MCU

Figure 4: The user program of UZAM_plc_8i8o_ex16.asm

32 ❙ August 09 - Electronics World

Figure 3: Ladder diagram for the user program of UZAM_plc_8i8o_ex15.asm

Page 49: PIC PLC

every PLC scan. Similar is applicable torung 3, where Q0 is incremented by oneon every PLC scan when I0.2 goes andstays true.

Rung 4 provides a little bit differentusage of the arithmetical macro “incR”.Here, we use a “rising edge detector”macro in order to detect the state changeof input I0.3 from OFF to ON. So this time,Q0 is incremented by one only at the risingedges of I0.3.

In the PLC rungs 5, 6 and 7 we see howthe arithmetical macro “decR” could beused. In rung 5, Q0 is decremented byone, i.e. the process Q0 = Q0 – 1 is carriedout when bI0.4 goes true. With this rung,if bI0.4 goes and stays true Q0 isdecremented by one on every PLC scan.Similar is applicable to rung 6, where Q0 isdecremented by one on every PLC scanwhen I0.5 goes and stays true.

Rung 7 provides a little bit differentFigure 6: The user program of UZAM_plc_8i8o_ex17.asm

www.electronicsworld.co.uk ❙ 33

PLC/MCU

Figure 5: Ladder diagram for the user program of UZAM_plc_8i8o_ex16.asm

Page 50: PIC PLC

PLC/MCU

usage of the arithmetical macro “decR”.Here we use a “rising edge detector”macro in order to detect the state change

of input I0.6 from OFF to ON. So this time,Q0 is decremented by one only at therising edges of I0.6. ■

If you’ve missed any of the previousarticles in this series, you can now order iton line at www.electronicsworld.co.uk

WEB DIRECTORY

34 ❙ August 09 - Electronics World

Page 51: PIC PLC

PLC/MCU

38 ❙ September 09 - Electronics World

THE LOGICAL MACROS AND,NAND, OR, NOR, XOR, XNOR and inv_R areapplied to an 8-bit register (R1) with anotherregister (R2) or an 8-bit constant (K).

A logical function performs AND, NAND,OR, NOR, exclusive-OR (XOR), exclusive-NOR (XNOR) logical operations on tworegisters (or one register plus one constantvalue) and NOT (invert) logical operationon one register.

As an example, Figure 1 shows an ANDlogical function that will retrieve and“AND” two values from sources labelledsource A and source B and will store theresult in destination C. AND, NAND, OR,NOR, XOR and XNOR logical functionshave the form of Figure 1 with two sourcevalues and one destination register. Inthese, the logical function is applied tothe two source values and the result is putin the destination register. However, theunary invert (INV) logical function has onesource register and one destination

register. It inverts all of the bits in thesource register and puts the result in thedestination register.

Here I’ll describe thirteen logical macrosfor UZAM_PLC, as shown in Table 1. Inthese macros, EN is a Boolean inputvariable taken into the macro through W,and ENO is a Boolean output variable sentout from the macro through W. OutputENO follows the input EN. This means thatwhen EN=0, ENO is forced to be 0 andwhen EN=1, ENO is forced to be 1. This isespecially useful if we want to carry outmore than one operation based on asingle input condition.

“IN”, “R”, “R1” and “R2” refer to 8-bitsource variables from where the sourcevalues are taken into the related macro,while “OUT” refers to an 8-bit destinationvariable to which the result of the relatedmacro is stored. “K” represents an 8-bitconstant data to be used within therelated macro. When EN=1, the macros

“R1andR2”, “R1nandR2”, “R1orR2”,“R1norR2”, “R1xorR2” and “R1xnorR2”carry out the logical operations AND,NAND, OR, NOR, XOR and XNORrespectively on two 8-bit variables R1 andR2, and they store the result into the 8-bitoutput variable OUT.

Similarly, when EN=1, the macros“RandK”, “RnandK”, “RorK”, “RnorK”,“RxorK” and “RxnorK” carry out thelogical operations AND, NAND, OR, NOR,XOR and XNOR respectively on thecontent of an 8-bit variable R and an 8-bitconstant data K, and they store the resultinto the 8-bit output variable OUT.

Finally, when EN=1, the macro “inv_R”inverts all of the bits in the 8-bit sourceregister IN and puts the result in the 8-bitdestination register OUT.

Logical Macros ExampleIn this section, we will consider an

example program(UZAM_plc_8i8o_ex18.asm) to show theusage of all logical macros. In order to testthis example please download the filefrom http://host.nigde.edu.tr/muzam/ andthen open the programUZAM_plc_8i8o_ex18.asm by MPLAB IDEand compile it. After that, by using thePIC programmer software, take thecompiled file “UZAM_plc_8i8o_ex18.hex”

Associate Professor Dr Murat Uzam from Nigde University in Turkey presentsa series of articles on a project that focuses on a microcontroller-based PLC.This is the eleventh article in the series describing the logical macros AND,NAND, OR, NOR, XOR, XNOR and inv_R

PLC with PIC16F648AMicrocontroller –Part 11

Figure 1: The AND function

Page 52: PIC PLC

PLC/MCU

and with PIC programmer hardware sendit to the program memory of PIC16F648Amicrocontroller within the UZAM_PLC.After loading the “UZAM_plc_8i8o_ex18.hex”, switch the 4PDT in “RUN” and the power switch in “ON” position.Finally, the example program is ready tobe tested.

To check the correctness of the programyou are referred to the related informationfor the logical macros provided in Table 1.When studying the example, note that theoutput register Q0 is made up of the 8bits: Q0.7, Q0.6…Q0.0 and that Q0.7 isthe most significant bit (MSB), while Q0.0is the least significant bit (LSB). Similarly,note that the input register I0 is made upof the 8 bits: I0.7, I0.6…I0.0 and that I0.7is the MSB while I0.0 is the LSB. The theexample considered here makes use of thepreviously described macro “load_R”, sothe file “mv_ld_mcr_def.inc” is includedas well.

The example program,“UZAM_plc_8i8o_ex18.asm” is shown inFigure 2. The ladder diagram of the userprogram of “UZAM_plc_8i8o_ex18.asm”shown in Figure 2 is depicted in Figure 3.This example is more complicated than theones considered in the previous articles ofthis series.

As can be seen from Figure 2, we defineand use three additional 8-bit variables:REG1, REG2 and REG3. In the first rung,Q0 is cleared, 8-bit numerical data “F0h”– the mask data – is loaded to 8-bitvariable REG1, and 8-bit numerical data“50h” is loaded to 8-bit variable REG2 byusing the macro “load_R”. This process iscarried out once at the first program scanby using the “FRSTSCN” NO contact.

Another condition to carry out the sameprocess is the NO contact of the inputI0.0. This means that when this program isrun during the normal PLC operation, ifwe force the input I0.0 to be true, then Table 1: The logical macros together with their algorithms and symbols (continued)

www.electronicsworld.co.uk ❙ 39

Page 53: PIC PLC

40 ❙ September 09 - Electronics World

the above mentioned process will takeplace. In the 13 PLC rungs between 2 and14, a “4 to 16 decoder” is implemented,whose inputs are I0.3, I0.2, I0.1 and I0.0,and whose outputs are M0.0, M0.1...M0.7, M1.0, M1.1...M1.4. Note that onlythe first 13 combinations are utilised,while the following combinations forinputs (I0.3, I0.2, I0.1, I0.0): 1101, 1110and 1111 are not implemented. Therefore,for these combinations of the inputs I0.3,I0.2, I0.1 and I0.0, the program will notproduce any meaningful output.

This arrangement is made to choose 13different processes based on the inputinformation given through the input bitsI0.3, I0.2, I0.1 and I0.0. Table 2 showsthe truth table based on the input dataentered through I0.3, I0.2, I0.1 and I0.0,and the 13 chosen processes. In the 13PLC rungs between 15 and 27, we definedifferent logical operations according tothe decoder output represented by themarker bits M0.0, M0.1...M0.7, M1.0,M1.1...M1.4. In these 13 rungs, the firstcontacts represent the decoder outputand, in the second place, we use a macro“R1andR2” whose inputs are “I0” and“REG1” (having being loaded with “F0h”data throughout the PLC operation) andwhose output is REG3. This is solely donein order to “mask” the lower nibble (lower4 bits) of the input register I0, because wealready use the lower nibble as the inputbits of the “4 to 16 decoder”. Therefore,the logical operations placed in the thirdplaces of these 13 rungs are onlyapplicable to the higher nibble of I0(REG3). This fact can be seen from Table 2.

As an example let us consider the rung27. When M1.4 = 1, which implies thatinput bits are (I0.3, I0.2, I0.1, I0.0) =1100, the following function is chosen tobe done: Q0 = REG3 (I0.7, I0.6, I0.5, I0.4,0, 0, 0, 0) XNOR 50h. This means that thehigher nibble of REG3, which is made upof input bits I0.7, I0.6, I0.5, I0.4 will besubject to XNOR logical function with theTable 1: Continued from the previous page

Page 54: PIC PLC

www.electronicsworld.co.uk ❙ 41

PLC/MCU

Figure 2: The user program of UZAM_plc_8i8o_ex18.asm

Page 55: PIC PLC

PLC/MCU

Table 2: The truth table of the user program of “UZAM_plc_8i8o_ex18.asm”

Figure 3: Ladder diagram for the user program ofUZAM_plc_8i8o_ex18.asm

data “0101” and the result will appearfrom the output bits Q0.7, Q0.6, Q0.5,Q0.4. When this program is run, thelower nibble of the output Q0 will alwaysbe observed to be all zeros, i.e. (Q0.3,Q0.2, Q0.1, Q0.0) = 0000. ■

If you’ve missed any of the previousarticles in this series, you can now orderit on line atwww.electronicsworld.co.uk

42 ❙ September 09 - Electronics World

Page 56: PIC PLC

PLC/MCU

THE FOLLOWING SHIFT & Rotatemacros are described in this article: SHIFT_R (shiftright the content of register R), SHIFT_L (shift leftthe content of register R), ROTATE_R (rotateright the content of register R), ROTATE_L(rotate left the content of register R), SWAP(swap the nibbles of the register).

A shift function (SHIFT) moves the bits in aregister to the right or to the left. As an example,Figure 1 shows a shift right function that willretrieve the input data from the source register Aand shifts the bits of source register A towardsright as many number as specified by the numberof shift, while the serial data is taken from leftthrough the Boolean input variable “shift in bit”.The result of the shift operation will be stored ina destination register B.

In this case, the least significant bit (LSB) isshifted out as many numbers as specified by thenumber of shift. A shift left function is identical,except that the shift in bit, taken from the right,is moved in the opposite direction towards left,shifting out the most significant bit (MSB) by asmany a number as specified by the number of‘shift’.

A rotate function (ROTATE), like a shiftfunction, shifts data to the right or left; butinstead of losing the shift-out bit, this bitbecomes the shift-in bit at the other end of theregister (rotated bit). The number of ‘rotate’defines how many bits will be rotated to theright or left. Similar to the shift function, theresult of the rotate operation will be stored in adestination register B.

In this article, there are two shift (shift rightand shift left) macros, two rotate (rotate rightand rotate left) macros and a swap macrodescribed for UZAM_PLC as shown in Table 1.In these macros, EN is a Boolean input variabletaken into the macro through W and ENO is aBoolean output variable sent out from the macrothrough W. Output ENO follows the input EN.This means that when EN=0, ENO is forced tobe 0 and when EN=1, ENO is forced to be 1.This is especially useful if we want to carry outmore than one operation based on a singleinput condition.

“IN” and “RIN” refer to 8-bit source variablesfrom where the source values are taken into the

PLC with PIC16F648AMicrocontroller – Part 12

Table 1: The shift&rotate macros, together with their algorithms and symbols(continued on the next page)

36 ❙ October 09 - Electronics World

Page 57: PIC PLC

PLC/MCU

related macro, while “OUT” and “ROUT” refersto 8-bit destination variables to which the resultsof the related macros are stored. In shift macros,namely “SHIFT_R” and “SHIFT_L”, N representsthe number of shift, which can be any numberin 1, 2...8. Again in shift macros, SIN is theBoolean input variable “shift in bit”. In rotatemacros, namely “ROTATE_R” and “ROTATE_L”,N represents the number of ‘rotate’, which canbe any number in 1, 2...7.

When EN=1, the macro “SHIFT_R” willretrieve the 8-bit input data from RIN and shiftsthe bits of RIN towards right as many a number

as specified by N, while the serial data is takenfrom left through SIN. The result of the shiftright operation will be stored in 8-bit outputregister ROUT.

When EN=1, the macro “SHIFT_L” willretrieve the 8-bit input data from RIN and shiftsthe bits of RIN towards left as many times asspecified by N, while the serial data is takenfrom right through SIN. The result of the shiftright operation will be stored in 8-bit outputregister ROUT.

When EN=1, the macro “ROTATE_R”, willretrieve the 8-bit input data from RIN and

rotates the bits of RIN towards right as many anumber as specified by N. The result of the shiftright operation will be stored in 8-bit outputregister ROUT. When EN=1, the macro“ROTATE_L”, will retrieve the 8-bit input datafrom RIN and rotates the bits of RIN towards leftas many a number as specified by N. The resultof the shift left operation will be stored in 8-bitoutput register ROUT.

In addition to these shift and rotate macros,here we define a “swap” macro. When EN=1,the macro “SWAP”, will retrieve the 8-bit inputdata from IN and swaps (exchanges the upperand lower nibbles – 4 bits) the nibbles of RIN.The result of the swap operation will be storedin 8-bit output register ROUT. The file“shift_mcr_def.inc” including the 7 shift&rotatemacros shown in Table 1 can be downloadedfrom http://host.nigde.edu.tr/muzam/.

Examples of the Shift & Rotate MacrosHere we will consider two examples of the

UZAM_plc_8i8o_exN.asm with N = 19, 20 toshow the usage of the shift&rotate macros. Inorder to test this example, you should downloadthe files from http://host.nigde.edu.tr/muzam/and then open the program UZAM_plc_8i8o_exN.asm, N = 19, 20 by MPLAB IDE andcompile it. After that, by using the PICprogrammer software, take the compiled file“UZAM_PLC_8i8o_exN.hex” and with a PICprogramming hardware send it to the programmemory of PIC16F648A microcontroller withinthe UZAM_PLC. After loading the “UZAM_PLC_8i8o_exN.hex”, switch the 4PDT in “RUN”and the power switch in “ON” position. Theexample program is ready for test.

To check the correctness of each program youare referred to the related information for eachshift&rotate macro provided in Table 1. Whenstudying these three examples, note that theoutput register Q0 is made up of the 8-bits:Q0.7, Q0.6...Q0.0 and that Q0.7 is the mostsignificant bit (MSB), while Q0.0 is the leastsignificant bit (LSB).

Similarly, note that the input register I0 ismade up of the 8-bits: I0.7, I0.6...I0.0 and thatI0.7 is the MSB while I0.0 is the LSB. The twoexamples considered here make use of the

www.electronicsworld.co.uk ❙ 37

Associate Professor Dr Murat Uzam from Nigde University in Turkey presentsa series of articles on a project that focuses on a microcontroller-based PLC.This is the twelfth article in the series describing the Shift & Rotate macros

Figure 1: The SHIFT RIGHT function

Table 1: Continued from the previous page

Page 58: PIC PLC

PLC/MCU

38 ❙ October 09 - Electronics World

previously described macros “load_R” and“r_edge” and, so, the files “mv_ld_mcr_def.inc”and “ff_mcr_def.inc” are included too.

Example OneThe first example program, “UZAM_plc_8i8o_

ex19.asm” is shown in Figure 2. It shows theusage of two shift macros “SHIFT_R” and“SHIFT_L”. The ladder diagram of the userprogram of “UZAM_plc_8i8o_ex19.asm” shownin Figure 2 is depicted in Figure 3.

As can be seen from Figure 2, we define anduse an additional 8-bit variable called REG. In

the first rung, 8-bit numerical data “F0h” isloaded to 8-bit variable REG, by using the macro“load_R”.

This process is carried out once at the firstprogram scan by using the “FRSTSCN” NOcontact. In the 8 PLC rungs between 2 and 9, a“3 to 8 decoder” is implemented, whose inputsare I0.2, I0.1 and I0.0, and whose outputs areM0.0, M0.1...M0.7. This arrangement is madeto choose the number of shift for the selectedshift right or shift left operation based on theinput information given through the input bitsI0.2, I0.1 and I0.0. When these bits are 001,

010, 100, 100, 101, 110, 111 and 000, wedefine the number of shift for the selected shiftright or shift left operation as 1, 2, 3, 4, 5, 6, 7and 8, respectively.

In the 8 PLC rungs between 10 and 17, wedefine 8 different shift right operationsaccording to the 3 to 8 decoder outputsrepresented by the marker bits M0.0,M0.1...M0.7. Shift right operations defined inthese rungs are applied to the 8-bit inputvariable REG, holding the 8-bit value “F0h”throughout the PLC operation. The result of theshift right operations defined in these rungs willbe stored in Q0. The “shift in bit” for these shiftright operations defined in these rungs is I0.5.

The only difference for these eight shift rightoperations is the number of shift. It can be seenthat for each rung one “rising edge detector” isused. This is to make sure that when the relatedshift right operation is chosen, it will be carriedout only once. In order to choose one of these 8shift right operations the input bits I0.4 and I0.3must be as follows: I0.4=0, I0.3=1.

In the 8 PLC rungs between 18 and 25, wedefine 8 different shift left operations accordingto the 3 to 8 decoder outputs represented bythe marker bits M0.0, M0.1...M0.7. Shift leftoperations defined in these rungs are applied tothe 8-bit input variable REG, holding the 8-bitvalue “F0h” throughout the PLC operation. Theresult of the shift left operations defined in theserungs will be stored in Q0. The “shift in bit” forthese shift left operations defined in these rungsis I0.6.

The only difference for these eight shift leftoperations is the number of shift. It can be seenthat for each rung one “rising edge detector” isused. This is to make sure that when the relatedshift left operation is chosen, it will be carriedout only once. In order to choose one of these 8shift left operations, the input bits I0.4 and I0.3must be set as follows: I0.4=1, I0.3=0. Table 2shows the truth table of the userprogram“UZAM_plc_8i8o_ex19.asm”.

Example TwoThe second example program, “UZAM_

plc_8i8o_ex20.asm”, is shown in Figure 4. Itshows the usage of three shift&rotate macros“ROTATE_R”, “ROTATE_L” and “SWAP”.

The ladder diagram of the user program of“UZAM_plc_8i8o_ex20.asm” shown in Figure 4is depicted in Figure 5. As can be seen fromFigure 4, we define and use an additional 8-bitvariable called, REG.

In the first rung, 8-bit numerical data “F0h” isloaded to 8-bit variable REG, by using the macro“load_R”. This process is carried out once at the

Table 2: The truth table of the user program “UZAM_plc_8i8o_ex19.asm”×: Don’t care. Note that the resut of the shift operations will be stored in Q0

Table 3: The truth table of the user program “UZAM_plc_8i8o_ex20.asm”×: Don’t care. Note that the resut of the rotate operations will be stored in Q0. In addition, when I0 = 10h, “Swap REG (F0h) and store the result in Q0” process is selected

Page 59: PIC PLC

first program scan by using the “FRSTSCN” NOcontact. In the 7 PLC rungs between 2 and 8, a“3 to 8 decoder” is implemented with inputsthat are I0.2, I0.1 and I0.0, and whose outputsare M0.1, M0.2...M0.7.

Note that the first combination of 3 to 8decoder, namely (I0.2, I0.1, I0.0) = 000 is notimplemented. Therefore, for this combinationthe program will not produce any meaningfuloutput. This arrangement is made to choose thenumber of rotate for the selected rotate right orrotate left operation based on the inputinformation given through the input bits I0.2,I0.1 and I0.0. When these bits are 001, 010,100, 100, 101, 110 and 111, we define thenumber of rotate for the selected rotate right orrotate left operation as 1, 2, 3, 4, 5, 6 and 7,respectively.

In the 7 PLC rungs between 9 and 15 wedefine 7 different rotate right operationsaccording to the 3 to 8 decoder outputsrepresented by the marker bits M0.1,M0.2...M0.7. Rotate right operations defined inthese rungs are applied to the 8-bit inputvariable REG, holding the 8-bit value “F0h”throughout the PLC operation. The result of therotate right operations defined in these rungswill be stored in Q0.

The only difference for these seven rotateright operations is the number of rotate. It canbe seen that for each rung one “rising edgedetector” is used. This is to make sure thatwhen the related rotate right operation ischosen, it will be carried out only once. In orderto choose one of these 7 rotate right operations,the input bits I0.4 and I0.3 must be as follows:I0.4=0, I0.3=1. In the 7 PLC rungs between 16and 22 we define 7 different rotate leftoperations according to the 3 to 8 decoderoutputs represented by the marker bits M0.1,M0.2...M0.7. Rotate left operations defined inthese rungs are applied to the 8-bit inputvariable REG, holding the 8-bit value “F0h”throughout the PLC operation. The result of therotate left operations defined in these rungs willbe stored in Q0.

The only difference for these seven rotate leftoperations is the number of rotate. It can beseen that for each rung one “rising edgedetector” is used. This is to make sure thatwhen the related rotate left operation is chosen,it will be carried out only once. In order tochoose one of these 7 rotate left operations, theinput bits I0.4 and I0.3 must be set as follows:I0.4=1, I0.3=0. In the last rung 23, an example isused to show the use of swap function.

If the 8-bit input register I0 is set to be “10h”,then the “Swap REG (F0h) and store the result in

www.electronicsworld.co.uk ❙ 39

PLC/MCU

Figure 2: The user program UZAM_plc_8i8o_ex19.asm

Page 60: PIC PLC

PLC/MCU

Figure 3: Ladder diagram for the user program UZAM_plc_8i8o_ex19.asm

Q0” process is selected. In this case we shall observe the 8-bit output registerQ0 to be “0Fh”. Table 3 shows the truth table of the user program“UZAM_plc_8i8o_ex20.asm”. ■If you’ve missed any of the previous articles in this series, you can now order iton line at www.electronicsworld.co.uk

40 ❙ October 09 - Electronics World

Figure 5: Ladder diagram for the user program UZAM_plc_8i8o_ex20.asm

Page 61: PIC PLC

PLC/MCU

Figure 4: The user program UZAM_plc_8i8o_ex20.asm

www.electronicsworld.co.uk ❙ 41

Page 62: PIC PLC

PLC/MCU

IN THIS ARTICLE, the followingmultiplexer macros are described: mux_2_1(2×1 MUX), mux_2_1_E (2×1 MUX withEnable input), mux_4_1 (4×1 MUX),mux_4_1_E (4×1 MUX with Enable input),mux_8_1 (8×1 MUX), mux_8_1_E (8×1 MUXwith Enable input). Five examples will beprovided in the next article to show theapplicability of these multiplexer macros.

As a standard combinational component,the multiplexer, abbreviated as MUX, allowsthe selection of one input signal among nsignals, where n > 1 and is a power of two.Selected lines connected to the multiplexerdetermine which input signal is chosen andpassed to the output of the multiplexer. Ascan be seen from Figure 1, in general, an n-to-1 multiplexer has n data input lines, mselect lines where m = log2 n, i.e. 2m = n,and one output line. Although, not shown inFigure 1, in addition to the other inputs, themultiplexer may have an enable line, E, forenabling it. When the multiplexer is disabledwith E set to 0 (for active-high enable inputE), no input signal is selected and passed tothe output.

The macro “mux_2_1” is shown in Table1, together with its symbol and truth table. In

this macro, “s0” is a Boolean input variabletaken into the macro through “regs0,bits0”and it represents the select input; “d0” and

“d1” are Boolean input variables taken intothe macro through “regi0,biti0” and“regi1,biti1” respectively, and they represent

Associate Professor Dr Murat Uzam from Nigde University in Turkey presentsa series of articles on a project that focuses on a microcontroller-based PLC.This is the thirteenth article in the series describing multiplexer macros

PLC with PIC16F648AMicrocontroller – Part 13

Table 2: The macro “mux_2_1_E” together with its symbol and truth tableFigure 1: The general form of an n-to-1multiplexer, where n = 2m

Table 1: The macro “mux_2_1” together with its symbol and truth table

42 ❙ November 09 - Electronics World

Page 63: PIC PLC

PLC/MCU

two input signals. Finally, “y” is a Booleanoutput variable produced as an outputthrough “rego,bito” and it represents theoutput signal.

In this MUX, when s0 = 0, the input signal“d0” is selected and passed to the output“y”. When s0 = 1, the input signal “d1” isselected and passed to the output “y”.

The macro “mux_2_1_E” is shown inTable 2, together with its symbol and truthtable. In addition to the “mux_2_1”, thismultiplexer macro has an active-high enableline, E, for enabling it. In this macro, E is aBoolean input variable taken into the macrothrough W. When this multiplexer is disabledwith E set to 0, no input signal is selectedand passed to the output “y”. When thismultiplexer is enabled with E set to 1, itfunctions as described for “mux_2_1”.

The macro “mux_4_1” is shown in Table3, together with its symbol and truth table. Inthis macro, “s1” and “s0” are Boolean inputvariables taken into the macro through“regs1,bits1” and “regs0,bits0” respectivelyand they represent the chosen inputs. “d0”,“d1”, “d2” and “d3” are Boolean inputvariables taken into the macro through“regi0,biti0”, “regi1,biti1”, “regi2,biti2” and“regi3,biti3”, and they represent four inputsignals. Finally, “y” is a Boolean outputvariable produced as an output through“rego,bito” and it represents the outputsignal. In this MUX, when s1s0 = 00,(respectively, 01, 10, 11) the input signal“d0” (respectively, d1, d2, d3) is selected andpassed to the output “y”.

The macro “mux_4_1_E” is shown inTable 4, together with its symbol and thetruth table. In addition to the “mux_4_1”,this multiplexer macro has an active-highenable line, E, for enabling it. In this macro, Eis a Boolean input variable taken into themacro through W. When this multiplexer isdisabled with E set to 0, no input signal isselected and passed to the output. When thismultiplexer is enabled with E set to 1, itfunctions as described for “mux_4_1”.

The macro “mux_8_1” is shown in Table5, together with its symbol and truth table. In

www.electronicsworld.co.uk ❙ 43

Table 3: The macro “mux_4_1” together with its symbol and truth table

Table 4: The macro “mux_4_1_E” together with its symbol and truth table

Page 64: PIC PLC

PLC/MCU

this macro, “s2”, “s1” and“s0” are Boolean input variablestaken into the macro through“regs2,bits2”, “regs1,bits1”and “regs0,bits0” respectivelyand they represent the selectinputs. “d0”, “d1”, “d2”, “d3”,“d4”, “d5”, “d6” and “d7”areBoolean input variables takeninto the macro through“regi0,biti0”, “regi1,biti1”,“regi2,biti2”, “regi3,biti3”,“regi4,biti4”, “regi5,biti5”,“regi6,biti6” and “regi7,biti7”respectively, and they representeight input signals. Finally, “y”is a Boolean output variableproduced as an output through“rego,bito” and it representsthe output signal. In this MUX,when s2s1s0 = 000,(respectively, 001, 010, 011,

100, 101, 110, 111) the input signal“d0” (respectively, d1, d2, d3, d4, d5,d6, d7) is selected and passed to theoutput “y”.

The macro “mux_8_1_E” is shownin Table 6, together with its symboland the truth table. In addition to the“mux_8_1”, this multiplexer macro hasan active-high enable line, E, forenabling it. In this macro, E is aBoolean input variable taken into themacro through W. When thismultiplexer is disabled with E set to 0,no input signal is selected and passedto the output. When this multiplexer isenabled with E set to 1, it functions asdescribed for “mux_8_1”.

The file “mux_mcr_def.inc”including the 6 multiplexer macrosshown in Tables 1, 2…6 can bedownloaded fromhttp://host.nigde.edu.tr/muzam/. ■

If you’ve missed any of the previousarticles in this series, you can noworder it on line atwww.electronicsworld.co.uk

Table 5: The macro “mux_8_1” together with its symbol and truth table

Table 6: The macro “mux_8_1_E” together with its symbol and truth table

44 ❙ November 09 - Electronics World

Page 65: PIC PLC

PLC/MCU

IN THIS ARTICLE we will considerfive examples, namely UZAM_plc_8i8o_exN.asm, where N = 21, 22…25, to showthe use of multiplexer macros described inthe previous article. In order to test theexample you can download the files fromhttp://host.nigde.edu.tr/muzam/ and thenopen the UZAM_plc_8i8o_exN.asmprogram by MPLAB IDE and compile it.

Following that, with the PIC programmersoftware take the compiled file “UZAM_PLC_8i8o_exN.hex” and with the PICprogrammer hardware send it to theprogram memory of PIC16F648Amicrocontroller within the UZAM_PLC.After loading the “UZAM_PLC_8i8o_exN.hex”, switch the 4PDT in “RUN” andthe power switch in the “ON” position.Finally, you are ready to test the exampleprogram.

To check the correctness of eachprogram, you are referred to the relatedinformation for each multiplexer macroprovided in Tables 1, 2…6 of the previousarticle. Note that, in some of theseexamples, we use some of the eight freerunning reference timing signals, namelyT8, T9…T15 with the “T” timing periods131.072ms, 262.144ms…16777.216msrespectively.

Example ProgramsThe first example program,

“UZAM_plc_8i8o_ex21.asm”, is shown inFigure 1. It shows the usage of twomultiplexer macros “mux_2_1” and“mux_2_1_E”. The schematic diagram ofthe user program of “UZAM_plc_8i8o_ex21.asm” shown in Figure 1, is depictedin Figure 2. In the first rung, the

Associate Professor Dr Murat Uzam from Nigde University in Turkey presents aseries of articles on a project that focuses on a microcontroller-based PLC. This is thefourteenth article where five examples are provided to show the use of multiplexermacros described in the last issue’s article – Part 13

PLC with PIC16F648AMicrocontroller – Part 14

Figure 3: The user program UZAM_plc_8i8o_ex22.asm

Figure 1: The user program UZAM_plc_8i8o_ex21.asm

Figure 2: Schematic diagram for the user program UZAM_plc_8i8o_ex21.asm

40 ❙ December 09 - Electronics World

Page 66: PIC PLC

PLC/MCU

multiplexer macro “mux_2_1” (2×1multiplexer) is used. In this multiplexer, theinput signals are d0 = I0.1 and d1 = I0.2,while the output is y = Q0.0 and the selectinput is s0 = I0.0.

In the second rung, the macro “mux_2_1_E” (2×1 multiplexer with active highenable input) is used. In this multiplexer,the input signals are d0 = T10 (524.288ms)and d1 = T11 (1048.576ms), while theoutput is y = Q0.7 and the select input iss0 = I0.7. In addition, the active highenable input E is defined to be E = I0.6.

The second example program,“UZAM_plc_8i8o_ex22.asm”, is shown inFigure 3. It shows the usage of themultiplexer macro “mux_4_1”. Theschematic diagram of the user program of“UZAM_plc_8i8o_ex22.asm” shown inFigure 3, is depicted in Figure 4. In thisexample, the multiplexer macro“mux_4_1” (4×1 multiplexer) is used. Inthis multiplexer, the input signals d0, d1,d2 and d3 are defined to be I0.2, I0.3, I0.4and I0.5 respectively, while the output is y= Q0.0 and the select inputs s0 and s1 areI0.1 and I0.0.

The third example program,“UZAM_plc_8i8o_ex23.asm”, is shown inFigure 5. It shows the usage of themultiplexer macro “mux_4_1_E”. Theschematic diagram of the user program of“UZAM_plc_8i8o_ex23.asm” shown inFigure 5, is depicted in Figure 6. In thisexample, the multiplexer macro“mux_4_1_E” (4×1 multiplexer with activehigh enable input) is used. In thismultiplexer, the input signals d0, d1, d2and d3 are defined to be as free runningreference timing signals T08, T09, T10 and

www.electronicsworld.co.uk ❙ 41

Figure 4: Schematic diagram for the user program UZAM_plc_8i8o_ex22.asm

Figure 6: Schematic diagram for the user program UZAM_plc_8i8o_ex23.asm

Figure 5: The user program UZAM_plc_8i8o_ex23.asm

Figure 7: The user program UZAM_plc_8i8o_ex24.asm

Page 67: PIC PLC

PLC/MCU

T11 respectively, while the output is y =Q0.0 and the select inputs s0 and s1 areI0.1 and I0.0. In addition, the activehigh enable input E is defined to be E =I0.7.

The forth example program,“UZAM_plc_8i8o_ex24.asm”, is shownin Figure 7. It shows the usage of themultiplexer macro “mux_8_1”. Theschematic diagram of the user programof “UZAM_plc_8i8o_ex24.asm” shownin Figure 7, is depicted in Figure 8. Inthis example, the multiplexer macro“mux_8_1” (8×1 multiplexer) is used. Inthis multiplexer, the input signals d0,d1, d2, d3, d4, d5, d6 and d7 aredefined to be as free running referencetiming signals T08, T09, T10, T11, T12,T13, T14 and T15 respectively, while theoutput is y = Q0.0 and the select inputss0, s1 and s2 are I0.2, I0.1 and I0.0.

The fifth and last example program,“UZAM_plc_8i8o_ex25.asm”, is shownin Figure 9. It shows the usage of themultiplexer macro “mux_8_1_E”. Theschematic diagram of the user programof “UZAM_plc_8i8o_ex24.asm” shownin Figure 9, is depicted in Figure 10. Inthis example, the multiplexer macro“mux_8_1_E” (8×1 multiplexer withactive high enable input) is used. In thismultiplexer, the input signals d0, d1, d2,d3, d4, d5, d6 and d7 are defined to beas free running reference timing signalsT08, T09, T10, T11, T12, T13, T14 andT15 respectively, while the output is y =Q0.0 and the select inputs s0, s1 and s2are I0.2, I0.1 and I0.0 respectively. Inaddition, the active high enable input Eis defined to be E = I0.7. ■

If you’ve missed any of the previousarticles in this series, you can now orderit on line atwww.electronicsworld.co.uk

Figure 8: Schematic diagram for the user program UZAM_plc_8i8o_ex24.asm

Figure 10: Schematic diagram for the user program UZAM_plc_8i8o_ex25.asm

Figure 9: The user program UZAM_plc_8i8o_ex25.asm

42 ❙ December 09 - Electronics World

Page 68: PIC PLC

PLC/MCU

www.electronicsworld.co.uk � 35

A DEMULTIPLEXER, abbreviatedas DMUX, is used when a circuit is to senda signal to one of many devices. Thisdescription sounds similar to the descriptiongiven for a decoder, but a decoder is usedto select among many devices while ademultiplexer is used to send a signalamong many devices. However, anydecoder having an enable line can functionas a demultiplexer. If the enable line of adecoder is used as a data input, then thedata can be routed to any one of theoutputs and, thus, in that case the decodercan be used as a demultiplexer.

As the name infers, a demultiplexerperforms the opposite function to that of amultiplexer. A single input signal can beconnected to any one of the output linesprovided by the choice of an appropriateselect signal. The general form of a 1-to-ndemultiplexer can be seen in Figure 1. Ifthere are “m” select inputs then thenumber of output lines to which the datacan be routed is n = 2m. Although, notshown in Figure 1, in addition to the otherinputs, the demultiplexer may have an

enable line, E, forenabling it. When thedemultiplexer isdisabled with E set to0 (for active-highenable input E), nooutput line is selectedand, therefore, theinput signal is notpassed to any outputline.

In this article, thereare six demultiplexermacros, namelyDmux_1_2 (1×2DMUX), Dmux_1_2_E

(1×2 DMUX with Enable input), Dmux_1_4(1×4 DMUX), Dmux_1_4_E (1×4 DMUX

with Enable input), Dmux_1_8 (1×8DMUX), Dmux_1_8_E (1×8 DMUX withEnable input), described for UZAM_PLC asshown in Tables 1, 2…6, respectively. Letus now consider these macros.

The macro “Dmux_1_2” is shown inTable 1, together with its symbol and truthtable. In this macro, “s0” is a Boolean inputvariable taken into the macro through“regs0,bits0” and it represents the selectinput. “y0” and “y1” are Boolean outputvariables produced as outputs through“rego0,bito0” and “rego1,bito1”respectively and they represent two outputsignals. Finally, “i” is a Boolean inputvariable produced, taken into the macrothrough “regi,biti” and it represents theinput signal. In this DMUX, when the select

Associate Professor Dr Murat Uzam from Nigde University in Turkey presents aseries of articles on a project that focuses on a microcontroller-based PLC. This is thefifteenth article explaining the demultiplexer macros of the project

PLC with PIC16F648AMicrocontroller – Part 15

Figure 1: The generalform of a 1-to-ndemultiplexer, wheren = 2m

Table 1: The macro “Dmux_1_2” togetherwith its symbol and truth table

Page 69: PIC PLC

PLC/MCU

36 � January 10 - Electronics World

input is s0 = 0, the input signal “i” ispassed to the output line “y0”. When theselect input is s0 = 1, the input signal “i” ispassed to the output line “y1”.

The macro “Dmux_1_2_E” is shown inTable 2, together with its symbol and truthtable. In addition to the “Dmux_1_2”, this

demultiplexer macro has an active-highenable line, E, for enabling it. In thismacro, E is a Boolean input variable takeninto the macro through W. When thisdemultiplexer is disabled with E set to 0,no output line is selected and the inputsignal is not passed to any output. Whenthis demultiplexer is enabled with E set to1, it functions as described for“Dmux_1_2”.

The macro “Dmux_1_4” is shown inTable 3, together with its symbol and truthtable. In this macro, “s1” and “s0” areBoolean input variables taken into themacro through “regs1,bits1” and“regs0,bits0” respectively and theyrepresent the select inputs. “y0”, “y1”,“y2” and “y3” are Boolean output variablesproduced as outputs through“rego0,bito0”, “rego1,bito1”,“rego2,bito2” and “rego3,bito3”respectively and they represent four outputsignals. Finally, “i” is a Boolean inputvariable produced, taken into the macrothrough “regi,biti” and it represents theinput signal. In this DMUX, when the selectinputs are s1s0 = 00 (respectively 01, 10,11), the input signal “i” is passed to theoutput line “y0” (respectively, y1, y2, y3).

The macro “Dmux_1_4_E” is shown inTable 4, together with its symbol and truthtable. In addition to the “Dmux_1_4”, thisdemultiplexer macro has an active-highenable line, E, for enabling it. In thismacro, E is a Boolean input variable taken

Table 2: The macro “Dmux_1_2_E”together with its symbol and truth table

Table 3: The macro “Dmux_1_4”together with its symbol and truth table

Page 70: PIC PLC

PLC/MCU

www.electronicsworld.co.uk � 37

into the macro through W. When thisdemultiplexer is disabled with E set to 0,no output line is selected and the inputsignal is not passed to any output. Whenthis demultiplexer is enabled with E set to1, it functions as described for“Dmux_1_4”.

The macro “Dmux_1_8” is shown inTable 5, together with its symbol and truthtable. In this macro, “s2”, “s1” and “s0”are Boolean input variables taken into themacro through “regs2,bits2”,

“regs1,bits1” and “regs0,bits0”respectively, and they represent the selectinputs. “y0”, “y1”, “y2”, “y3”, “y4”, “y5”,“y6” and “y7” are Boolean outputvariables produced as outputs through“rego0,bito0”, “rego1,bito1”,“rego2,bito2”, “rego3,bito3”,“rego4,bito4”, “rego5,bito5”,“rego6,bito6” and “rego7,bito7”respectively, and they represent eightoutput signals. Finally, “i” is a Booleaninput variable produced, taken into the

macro through “regi,biti” and it representsthe input signal. In this DMUX, when theselect inputs are s2s1s0 = 000 (respectively001, 010, 011, 100, 101, 110, 111), theinput signal “i” is passed to the outputline “y0” (respectively, y1, y2, y3, y4, y5, y6,y7).

The macro “Dmux_1_8_E” is shown inTable 6, together with its symbol and truthtable. In addition to the “Dmux_1_8”, thisdemultiplexer macro has an active-highenable line, E, for enabling it. In this

Table 4: The macro “Dmux_1_4_E”together with its symbol and truth table

Page 71: PIC PLC

PLC/MCU

38 � January 10 - Electronics World

Table 5: The macro “Dmux_1_8” togetherwith its symbol and truth table

Page 72: PIC PLC

PLC/MCU

www.electronicsworld.co.uk � 39

Table 6: The macro “Dmux_1_8_E”together with its symbol and truth table

macro, E is a Boolean input variable takeninto the macro through W. When thisdemultiplexer is disabled with E set to 0,no output line is selected and the inputsignal is not passed to any output. When

this demultiplexer is enabled with E set to1, it functions as described for“Dmux_1_8”.

The file “dmux_mcr_def.inc” includingthe 6 demultiplexer macros shown in

Tables 1, 2…6 can be downloaded fromhttp://host.nigde.edu.tr/muzam/. �If you’ve missed any of the previous articlesin this series, you can now order them online at www.electronicsworld.co.uk

Page 73: PIC PLC

PLC/MCU

www.electronicsworld.co.uk � 41

Figure 3: The user program UZAM_plc_8i8o_ex27.asm

Figure 1: The user program UZAM_plc_8i8o_ex26.asm

Figure 2: Schematic diagram for the user program UZAM_plc_8i8o_ex26.asm

Figure 4: Schematic diagram for the user program UZAM_plc_8i8o_ex27.asm

PLC with PIC16F648A Microcontroller

Professor Dr Murat Uzamfrom Nigde University inTurkey presents a series ofarticles on a project thatfocuses on a microcontroller-based PLC. This is thesixteenth article providingfour examples to show theuse of demultiplexer macros

Part 16

Page 74: PIC PLC

PLC/MCU

42 � February 10 - Electronics World

Figure 6: Schematic diagram for the user program UZAM_plc_8i8o_ex28.asm

Figure 5: The user program UZAM_plc_8i8o_ex28.asm

Figure 7: The user program UZAM_plc_8i8o_ex29.asm

Figure 8: Schematic diagram for the user program UZAM_plc_8i8o_ex29.asm�

Page 75: PIC PLC

PLC/MCU

www.electronicsworld.co.uk � 41

Table 2: The macro “decod_1_2_E” together with its symbol and truth table

Table 1: The macro “decod_1_2” together with its symbol and truth table

Table 3: The macro “decod_2_4” together with its symbol and truth table

PLC with PIC16F648A Microcontroller

Professor Dr MuratUzam from NigdeUniversity in Turkeypresents a series of articleson a project that focuseson a microcontroller-based PLC. This articledescribes decoder macros

Part 17

Page 76: PIC PLC

PLC/MCU

42 � March 10 - Electronics World

Table 4: The macro “decod_2_4_E” together with its symbol and truth table

Table 5: The macro “decod_3_8” together with its symbol and truth table

Page 77: PIC PLC

PLC/MCU

www.electronicsworld.co.uk � 43

Figure 1: The general form of an m-to-n decoder, where n = 2m

Table 6: The macro “decod_3_8_E” together with its symbol and truth table�

Page 78: PIC PLC

IN THIS ARTICLE, four examples areprovided to show the use of decoder macrosdescribed in the previous article. We will considerUZAM_plc_8i8o_exN.asm, N = 30, 31, 32, 33 toshow the usage of decoder macros.

In order to test the respected example pleasedownload the files fromhttp://host.nigde.edu.tr/muzam/ and then open theprogram UZAM_plc_8i8o_exN.asm, N = 30, 31, 32,33 by MPLAB IDE and compile it. After that, by usingthe PIC programmer software, take the compiled file“UZAM_PLC_8i8o_exN.hex” and with a PICprogrammer hardware send it to the programmemory of PIC16F648A microcontroller within theUZAM_PLC.

After loading the “UZAM_PLC_8i8o_exN.hex”,switch the 4PDT in “RUN” and the power switch in“ON” position, leaving it ready for test. To check thecorrectness of each program, check the informationfor each decoder macro in Tables 1, 2…6 of theprevious article.

The first example program,“UZAM_plc_8i8o_ex30.asm” is shown in Figure 1. Itshows the usage of two decoder macros“decod_1_2” and “decod_1_2_E”. The schematicdiagram of the user program of“UZAM_plc_8i8o_ex30.asm” shown in Figure 1 isshown in Figure 2.

In the first rung, the decoder macro “decod_1_2”(1×2 decoder) is used. In this decoder, the selectinput is A = I0.0, while the output lines are d0 =Q0.0 and d1 = Q0.1. In the second rung, the macro“decod_1_2_E” (1×2 decoder with active highenable input) is used. In this decoder, the selectinput is A = I0.6, while the output lines are d0 =Q0.6 and d1 = Q0.7. In addition, the active high

PLC/MCU

www.electronicsworld.co.uk � 41

Figure 2: Schematic diagram for the user program of UZAM_plc_8i8o_ex30.asm

Figure 1: The user program UZAM_plc_8i8o_ex30.asm

Figure 3: The user program UZAM_plc_8i8o_ex31.asm

PLC with PIC16F648AMicrocontroller

Professor Dr Murat Uzamfrom Nigde University in Turkeypresents a series of articles on aproject that focuses on amicrocontroller-based PLC. Thisarticle he gives examples ofdecoder macros

Part 18

Page 79: PIC PLC

PLC/MCU

42 � April 10 - Electronics World

Figure 4: Schematic diagram for the user program of UZAM_plc_8i8o_ex31.asm

Figure 5: The user program UZAM_plc_8i8o_ex32.asm

Figure 6: Schematic diagram for the user program of UZAM_plc_8i8o_ex32.asm

enable input E is defined to be E = I0.7.The second example program,

“UZAM_plc_8i8o_ex31.asm” is shown inFigure 3. It shows the usage of two decodermacros “decod_2_4” and “decod_2_4_E”.The schematic diagram of the user program of“UZAM_plc_8i8o_ex31.asm” shown in Figure3 is depicted in Figure 4.

In the first rung, the decoder macro“decod_2_4” (2×4 decoder) is used. In thisdecoder, the select inputs are A = I0.0 and B =I0.1, while the output lines are d0 = Q0.0, d1

= Q0.1, d2 = Q0.2 and d3 = Q0.3. In thesecond rung, the macro “Dmux_2_4_E” (2×4decoder with active high enable input) is used.In this decoder, the select inputs are A = I0.5and B = I0.6, while the output lines are d0 =Q0.4, d1 = Q0.5, d2 = Q0.6 and d3 = Q0.7. Inaddition, the active high enable input E isdefined to be E = I0.7.

The third example program,“UZAM_plc_8i8o_ex32.asm” is shown inFigure 5. It shows the usage of the decodermacro “decod_3_8”. The schematic diagramof the user program of“UZAM_plc_8i8o_ex32.asm” shown in Figure5 is depicted in Figure 6. In this example, thedecoder macro “decod_3_8” (3×8 decoder) isused. In this decoder, the select inputs are A =I0.0, B = I0.1 and C = I0.2, while the outputlines are d0 = Q0.0, d1 = Q0.1, d2 = Q0.2, d3

= Q0.3, d4 = Q0.4, d5 = Q0.5, d6 = Q0.6 andd7 = Q0.7.

The forth and last example program,“UZAM_plc_8i8o_ex33.asm” is shown inFigure 7. It shows the usage of the decodermacro “decod_3_8_E”. The schematic diagramof the user program of“UZAM_plc_8i8o_ex33.asm” shown in Figure7 is depicted in Figure 8. In this example, thedecoder macro “decod_3_8_E” (3×8 decoderwith active high enable input) is used. In thisdecoder, the select inputs are A = I0.0, B =I0.1 and C = I0.2, while the output lines ared0 = Q0.0, d1 = Q0.1, d2 = Q0.2, d3 = Q0.3,d4 = Q0.4, d5 = Q0.5, d6 = Q0.6 and d7 =Q0.7. In addition, the active high enable inputE is defined to be E = I0.7. �

Page 80: PIC PLC

PLC/MCU

www.electronicsworld.co.uk � 43

Figure 7: The userprogram ofUZAM_plc_8i8o_ex33.asm

Figure 8: Schematic diagramfor the user program ofUZAM_plc_8i8o_ex33.asm

Page 81: PIC PLC

HERE, THE FOLLOWING priorityencoder macros are described: encod_4_2_p(4×2 priority encoder), encod_4_2_p_E (4×2priority encoder with Enable input),encod_8_3_p (8×3 priority encoder),encod_8_3_p_E (8×3 priority encoder withEnable input), encod_dec_bcd_p (decimal toBCD [Binary Coded Decimal] priorityencoder), encod_dec_bcd_p_E (decimal toBCD priority encoder with Enable input).

Four examples will be provided in the nextarticle to show the applicability of thesepriority encoder macros.

Priority Encoder MacrosAn encoder is a circuit that changes a set

of signals into a code. As a standardcombinational component, an encoder isalmost like the inverse of a decoder where itencodes a 2n-bit input data into an n-bit

code. The encoder has m = 2n input linesand n output lines, as shown by the generalform of an m-to-n encoder in Figure 1.

For active high inputs, the operation of theencoder is such that exactly one of the inputlines should have a 1, while the remaininginput lines should have 0s. The output is thebinary value of the index of the input linethat has the 1. It is assumed that only oneinput line can be a 1.

Encoders are used to reduce the numberof bits needed to represent some given dataeither in data storage or in datatransmission. Encoders are also used in asystem with 2n input devices, each of whichmay need to request for service.

One input line is connected to one inputdevice. The input device requesting forservice will assert the input line that isconnected to it. The corresponding n-bitoutput value will indicate to the systemwhich of the 2n devices is requesting forservice. However, this only works correctly ifit is guaranteed that only one of the 2n

devices will request for service at any onetime. If two or more devices request forservice at the same time, then the outputwill be incorrect.

To resolve this problem, a priority isassigned to each of the input lines so thatwhen multiple requests are made, theencoder outputs the index value of the input

PLC/MCU

www.electronicsworld.co.uk � 39

Table 1: The macro “encod_4_2_p” together with its symbol and truth table

Figure 1: The general form of an m-to-n encoder, where m = 2n

PLC with PIC16F648AMicrocontroller

Professor Dr MuratUzam from NigdeUniversity in Turkeypresents a series of articleson a project that focuseson a microcontroller-based PLC. In this articlehe describes priorityencoder macros

Part 19

Page 82: PIC PLC

PLC/MCU

40 � May 10 - Electronics World

line with the highest priority. This modifiedencoder is known as a priority encoder. Inthis article, we discuss the priority encoders.

Although, not shown in Figure 1, thepriority encoder may have an enable line, E,for enabling it. When the priority encoder isdisabled with E set to 0 (for active-highenable input E), all the output lines will have0s (for active-high outputs). When thepriority encoder is enabled, then the outputlines issue the binary data representation ofthe highest priority input signal asserted (setto 1 for active-high).

In this article, there are six priorityencoder macros, namely encod_4_2_p (4×2priority encoder), encod_4_2_p_E (4×2priority encoder with Enable input),encod_8_3_p (8×3 priority encoder),encod_8_3_p_E (8×3 priority encoder withEnable input), encod_dec_bcd_p (decimal toBCD priority encoder), encod_dec_bcd_p_E(decimal to BCD priority encoder withEnable input), described for UZAM_PLC asshown in Tables 1, 2…6, respectively. Letus now consider these macros.

The 4×2 priority encoder macro“encod_4_2_p” is shown in Table 1,together with its symbol and truth table. Inthis priority encoder, there are four inputlines, namely 3, 2, 1 and 0, represented byBoolean variables “reg3,bit3”, “reg2,bit2”,“reg1,bit1” and “reg0,bit0” respectively.

Input line 3 has the highest priority, whilethe input line 0 has the lowest. The twooutput lines are A1 (Most Significant Bit –MSB) and A0 (Least Significant Bit – LSB),represented by Boolean variables“regA1,bitA1” and “regA0,bitA0”respectively. How the macro“encod_4_2_p” works is shown in the truthtable. It can be seen that the output binarycode is generated based on the highestpriority input signal present in the fourinput lines. For example, when the signalpresent in the input line 3 is 1, the outputlines generate the following binary codeA1A0 = 11 for this input signal, regardlessof the signals present in other input lines.

The 4×2 priority encoder with Enable

Table 2: The macro “encod_4_2_p_E” together with its symbol and truth table

Table 3: The macro “encod_8_3_p” together with its symbol and truth table

Page 83: PIC PLC

PLC/MCU

www.electronicsworld.co.uk � 41

input macro “encod_4_2_p_E” is shown inTable 2, together with its symbol and thetruth table. In addition to the“encod_4_2_p”, this priority encoder macrohas an active-high enable line, E, for enablingit. In this macro, E is a Boolean input variabletaken into the macro through W. When thispriority encoder is disabled with E set to 0,all the output lines will have 0s (for active-high outputs). When this priority encoder isenabled with E set to 1, it functions asdescribed for “encod_4_2_p”.

The 8×3 priority encoder macro“encod_8_3_p” is shown in Table 3,together with its symbol and truth table. Inthis priority encoder, there are eight inputlines, namely 7, 6…0, represented byBoolean variables “reg7,bit7”, “reg6,bit6”,“reg5,bit5”, “reg4,bit4”, “reg3,bit3”,“reg2,bit2”, “reg1,bit1” and “reg0,bit0”respectively.

Input line 7 has the highest priority, while

the input line 0 has the lowest priority. Thethree output lines are A2 (MSB), A1 and A0

(LSB), represented by Boolean variables“regA2,bitA2”, “regA1,bitA1” and“regA0,bitA0” respectively. How the macro“encod_8_3_p” works is shown in the truthtable. It can be seen that the output binarycode is generated based on the highestpriority input signal present in the eight inputlines. For example, when the signal presentin the input line 7 is 1, the output linesgenerate the following binary code A2A1A0 =111 for this input signal, regardless of thesignals present in other input lines.

The 8×3 priority encoder with Enable inputmacro “encod_8_3_p_E” is shown in Table4, together with its symbol and truth table.In addition to the “encod_8_3_p”, thispriority encoder macro has an active-highenable line, E, for enabling it. In this macro,E is a Boolean input variable taken into themacro through W. When this priority

encoder is disabled with E set to 0, all theoutput lines will have 0s (for active-highoutputs). When this priority encoder isenabled with E set to 1, it functions asdescribed for “encod_8_3_p”.

The decimal to BCD priority encoder macro“encod_dec_bcd_p” is shown in Table 5,together with its symbol and truth table. Inthis priority encoder, there are ten inputlines, namely 9, 8…0, represented byBoolean variables “reg9,bit9”, “reg8,bit8”,“reg7,bit7”, “reg6,bit6”, “reg5,bit5”,“reg4,bit4”, “reg3,bit3”, “reg2,bit2”,“reg1,bit1” and “reg0,bit0” respectively.

Input line 9 has the highest priority, whilethe input line 0 has the lowest priority. Thefour output lines are A3 (MSB), A2, A1 and A0

(LSB), represented by Boolean variables“regA3,bitA3”, “regA2,bitA2”,“regA1,bitA1” and “regA0,bitA0”respectively. How the macro“encod_dec_bcd_p” works is shown in thetruth table. It can be seen that the outputbinary code is generated based on the highestpriority input signal present in the ten inputlines. For example when the signal present inthe input line 9 is 1, the output lines generatethe following binary code A3A2A1A0 = 1001for this input signal, regardless of the signalspresent in other input lines.

The decimal to BCD priority encoder withEnable input macro “encod_dec_bcd_p_E” isshown in Table 6, together with its symboland truth table. In addition to the“encod_dec_bcd_p”, this priority encodermacro has an active-high enable line, E, forenabling it. In this macro, E is a Booleaninput variable taken into the macro throughW. When this priority encoder is disabledwith E set to 0, all the output lines will have0s (for active-high outputs). When thispriority encoder is enabled with E set to 1, itfunctions as described for“encod_dec_bcd_p”.

The file “p_enc_mcr_def.inc”, includingthe 6 priority encoder macros shown inTables 1, 2…6 can be downloaded fromhttp://host.nigde.edu.tr/muzam/. �

Tables 5 and 6 are shown on the next page

Table 4: The macro “encod_8_3_p_E” together with its symbol and truth table

Page 84: PIC PLC

PLC/MCU

42 � May 10 - Electronics World

Table 5: The macro “encod_dec_bcd_p” together with its symbol and truth table

Page 85: PIC PLC

PLC/MCU

www.electronicsworld.co.uk � 43

Table 6: The macro “encod_dec_bcd_p_E” together with its symbol and truth table

Page 86: PIC PLC

IN THIS SECTION, we will considerfour examples – UZAM_plc_8i8o_exN.asm, N= 34, 35, 36, 37 – to show the usage ofpriority encoder macros.

In order to test these examples you candownload the files fromhttp://host.nigde.edu.tr/muzam/ and then usethe program UZAM_plc_8i8o_exN.asm, N =34, 35, 36, 37 by MPLAB IDE and compile it.Following that, by using the PIC programmersoftware, take the compiled file“UZAM_PLC_8i8o_exN.hex” and with PICprogrammer hardware send it to the programmemory of PIC16F648A microcontrollerwithin the UZAM_PLC. After loading the

“UZAM_PLC_8i8o_ exN.hex”, switch the4PDT in “RUN” and the power switch in the“ON” position.

To check the correctness of each program,you are referred to the related informationfor each priority encoder macro provided inTables 1, 2, 3, 4 of the previous article. Notethat in the current set-up of UZAM_PLC, with8 inputs and 8 outputs, we are not able to

test the priority encoder macros“encod_dec_bcd_p” and“encod_dec_bcd_p_E”, which require 10 and11 inputs respectively. However, if you usethe extension board together with theUZAM_PLC main board then you can set upan example for these two priority encodermacros.

The first example program,“UZAM_plc_8i8o_ex34.asm”, is shown inFigure 1. It shows the usage of the 4×2priority encoder macro “encod_4_2_p”. Theschematic diagram is depicted in Figure 2. Inthis priority encoder, four input lines, 3, 2, 1and 0 are defined as I0.0, I0.1, I0.2 and I0.3respectively, while the output lines A1 andA0 are defined as Q0.0 and Q0.1.

The second example program“UZAM_plc_8i8o_ex35.asm” is shown inFigure 3. It shows the usage of the 4×2priority encoder with Enable input macro

Figure 3: The user program UZAM_plc_8i8o_ex35.asm

Figure 1: The user program UZAM_plc_8i8o_ex34.asm

Figure 2: Schematic diagram for the user program UZAM_plc_8i8o_ex34.asm

PLC with PIC16F648AMicrocontroller

Professor Dr MuratUzam from Nigde

University in Turkeypresents a series of

articles on a project thatfocuses on a

microcontroller-basedPLC. In this article fourexamples are provided

to show the use ofpriority encoder macros

described in theprevious parts

Part 20

PLC/MCU

38 � June 10 - Electronics World

Page 87: PIC PLC

PLC/MCU

www.electronicsworld.co.uk � 39

CONGRATULATIONSto the following winners of

the reader offer competitionthat run in the January issue of

Electronics World magazine.

Each winner receives the Si1120 Slider BoardDemo Kit from SILICON LABS:

1. PIETRO CREMONINI, Italy2. WOJCIECH STODULY, Poland3. CLAIRE ANDREWS, UK4. EMILIO BALDI, Australia5. ABDULNASSER NOFAL6. ERMANNO BERNASCONI, Switzerland7. ANDREW LUTLEY, UK8. PIERPAOLO PIEROZZI, Italy9. ROBERT ALBEE, USA10. YU KWONG YIU, Hong Kong

WINNERS!

WINNERS!

WINNERS!

TRANSFORMER MANUFACTURE

Automatic Windings Ltd

Unit 40 Woolsbridge Industrial Estate,

Three Legged Cross, Wimborne,

Dorset, BH21 6SZ

Tel: 01202 814532

Fax: 01202814533

Email: [email protected]

Web: www.automatic-windings.co.uk

Page 88: PIC PLC

“encod_4_2_p_E”. The schematic diagram isshown in Figure 4. In this priority encoder,four input lines, 3, 2, 1 and 0, are defined asI0.0, I0.1, I0.2 and I0.3, while the output linesA1 and A0 are defined as Q0.0 and Q0.1. Inaddition, the active high enable input E isdefined to be E = I0.7.

The third example program“UZAM_plc_8i8o_ex36.asm” is shown inFigure 5. It shows the usage of the 8×3priority encoder macro “encod_8_3_p”. Itsschematic diagram is depicted in Figure 6. Inthis priority encoder, eight input lines, 7, 6, 5,4, 3, 2, 1 and 0, are defined as I0.0, I0.1,I0.2, I0.3, I0.4, I0.5, I0.6 and I0.7, while theoutput lines A2, A1 and A0 are defined asQ0.0, Q0.1 and Q0.2.

The forth and last example program,“UZAM_plc_8i8o_ex37.asm” is shown inFigure 7. It shows the usage of the 8×3

priority encoder with Enable input macro“encod_8_3_p_E”. The schematic diagram isdepicted in Figure 8. In this priority encoder,eight input lines, 7, 6, 5, 4, 3, 2, 1 and 0, aredefined as I0.0, I0.1, I0.2, I0.3, I0.4, I0.5, I0.6and I0.7, while the output lines A2, A1 andA0 are defined as Q0.0, Q0.1 and Q0.2. Inaddition, the active high enable input E isdefined to be E = T14, the free runningreference timing signal with T = 8388.608ms.This means that this priority encoder will beenabled for ½T = 4194.304ms and will bedisabled for the next 4194.304ms and thisprocess will continue. �

Figure 4: Schematic diagram for the user program UZAM_plc_8i8o_ex35.asm

Figure 5: The user program of UZAM_plc_8i8o_ex36.asm

Figure 6: Schematic diagram for the userprogram UZAM_plc_8i8o_ex36.asm

Figure 8: Schematic diagram for the userprogram UZAM_plc_8i8o_ex37.asm

Figure 7: The user program UZAM_plc_8i8o_ex37.asm

PLC/MCU

40 � June 10 - Electronics World

Page 89: PIC PLC

40 � July 10 - Electronics World

Figure 1 shows the remotely controlled modelgate system, used in this article as an exampleto show how UZAM_PLC can be utilized in thecontrol of real systems. In this system, whenthe DC motor turns backwards (or forwards)the gate is opened (or closed). To control theDC motor in backwards and forwardsdirections, the UZAM_PLC outputs Q0.0 and

Q0.1 are used respectively. In the system there are two buttons, B0 and

B1, and they both have only one normally open(NO) contact. When pressed, button B0 (or B1) isused to give the control system the followingorder: “open the gate” (or “close the gate”).UZAM_PLC inputs I0.0 and I0.1 are used foridentifying the “on” or “off” states of the

buttons B0 and B1.When the gate iscompletely open, itapplies the F1 force,shown in Figure 1,to the limit switch 1(LS1). In this case,the NO contact ofLS1 is closed.

To detect whetheror not the gate iscompletely open, theUZAM_PLC inputI0.2 is utilized. Whenthe gate iscompletely closed, itapplies the F2 force,shown in Figure 1,on to the limitswitch 2 (LS2). In this

case, the NO contact of LS2 is closed. To detectwhether or not the gate is completely closed, theUZAM_PLC input I0.3 is utilized. An infrared (IR)transmitter/receiver sensor is used to detect ifthere is any obstacle in the gate’s path. This isvery important because when the gate is closingthere shouldn’t be any obstacle in its path inorder not to cause any damage to anybody oranything. When the light emitted from the IRtransmitter is received from the IR receiver, theNO contact of the sensor in closed. In this case,we conclude that there is no obstacle in thepath.

When the light emitted from the IR transmitteris not received from the IR receiver, the NOcontact of the sensor is open, i.e. in its normalcondition. This means that there is an obstacle inthe path. To detect whether or not there is anobstacle in the path, the UZAM_PLC input I0.4 isutilized. In addition, there is also an RF (RadioFrequency) transmitter/receiver used as a remotecontrol mechanism within the system. In the RFtransmitter there is a button. When this button ispressed, the RF waves are emitted from thetransmitter and they are received from the RFreceiver. In this case, NO contact at the RFreceiver is closed, signalling the button pressfrom the RF transmitter counterpart. To detect

Figure 1: The remotely controlled model gate system

PLC with PIC16F648AMicrocontroller

Professor Dr MuratUzam from Nigde

University in Turkeypresents a series of

articles on a project thatfocuses on a

microcontroller-basedPLC. This article describesan example of remotely-

controlled model gatesystem and declares sevendifferent control scenarios

to be carried out

Part 21

PLC/MCU

Figure 2: The DC motor control circuit embeddedwithin the model gate system

Page 90: PIC PLC

www.electronicsworld.co.uk � 41

whether or not the RF transmitter button ispressed, the UZAM_PLC input I0.5 is utilized.

The DC motor control circuit embedded withinthe model gate system is depicted in Figure 2,where there are two relays, Relay 1 and Relay 2,operating at 24V DC. Both of them have anSPDT (Single Pole, Double Throw) contact, withthe terminals named NO (Normally Open), C(Common) and NC (Normally Closed). Terminal Cis shared between the other two contacts.

The normal states of the contacts are shown inFigure 2. In this case, the C and NC terminals ofboth relays are “closed”, while C and NOterminals are “open”. If any of these relays’ coilsis energized, the contacts are actuated and, assuch, the C and NC terminals of the relay are“open”, while the C and NO terminals are“closed”.

With this set-up, by means of the two relays,we can have the DC motor turning forwards orbackwards as shown in Table 1. It is importantto note that if both relays are ON, then the DCmotor will not be working. One terminal of eachrelay coil is connected to 24V DC, while the otherone is left unconnected.

To operate any relay it is necessary to connectits open terminal to the ground of the 24V DC.The control of the DC motor is achieved bymeans of the Q0.0 and Q0.1 outputs of theUZAM_PLC. As can be seen from Figure 3,when Q0.0 is ON (and Q0.1 is OFF), the NOcontact of Q0.0 will switch on Relay 2, in whichcase the motor turns backwards and the gate isopened. Similarly, when Q0.1 is ON (and Q0.0 isOFF), the NO contact of Q0.1 will switch on Relay1, in which case the motor turns forwards andthe gate is closed.

Figure 3 shows the wiring of the UZAM_PLCwith the remotely controlled model gate system.In this set-up, when any of the NO contacts ofthe model gate system are closed or a button ispressed, 5V DC is applied to related UZAM_PLCinput.

Control Scenarios for the Model GateSystem

In this section we will declare seven differentcontrol scenarios for the remotely controlledmodel gate system as follows:1. When B0 is being pressed, the gate will open.2. Once B0 is pressed, the gate will open.3. Once B0 is pressed, the gate will open. The

motor will stop when the gate is completelyopen.

4. Once B0 is pressed, the gate will open. Themotor will stop when the gate is completelyopen. Once B1 is pressed, the gate will close.

The motor will stop when the gate iscompletely closed.

5. If the gate is not closing, then once B0 ispressed, the gate will open. The motor willstop when the gate is completely open. If thegate is not opening, then once B1 is pressed,the gate will close. The motor will stop whenthe gate is completely closed.

6. If the gate is not closing, then once B0 or RFtransmitter button is pressed, the gate willopen. The motor will stop when the gate iscompletely open. When the gate is completelyopen, it will wait five seconds beforeautomatically closing. The motor will stopwhen the gate is completely closed.

7. If the gate is not closing, then once B0 or theRF transmitter button is pressed, the gate willopen. The motor will stop when the gate iscompletely open. When the gate is completelyopen, it will wait five seconds beforeautomatically closing. The motor will stopwhen the gate is completely closed. When thegate is closing, if there is an obstacle in thegate’s path, the gate will open. In this case itwill wait five seconds before automaticallyclosing as defined above. �

If you missed any of the previous articles in thisseries you can now order them by going on lineat www.electronicsworld.co.uk

Figure 3: Wiring of UZAM_PLC with the model gate system

Table 1: The state of the DC motor based on two relays

Relay 1 Relay 2 DC motor

OFF(Q0.1=0) OFF(Q0.0=0) OFF (not working)

OFF(Q0.1=0) ON (Q0.0=1) Turns backwards (the gate is opened)

ON (Q0.1=1) OFF(Q0.0=0) Turns forwards (the gate is closed)

ON (Q0.1=1) ON (Q0.0=1) OFF (not working)

Page 91: PIC PLC

IN THIS SECTION, we will explain thesolutions to the seven control scenariosdescribed in the previous article for the remotelycontrolled model gate system, namelyUZAM_plc_8i8o_exN.asm, N = 38, 39…44.

In order to test the example, you candownload the files from http://host.nigde.edu.tr/muzam/ and then open the UZAM_plc_8i8o_exN.asm, N = 38, 39…44 program by MPLABIDE and compile it. After that by using the PICprogrammer software, take the compiled file“UZAM_PLC_8i8o_ exN.hex” and with your PICprogrammer hardware send it to the programmemory of PIC16F648A microcontroller withinthe UZAM_PLC. After loading the “UZAM_PLC_8i8o_exN.hex”, switch the 4PDT in “RUN” andthe power switch in “ON” position. Finally, theprogram is ready to run.

The ladder diagram for the first scenario isshown in Figure 1 and its UZAM_PLCrepresentation, the program “UZAM_plc_8i8o_ex38.asm”, is shown in Figure 2. In thisexample, when B0 (I0.0) is being pressed, thegate will open (Q0.0 will be ON). However, inthis case if B0 is released then the gate will stop.This means that the program does not

remember whether or not the B0 was pressed. The ladder diagram for the second scenario is

shown in Figure 3 and its UZAM_PLCrepresentation, the program “UZAM_plc_8i8o_ex39.asm”, is shown in Figure 4. In thisexample, once B0 (I0.0) is pressed, with the helpof NO contact Q0.0 that is connected in parallelto the NO contact I0.0, the gate will open (Q0.0will be ON). Here, the NO contact Q0.0 is a“sealing contact”, which helps the program toremember whether B0 was pressed. Theproblem here is that when the gate iscompletely opened, the motor will not stop.

The ladder diagram for the third scenario isshown in Figure 5 and its UZAM_PLCrepresentation, the program“UZAM_plc_8i8o_ex40.asm”, is shown inFigure 6. In this example, once B0 (I0.0) ispressed, with the help of NO contact Q0.0connected in parallel to the NO contact I0.0, thegate will open (Q0.0 will be ON). Here, whenthe gate is opened completely, the motor willstop with the help of NC contact of I0.2 insertedbefore the output Q0.0.

The ladder diagram for the fourth scenario isshown in Figure 7 and its UZAM_PLCrepresentation, the program “UZAM_plc_8i8o_ex41.asm”, is shown in Figure 8. In thisexample, once B0 (I0.0) is pressed, with the helpof NO contact Q0.0 connected in parallel to the

NO contact I0.0, the gate will open (Q0.0 will beON). Here, when the gate is opened completely,the motor will stop with the help of NC contactof I0.2 inserted before the output Q0.0.

Similarly, once B1 (I0.1) is pressed, with thehelp of NO contact of Q0.1 connected in parallelto the NO contact I0.1, the gate will close (Q0.1will be ON). Here, when the gate is closedcompletely, the motor will stop with the help ofNC contact of I0.3 inserted before the outputQ0.1. The problem with this example is that ifboth B0 and B1 are pressed at the same time,then both outputs will be ON. This is not adesired situation. The solution to this problem isgiven in the next example.

The ladder diagram for the fifth scenario isshown in Figure 9 and its UZAM_PLCrepresentation, the user program“UZAM_plc_8i8o_ex42.asm”, is shown inFigure 10. In this example, if the gate is notclosing (Q0.1=0) once B0 (I0.0) is pressed, thenthe gate will open (Q0.0 will be ON) with thehelp of NO contact of Q0.0 connected in parallelto the NO contact I0.0. In this case, when thegate is opened completely (I0.2=1 and thereforeNC contact of I0.2 will open), the motor willstop with the help of NC contact of I0.2 insertedbefore the output Q0.0.

Similarly, if the gate is not opening (Q0.0=0)once B1 (I0.1) is pressed, then the gate will close

Figure 2: The user program UZAM_plc_8i8o_ex38.asm

Figure 1: Ladder diagram for the user programUZAM_plc_8i8o_ex38.asm

PLC with PIC16F648AMicrocontrollerProfessor Dr MuratUzam from NigdeUniversity in Turkeypresents a series of articleson a project that focuseson a microcontroller-based PLC. This article isthe last in the series and itexplains seven solutionsfor the seven controlscenarios for a remotely-controlled model gatesystem described in thelast issue

Part 22

PLC/MCU

40 � August 10 - Electronics World

Page 92: PIC PLC

PLC/MCU

www.electronicsworld.co.uk � 41

(Q0.1 will be ON) with the help of NO contactQ0.1 connected in parallel to the NO contact ofI0.1. Here, when the gate is closed completely(I0.3=1 and therefore NC contact of I0.3 willopen), the motor will stop with the help of NCcontact of I0.3 inserted before the output Q0.1.Therefore, once the gate is being opened we cannot force it to close, and vice versa.

The ladder diagram for the sixth scenario isshown in Figure 11 with its UZAM_PLCrepresentation, the user program“UZAM_plc_8i8o_ex43.asm” in Figure 12. In thisexample, if the gate is not closing (Q0.1=0) onceB0 (I0.0) or RF transmitter button (I0.5) is pressed,then the gate will open (Q0.0 will be ON) withthe help of NO contact of Q0.0 connected inparallel to the NO contact of I0.0. In this case,when the gate is opened completely (I0.2=1 andtherefore NC contact of I0.2 will open), the motorwill stop with the help of NC contact of I0.2inserted before the output Q0.0. When the gateis completely open (I0.2=1), an on delay timer(TON_8) is used to obtain (10×524.288ms) 5.24seconds time delay.

After waiting 5.24 seconds, the status bitTON_8Q0 of the on delay timer becomes true. Ifthe gate is not opening (Q0.0=0) and if the NOcontact of TON_8Q0 is closed (i.e. 5.24 secondstime delay has elapsed), then the gate will close(Q0.1 will be ON) with the help of NO contactof Q0.1 connected in parallel to the NO contactof TON_8Q0. Here, when the gate is closedcompletely (I0.3=1 and therefore NC contact ofI0.3 will open), the motor will stop with thehelp of NC contact of I0.3 inserted before theoutput Q0.1.

The ladder diagram for the seventh and lastscenario is shown in Figure 13a. The first rungcannot be implemented as it is in UZAM_PLC.Therefore, the ladder diagram shown in Figure13a is modified. The UZAM_PLC implementationof this ladder diagram is shown in Figure 13b,and is provided as the user program “UZAM_plc_8i8o_ex44.asm” as shown in Figure 14.

In this example, if the gate is not closing(Q0.1=0) once B0 (I0.0) or RF transmitter button(I0.5) is pressed, then the gate will open (Q0.0will be ON) with the help of NO contact Q0.0connected in parallel to the NO contact I0.0. Inthis case, when the gate is opened completely(I0.2=1 and therefore NC contact of I0.2 willopen), the motor will stop with the help of NCcontact of I0.2 inserted before the output Q0.0.

If the gate is closing (Q0.1=1) and thepresence of an obstacle is detected in the gates’path (I0.4=0), then the gate will open (Q0.0 willbe ON). When the gate is completely open(I0.2=1), an on delay timer (TON_8) is used to

Figure 3: Ladder diagram for the user program UZAM_plc_8i8o_ex39.asm

Figure 4: The user program UZAM_plc_8i8o_ex39.asm

Figure 5: Ladder diagram for the user program UZAM_plc_8i8o_ex40.asm

Figure 6: The user program UZAM_plc_8i8o_ex40.asm

Figure 7: Ladder diagram for the user program UZAM_plc_8i8o_ex41.asm

Figure 8: The user program UZAM_plc_8i8o_ex41.asm

Page 93: PIC PLC

42 � August 10 - Electronics World

obtain (10×524.288ms) 5.24 seconds time delay.After waiting 5.24 seconds, the status bitTON_8Q0 of the on delay timer becomes true.

If the gate is not opening (Q0.0=0) and if theNO contact of TON_8Q0 is closed (i.e. 5.24seconds time delay has elapsed), then the gatewill close (Q0.1 will be ON) with the help of NOcontact Q0.1 connected in parallel to the NO

contact of TON_8Q0. Here, when the gate isclosed completely (I0.3=1 and therefore NCcontact of I0.3 will open), the motor will stopwith the help of NC contact of I0.3 insertedbefore the output Q0.1. If the gate is closing(Q0.1=1) and the presence of an obstacle isdetected in the gate’s path (I0.4=0), then theoutput Q0.1 will be switched OFF by means of

the NO contact of I0.4 inserted before theoutput Q0.1. �

This is the last article in the series of the “PLCwith PIC16F648A Microcontroller” project. If youmissed any of the previous articles, you canorder them on line atwww.electronicsworld.co.uk

Figure 9: Ladder diagram for the userprogram UZAM_plc_8i8o_ex42.asm

Figure 11: Ladder diagram for the userprogram UZAM_plc_8i8o_ex43.asm

Figure 14: The user programUZAM_plc_8i8o_ex44.asm

Figure 10: The user program UZAM_plc_8i8o_ex42.asm

Figure 12: The user program UZAM_plc_8i8o_ex43.asm

Figure 13a (left) and (b) right: Ladder diagrams forthe user program UZAM_plc_8i8o_ex44.asm

PLC/MCU