This document introduces ladder logic programming for PIC microcontrollers. It discusses how ladder logic is commonly used with programmable logic controllers (PLCs) due to its intuitive representation of electrical circuits using rungs and contacts. The document outlines how ladder logic can also be used with PIC microcontrollers and describes obtaining the necessary free software. It provides a high-level overview of creating and running ladder logic programs, including reading inputs, performing logic, and controlling outputs in a repeating scan cycle.
Automation could be achieved with the aid of Industrial Controller PLC. PLC basic Programming are discussed in this presentation.Case studies are available and solutions for those questions will be updated in next presentation.
Mini cement plant using plc published in national conference on materials, de...Sushil Kundu
This project analyses the simulation strategic considerations of PLC based mini cement plant system by developing ladder diagrams using the addressing modes of Allen Bradley PLC. This project presents comprehensive simulations of the performance of the different electrical actuators such as stepper motor, solenoid valve etc., the position sensor and the conveyer belt. Program execution status can also be monitored by the PLC. It scans memory, inputs and outputs in a deterministic manner. The user can access the logic, counting and memory functions easily by using this adopted simulation strategy with good performance and more reliability.
The design is for the production of large volume high quality dry powdered cement with PLC used as its controller, which implements ladder diagram logic to monitor the output signals from the different input sensors.
The document provides an introduction to programmable logic controllers (PLCs). It discusses how PLCs replaced electromechanical relays for control systems, allowing logic functions to be programmed rather than physically wired. The summary describes how PLCs work, including taking input from sensors and switches and outputting signals to devices. It also discusses how PLCs are programmed using ladder logic and can be reprogrammed to change control functions without rewiring. The document provides examples of programming PLCs to control lights and motors.
1. The document describes a project to control the speed of an induction motor by setting the maximum speed in a Siemens TD-200 operator panel.
2. An S7-200 PLC is used along with analog output and operator panel modules to control a SUNFAR inverter and induction motor.
3. The maximum motor speed is set in register VW100 from the operator panel user menu, and the current speed is set in VW0. Speed increase is denied if the current speed reaches the maximum.
Prior to programmable logic controllers, timing functions in industrial automation were implemented using various mechanical and electromechanical timers. Programmable logic controllers allowed timing functions to be programmed digitally, eliminating the need for external timers. A PLC timing instruction counts intervals of a selectable time base and uses bits to indicate when timing conditions are met. Standard timing functions like on delay, off delay, interval, retentive and symmetrical/asymmetrical recycle can be created using combinations of timing instructions, and cascading timers allows complex sequences.
This document discusses jump instructions in PLC ladder logic. Jump instructions allow a PLC program to break its normal sequential execution and move to another part of the program. The key points covered are:
- Jump instructions work with label instructions to redirect program flow. The jump instruction moves execution to the rung with a matching label number.
- Jumps can move execution forward or backward within a program. Multiple jumps can target the same label. Jumps can also be nested within other jumps.
- Advantages of jumps include allowing a PLC to run multiple programs, jumping sections during faults to reduce downtime, and improving scan time performance.
- An example is provided demonstrating a parking lot control system
This document provides instructions for maintaining a record book and following lab procedures for an advanced instrumentation lab at Vellore Institute of Technology. It outlines how to properly document experiments by including the date, experiment name and number, aim, circuit tables, diagrams, and getting staff certification. Safety instructions are provided, such as handling equipment carefully and not leaving the lab without permission. Finally, it lists 15 experiments to be completed, including implementing logic gates, timers, counters and process controls using a PLC.
Automation could be achieved with the aid of Industrial Controller PLC. PLC basic Programming are discussed in this presentation.Case studies are available and solutions for those questions will be updated in next presentation.
Mini cement plant using plc published in national conference on materials, de...Sushil Kundu
This project analyses the simulation strategic considerations of PLC based mini cement plant system by developing ladder diagrams using the addressing modes of Allen Bradley PLC. This project presents comprehensive simulations of the performance of the different electrical actuators such as stepper motor, solenoid valve etc., the position sensor and the conveyer belt. Program execution status can also be monitored by the PLC. It scans memory, inputs and outputs in a deterministic manner. The user can access the logic, counting and memory functions easily by using this adopted simulation strategy with good performance and more reliability.
The design is for the production of large volume high quality dry powdered cement with PLC used as its controller, which implements ladder diagram logic to monitor the output signals from the different input sensors.
The document provides an introduction to programmable logic controllers (PLCs). It discusses how PLCs replaced electromechanical relays for control systems, allowing logic functions to be programmed rather than physically wired. The summary describes how PLCs work, including taking input from sensors and switches and outputting signals to devices. It also discusses how PLCs are programmed using ladder logic and can be reprogrammed to change control functions without rewiring. The document provides examples of programming PLCs to control lights and motors.
1. The document describes a project to control the speed of an induction motor by setting the maximum speed in a Siemens TD-200 operator panel.
2. An S7-200 PLC is used along with analog output and operator panel modules to control a SUNFAR inverter and induction motor.
3. The maximum motor speed is set in register VW100 from the operator panel user menu, and the current speed is set in VW0. Speed increase is denied if the current speed reaches the maximum.
Prior to programmable logic controllers, timing functions in industrial automation were implemented using various mechanical and electromechanical timers. Programmable logic controllers allowed timing functions to be programmed digitally, eliminating the need for external timers. A PLC timing instruction counts intervals of a selectable time base and uses bits to indicate when timing conditions are met. Standard timing functions like on delay, off delay, interval, retentive and symmetrical/asymmetrical recycle can be created using combinations of timing instructions, and cascading timers allows complex sequences.
This document discusses jump instructions in PLC ladder logic. Jump instructions allow a PLC program to break its normal sequential execution and move to another part of the program. The key points covered are:
- Jump instructions work with label instructions to redirect program flow. The jump instruction moves execution to the rung with a matching label number.
- Jumps can move execution forward or backward within a program. Multiple jumps can target the same label. Jumps can also be nested within other jumps.
- Advantages of jumps include allowing a PLC to run multiple programs, jumping sections during faults to reduce downtime, and improving scan time performance.
- An example is provided demonstrating a parking lot control system
This document provides instructions for maintaining a record book and following lab procedures for an advanced instrumentation lab at Vellore Institute of Technology. It outlines how to properly document experiments by including the date, experiment name and number, aim, circuit tables, diagrams, and getting staff certification. Safety instructions are provided, such as handling equipment carefully and not leaving the lab without permission. Finally, it lists 15 experiments to be completed, including implementing logic gates, timers, counters and process controls using a PLC.
The document describes a traffic light control system using Programmable Logic Controllers (PLCs). The system uses three PLCs - a master PLC that controls two slave PLCs. The master PLC sends commands to control the light patterns at an intersection. The slave PLCs control the lights for cars and pedestrians. The system was prototyped using a PCB, 3D printed traffic lights, and packaging to test the logic implemented on the PLCs.
The document provides an overview of programmable logic controllers (PLCs). It defines PLCs as digital electronic devices that use programmable memory to implement logic functions like sequencing and timing to control machines and processes. The document discusses the basic structure of PLCs including the CPU, memory, input/output interfaces, and power supply. It also covers programming methods like ladder logic and instruction lists. Additional topics include input/output addressing, timers, counters, and techniques like latching, internal relays, and sequencing using timers.
This document describes experiments conducted using a programmable logic controller (PLC) to control various functions. The experiments include: 1) using a PLC to start and stop a motor via push buttons, 2) adding reverse direction control, 3) using timers to add on/off delays, and 4) combining on/off delays. The purpose is to understand and implement ladder logic programming of a PLC. Key components of a PLC like the power supply, processor, input and output modules are discussed. Ladder logic programming allows flexible control of industrial machinery.
This document provides information about programming and testing PLC programs. It discusses the hardware and software needed to program a PLC, including the PLC itself, a programming device like a PC, programming software, and a connector cable. It also describes how to test a program by downloading it from the PC to the PLC CPU and using an input simulator to simulate field inputs and observe the resulting outputs. The document includes examples of ladder logic programs using inputs, outputs, AND and OR logic, and timers to control gates at a parking lot entrance and exit.
Basic plc-programming-e book_Reliance High Tech LtdMarsus Marsus
This document provides an overview of basic PLC programming. It covers the introduction and history of PLCs, their basic design and components, programming methods, common programming languages, and examples of specific PLC models and their programming. The key points covered are:
- PLCs were developed in the 1960s as programmable replacements for relay-based control systems.
- A basic PLC has a CPU, memory, I/O modules, and a programming interface. Larger PLCs can have distributed architectures.
- PLC programming standards like IEC 61131 define common languages like ladder logic, function block diagrams, and structured text.
- Programming allows the control logic to be
PLC BASED AUTOMATED SYSTEM IN PROCESS INDUSTRY (Final Presentation)Shahid Faizee
This document describes a thesis project on implementing an automated PLC-based control system in a cement plant. The project involves developing motor block and group control block logic in Siemens Step 7 software to control crushers via a Siemens PLC and Expert Control System SCADA. Methodology includes defining inputs and outputs for motor and group blocks, designing submodules for start/stop, inputs, and outputs, and combining submodules into faceplates. The automated system is intended to reduce labor costs and improve performance by remotely monitoring and controlling plant operations.
This document discusses different types and programming of timers in PLC systems. It describes common approaches to modeling timers as relays or delay blocks. There are different types of timers including on-delay, off-delay, and pulse timers. Programming of timers varies between PLC manufacturers, with some treating timers as coils and others as delays. Examples are provided for sequencing motors using timers, cascading timers, producing an on-off cycle, and flashing a light using timers.
Automatic Bottle filling system and remote monitoring throughDHRUVIT KHARADI
This document describes an automatic bottle filling system that uses a programmable logic controller (PLC) and remote monitoring via a supervisory control and data acquisition (SCADA) system. The system includes a conveyor belt for bottle transport, a load cell for weight measurements, solenoid valves to control fluid flow, and a relay device to supply appropriate voltages to motors and pumps. Students developed PLC programming to control the system timers and incorporate the load cell measurements. They also configured communication between the PLC and computer software. The system is designed to automatically fill bottles with high accuracy.
The document introduces ladder diagrams and their basic components and logic. Ladder diagrams are a graphical programming language used to program programmable logic controllers (PLCs). Each rung represents a program statement with inputs on the left and outputs on the right. The PLC executes the ladder diagram by reading input states and determining output states from top to bottom. The document also describes common logic components like contacts, coils, timers, and counters used in ladder diagrams.
This document describes the design of a PLC-based smart lifting system using pneumatic components. The system uses a PLC as the main controller along with pneumatic actuators powered by an air compressor. It is configured to pick up and place objects at specified heights according to the object's detected height. The design includes modules for feeding, height detection, and robotic arm functions. Ladder logic programming was used to program the PLC and provide real-time monitoring of the system. The implemented design was demonstrated and shown to successfully detect object heights and control the lifting and placing of objects through three degrees of freedom.
The document discusses the basics of programmable logic controller (PLC) programming including PLC architecture, memory organization, programming languages, ladder logic instructions, addressing schemes, and programming techniques. Specifically, it covers the processor memory being divided into program and data memory, the ladder logic programming language using relay-type instructions like examine if closed and examine if open, addressing I/O locations by module and bit, and programming concepts such as parallel and nested rungs, internal control relays, and adjustments for different scan patterns.
The document provides an overview of programmable logic controllers (PLCs) and automation systems. It discusses PLC hardware components like racks, power supplies, CPUs, I/O modules. It describes programming PLCs using ladder logic and compares PLCs to traditional relay-based control systems. PLCs allow for more flexible, user-programmable control compared to hardwired relay systems and are well-suited for industrial automation applications. The document also gives examples of Siemens S7 PLC systems and their modular components.
Ladder diagrams are a type of graphic language used to represent logic systems for industrial control. They resemble a ladder, with two vertical power rails and circuits connected horizontally in rungs. Standard symbols are used to represent components like switches, relays, and outputs. Logic functions like AND, OR, and NOT can be depicted using these symbols. Ladder diagrams are used to program PLCs and show control circuits for machines, depicting inputs, logic functions, and outputs.
Difference between micro controller and PLC, Introduction to PLC.,
PLC structure at glance,
PLC structure,
I/O processing,
Ladder Diagram Fundamentals,
PLC for industrial Prose cc control,
Selection criteria for PLC
This presentation provides an introduction to programmable logic controllers (PLCs). It defines a PLC as a solid state electronic device that can be programmed to control machines and processes. The presentation outlines the typical components of a PLC including the power supply, input and output modules, processor, and programming device. It also discusses PLC sizes, common applications in manufacturing and industry, and provides an example of how a PLC could control a tank used to mix two liquids.
PLC stands for programmable logic controller. It is a digital computer used to monitor inputs and control outputs of automated processes. Some key points:
- PLCs were introduced in the 1960s to replace relay-based control systems. They have since evolved to become more sophisticated.
- Common PLC manufacturers include Siemens, Allen-Bradley, Schneider Electric.
- PLCs use ladder logic programming to represent relay-based logic. Other common languages include function block diagram and statement list.
- PLC components include a power supply, CPU, I/O modules, and communication modules. Common applications include industrial automation and process control.
This is the complete ppt of 3 floor elevator which shows all the equipments used. This will definately helps you to make this project. And the construction of various equipment are done by me. Nothing is copied here everything is new.
From this project work during whole year we are made this project model or elevator is work in emergency situation and It is work easily with PLC. It’s applications are mostly used in regular life.
Learn what PLC Programming is, how it differs from computer programming, and how PLC programming is used in the industry, specifically how we use it at Innovative Automation.
Ladder logic diagrams are used to document industrial control systems. They resemble ladders with vertical power rails and horizontal rungs representing circuits. Digital logic functions like AND, OR, and NOT can be represented using contact configurations. Permissive and interlock circuits ensure multiple conditions are met or prevent incompatible actions. Motor control circuits can latch contactors to keep motors running and use stop buttons to unlatch them.
This document provides an overview of ladder logic fundamentals for a PLC controls and instrumentation course. It discusses the anatomy of a ladder program including input and output instructions, rungs, and power rails. It also covers logic functions like AND, OR, and XOR. Additionally, it explains logical continuity versus electrical continuity and examines input instructions like examine on and examine off. The document concludes with a discussion of I/O mapping and how input and output field devices connect to instructions in the PLC program.
Programmable Logic Controller and ladder logic programmingseema Vishwakarma
This document provides an introduction to programmable logic controllers (PLCs) and ladder logic programming. It defines a PLC as a small computer used to automate industrial processes by monitoring inputs and making decisions to control outputs based on a stored program. The document outlines the basic components of a PLC including input and output modules and the central processing unit. It then introduces ladder logic as the most common programming language for PLCs, describing the basic symbols of ladder diagrams including contacts, coils, and rungs. Finally, it provides examples of ladder logic programs for AND, OR, and NOT logic operations as well as timers and counters.
The document describes a traffic light control system using Programmable Logic Controllers (PLCs). The system uses three PLCs - a master PLC that controls two slave PLCs. The master PLC sends commands to control the light patterns at an intersection. The slave PLCs control the lights for cars and pedestrians. The system was prototyped using a PCB, 3D printed traffic lights, and packaging to test the logic implemented on the PLCs.
The document provides an overview of programmable logic controllers (PLCs). It defines PLCs as digital electronic devices that use programmable memory to implement logic functions like sequencing and timing to control machines and processes. The document discusses the basic structure of PLCs including the CPU, memory, input/output interfaces, and power supply. It also covers programming methods like ladder logic and instruction lists. Additional topics include input/output addressing, timers, counters, and techniques like latching, internal relays, and sequencing using timers.
This document describes experiments conducted using a programmable logic controller (PLC) to control various functions. The experiments include: 1) using a PLC to start and stop a motor via push buttons, 2) adding reverse direction control, 3) using timers to add on/off delays, and 4) combining on/off delays. The purpose is to understand and implement ladder logic programming of a PLC. Key components of a PLC like the power supply, processor, input and output modules are discussed. Ladder logic programming allows flexible control of industrial machinery.
This document provides information about programming and testing PLC programs. It discusses the hardware and software needed to program a PLC, including the PLC itself, a programming device like a PC, programming software, and a connector cable. It also describes how to test a program by downloading it from the PC to the PLC CPU and using an input simulator to simulate field inputs and observe the resulting outputs. The document includes examples of ladder logic programs using inputs, outputs, AND and OR logic, and timers to control gates at a parking lot entrance and exit.
Basic plc-programming-e book_Reliance High Tech LtdMarsus Marsus
This document provides an overview of basic PLC programming. It covers the introduction and history of PLCs, their basic design and components, programming methods, common programming languages, and examples of specific PLC models and their programming. The key points covered are:
- PLCs were developed in the 1960s as programmable replacements for relay-based control systems.
- A basic PLC has a CPU, memory, I/O modules, and a programming interface. Larger PLCs can have distributed architectures.
- PLC programming standards like IEC 61131 define common languages like ladder logic, function block diagrams, and structured text.
- Programming allows the control logic to be
PLC BASED AUTOMATED SYSTEM IN PROCESS INDUSTRY (Final Presentation)Shahid Faizee
This document describes a thesis project on implementing an automated PLC-based control system in a cement plant. The project involves developing motor block and group control block logic in Siemens Step 7 software to control crushers via a Siemens PLC and Expert Control System SCADA. Methodology includes defining inputs and outputs for motor and group blocks, designing submodules for start/stop, inputs, and outputs, and combining submodules into faceplates. The automated system is intended to reduce labor costs and improve performance by remotely monitoring and controlling plant operations.
This document discusses different types and programming of timers in PLC systems. It describes common approaches to modeling timers as relays or delay blocks. There are different types of timers including on-delay, off-delay, and pulse timers. Programming of timers varies between PLC manufacturers, with some treating timers as coils and others as delays. Examples are provided for sequencing motors using timers, cascading timers, producing an on-off cycle, and flashing a light using timers.
Automatic Bottle filling system and remote monitoring throughDHRUVIT KHARADI
This document describes an automatic bottle filling system that uses a programmable logic controller (PLC) and remote monitoring via a supervisory control and data acquisition (SCADA) system. The system includes a conveyor belt for bottle transport, a load cell for weight measurements, solenoid valves to control fluid flow, and a relay device to supply appropriate voltages to motors and pumps. Students developed PLC programming to control the system timers and incorporate the load cell measurements. They also configured communication between the PLC and computer software. The system is designed to automatically fill bottles with high accuracy.
The document introduces ladder diagrams and their basic components and logic. Ladder diagrams are a graphical programming language used to program programmable logic controllers (PLCs). Each rung represents a program statement with inputs on the left and outputs on the right. The PLC executes the ladder diagram by reading input states and determining output states from top to bottom. The document also describes common logic components like contacts, coils, timers, and counters used in ladder diagrams.
This document describes the design of a PLC-based smart lifting system using pneumatic components. The system uses a PLC as the main controller along with pneumatic actuators powered by an air compressor. It is configured to pick up and place objects at specified heights according to the object's detected height. The design includes modules for feeding, height detection, and robotic arm functions. Ladder logic programming was used to program the PLC and provide real-time monitoring of the system. The implemented design was demonstrated and shown to successfully detect object heights and control the lifting and placing of objects through three degrees of freedom.
The document discusses the basics of programmable logic controller (PLC) programming including PLC architecture, memory organization, programming languages, ladder logic instructions, addressing schemes, and programming techniques. Specifically, it covers the processor memory being divided into program and data memory, the ladder logic programming language using relay-type instructions like examine if closed and examine if open, addressing I/O locations by module and bit, and programming concepts such as parallel and nested rungs, internal control relays, and adjustments for different scan patterns.
The document provides an overview of programmable logic controllers (PLCs) and automation systems. It discusses PLC hardware components like racks, power supplies, CPUs, I/O modules. It describes programming PLCs using ladder logic and compares PLCs to traditional relay-based control systems. PLCs allow for more flexible, user-programmable control compared to hardwired relay systems and are well-suited for industrial automation applications. The document also gives examples of Siemens S7 PLC systems and their modular components.
Ladder diagrams are a type of graphic language used to represent logic systems for industrial control. They resemble a ladder, with two vertical power rails and circuits connected horizontally in rungs. Standard symbols are used to represent components like switches, relays, and outputs. Logic functions like AND, OR, and NOT can be depicted using these symbols. Ladder diagrams are used to program PLCs and show control circuits for machines, depicting inputs, logic functions, and outputs.
Difference between micro controller and PLC, Introduction to PLC.,
PLC structure at glance,
PLC structure,
I/O processing,
Ladder Diagram Fundamentals,
PLC for industrial Prose cc control,
Selection criteria for PLC
This presentation provides an introduction to programmable logic controllers (PLCs). It defines a PLC as a solid state electronic device that can be programmed to control machines and processes. The presentation outlines the typical components of a PLC including the power supply, input and output modules, processor, and programming device. It also discusses PLC sizes, common applications in manufacturing and industry, and provides an example of how a PLC could control a tank used to mix two liquids.
PLC stands for programmable logic controller. It is a digital computer used to monitor inputs and control outputs of automated processes. Some key points:
- PLCs were introduced in the 1960s to replace relay-based control systems. They have since evolved to become more sophisticated.
- Common PLC manufacturers include Siemens, Allen-Bradley, Schneider Electric.
- PLCs use ladder logic programming to represent relay-based logic. Other common languages include function block diagram and statement list.
- PLC components include a power supply, CPU, I/O modules, and communication modules. Common applications include industrial automation and process control.
This is the complete ppt of 3 floor elevator which shows all the equipments used. This will definately helps you to make this project. And the construction of various equipment are done by me. Nothing is copied here everything is new.
From this project work during whole year we are made this project model or elevator is work in emergency situation and It is work easily with PLC. It’s applications are mostly used in regular life.
Learn what PLC Programming is, how it differs from computer programming, and how PLC programming is used in the industry, specifically how we use it at Innovative Automation.
Ladder logic diagrams are used to document industrial control systems. They resemble ladders with vertical power rails and horizontal rungs representing circuits. Digital logic functions like AND, OR, and NOT can be represented using contact configurations. Permissive and interlock circuits ensure multiple conditions are met or prevent incompatible actions. Motor control circuits can latch contactors to keep motors running and use stop buttons to unlatch them.
This document provides an overview of ladder logic fundamentals for a PLC controls and instrumentation course. It discusses the anatomy of a ladder program including input and output instructions, rungs, and power rails. It also covers logic functions like AND, OR, and XOR. Additionally, it explains logical continuity versus electrical continuity and examines input instructions like examine on and examine off. The document concludes with a discussion of I/O mapping and how input and output field devices connect to instructions in the PLC program.
Programmable Logic Controller and ladder logic programmingseema Vishwakarma
This document provides an introduction to programmable logic controllers (PLCs) and ladder logic programming. It defines a PLC as a small computer used to automate industrial processes by monitoring inputs and making decisions to control outputs based on a stored program. The document outlines the basic components of a PLC including input and output modules and the central processing unit. It then introduces ladder logic as the most common programming language for PLCs, describing the basic symbols of ladder diagrams including contacts, coils, and rungs. Finally, it provides examples of ladder logic programs for AND, OR, and NOT logic operations as well as timers and counters.
Ladder Logic and Touch Screen PLC Programming Tutorial/TrainingICP DAS USA, Inc.
Ladder Logic is widely used control functions, is a programming language based on boolean expressions and is represented by graphical relay logic diagrams. Our touch screen controllers can be programmed in both C Language and and Ladder Logic, comes with free HMIWorks Development Environment and Demo Programs. We provide free programming services for small and large projects.
Learn more: http://www.icpdas-usa.com/newsletters/Ladder-Logic-Touch-Screen-PLC-Programming.php?r=slideshare
This document is a project report on programmable logic controllers (PLCs) and supervisory control and data acquisition (SCADA) systems by Ishank Ranjan, an 8th semester undergraduate student at Hindustan College of Science and Technology in Mathura, India. The report provides an acknowledgment, certificate of training, preface, table of contents, and 15 sections that describe features of PLCs, ladder logic programming, SCADA systems, and potential benefits of using PLCs and SCADA for industrial automation and process control.
This document provides an overview of a seminar on programmable logic controllers (PLCs). The objectives are to describe PLC components, interpret specifications, apply troubleshooting techniques, convert relay logic to PLC languages, and operate and program PLCs. The contents include the history of PLCs, relay logic, PLC architecture such as CPU and I/O systems, programming concepts, applications, and troubleshooting. PLCs were developed to replace relay-based control systems and are now widely used in industrial automation.
PLC Ladder Diagram basics, with two solved examples
For more information go to
http://shrutizpresentations.blogspot.in/2014/04/plc-ladder-diagram-basics.html
This document provides an overview of programmable logic controllers (PLCs). It describes the basic components of a PLC including the central processing unit, input and output modules, power supply, and programming software. PLCs were developed to provide flexibility compared to traditional hardwired control systems. The document discusses PLC applications, advantages such as ease of programming and modification, as well as some disadvantages like proprietary aspects. It also covers PLC size, history, and leading manufacturers.
The document discusses automation and programmable logic controllers (PLCs). It describes how automation delegates human control functions to equipment to achieve higher productivity, superior product quality, efficient energy usage, and improved safety. It then defines PLCs, explaining that they are industrial computers that monitor inputs, make decisions based on programs, and control outputs to automate processes. PLCs have input and output modules, a central processing unit, memory, and power supply. They use ladder logic programming and have advantages like increased reliability but also disadvantages like high initial costs. The document also briefly introduces supervisory control and data acquisition (SCADA) systems.
This document provides an overview of programmable logic controllers (PLCs). It defines a PLC as a digital computer used for industrial control systems. The document outlines the history of PLCs, their major components including the processor, power supply, and I/O modules. It describes the operational sequence of a PLC including input scan, logic solve, and output scan. Programming methods like ladder logic and functional block diagrams are discussed. Examples are provided of ladder logic programs for starting and stopping a motor. Advantages of PLCs include reliability, flexibility, and cost effectiveness. The document concludes by listing some common industrial applications of PLCs.
Programmable logic controllers (PLCs) were introduced in the late 1960s/early 1970s to replace large expensive panels of relays and counters. PLCs have since become highly sophisticated and versatile control systems capable of complex math functions and high-speed operation. A PLC is a specialized digital computer used for automating electromechanical processes. It consists of a central processing unit, memory, input and output modules, a programmer, and racks/chassis. PLCs are programmed using ladder logic or other languages to control processes based on input and output status. Ladder logic uses contacts, coils, and rungs to represent relay-based logic diagrams graphically.
The document provides an overview of SCADA systems and PLCs. It discusses the key features of PLCs, including how they are programmed using ladder logic. The document also provides examples of using digital and analog signals with PLCs to control processes. Finally, it summarizes the training report submitted by Sonu Kumar Yadav on the study of SCADA systems and PLCs during an industrial internship.
International Journal of Computational Engineering Research(IJCER)ijceronline
International Journal of Computational Engineering Research(IJCER) is an intentional online Journal in English monthly publishing journal. This Journal publish original research work that contributes significantly to further the scientific knowledge in engineering and Technology.
This document provides an introduction to Programmable Logic Controllers (PLCs). It discusses the history and evolution of control systems from humans to relays to PLCs. The key components of a PLC including the input/output modules, central processing unit, memory, and programming terminal are described. Programming methods for PLCs such as ladder logic, Boolean expressions, and mnemonics are also introduced. Examples of using timers, counters, and internal relays in PLC programs are provided.
This industrial training report provides an overview of programmable logic controllers (PLCs) and supervisory control and data acquisition (SCADA) systems. It discusses the basic components, features, and wiring of PLCs. It also covers PLC programming using ladder logic, input/output signal generation, and comparisons to other control systems. The report then provides explanations of SCADA hardware architecture, communications, functionality, alarms, logging, reporting, automation, applications, and potential benefits.
This document provides information on programmable logic control (PLC) including processor information, theory of operation, Allen Bradley PLC details, pin diagrams, channel configuration, network configuration through LAN, and example programs to control devices like lights and fans using different logic functions. The document covers PLC basics, components, ladder logic programming, actuators, switches, and provides 14 programming examples to demonstrate sequencing, timing, and control applications using PLCs.
A programmable logic controller (PLC) is an industrial computer system that monitors inputs and controls outputs to automate a process. The document discusses PLC systems, including their components, programming, and applications. PLCs are used to control industrial processes like manufacturing plants, processing facilities, and wastewater treatment. They have inputs that monitor data, a CPU that runs logic programs, and outputs that control devices. PLCs are programmed using ladder logic, function block, or sequential function chart languages. They are widely used across industries like mining, oil and gas, and manufacturing due to their reliability in harsh conditions.
Programmable logic controllers (PLCs) are digital electronic devices that use a programmable memory to store instructions and implement functions like logic, sequencing, timing, and arithmetic to control machines and processes. PLCs were developed to simplify control automation by replacing relay logic systems. A PLC consists of a processor, memory, input/output modules, and a power supply. It reads input signals, executes a stored program to control outputs, and then repeats in a scan cycle. Common programming methods for PLCs include ladder logic, statement list, and function block diagrams. PLCs are widely used in industry for their flexibility, reliability, and ability to operate in harsh environments.
This document provides an overview of PLC and SCADA systems. It defines PLC as an industrial computer that monitors inputs, makes decisions based on its program, and controls outputs to automate processes. The history and components of PLCs are described, including the power supply, I/O modules, processor, and programming devices. Programming languages for PLCs include ladder logic, functional block diagrams, and sequential function charts. SCADA is defined as software used for process control that allows users to monitor, control, generate alarms and acquire data from remote facilities. The document discusses the composition, advantages, and applications of SCADA systems.
Training report prepared on PLC on CNC at BHEL,Hyderabad. It have sufficient slides to know the basics about PLC on CNC and working of that with coding. It was worth learning on BHEL.
Advanced plc programming & scada system designlakshanwalpita
The document provides an overview of programmable logic controllers (PLCs) and SCADA systems. It discusses the history and evolution of PLCs from relay-based control systems to modern PLCs that can be programmed using software on PCs. A PLC works by continuously scanning its program in a loop, checking input statuses, executing the user program, and updating outputs. The document also covers common PLC components, programming methods, and input/output connection types.
This document discusses programmable logic controllers (PLCs), including their basic structure, input/output processing, and programming. It notes that PLCs process inputs and outputs through programming, with ladder programming being a common technique. Ladder diagrams follow certain conventions, such as each rung defining one operation and starting with an input and ending with an output. Inputs and outputs are identified by their addresses in the PLC's memory.
training report. automation,plc , scada MdQutubuddin1
This document provides a training report on programmable logic controllers (PLCs), supervisory control and data acquisition (SCADA) systems, and automation. It introduces PLCs and their architecture, programming using ladder logic, applications of PLCs and SCADA systems, and common SCADA software. Examples of automation applications in various industries are also discussed. The report aims to explain the basic concepts and components of PLCs, SCADA, and automation through diagrams and a programming example.
This document provides an overview of a basic training course on programmable logic controllers (PLCs). It describes the course objectives which are to understand the major PLC components, interpret specifications, troubleshoot PLCs, convert relay logic to PLC programming, and operate and program a PLC for applications. The course covers the history of PLCs, components like the CPU and I/O system, programming concepts, applications, and troubleshooting. It also provides examples of PLC programming for mixing tank controls.
The document discusses programmable logic controllers (PLCs), which are microprocessor-based devices used to control machinery on the shop floor. Early PLCs were designed to replace relay logic systems and were programmed using ladder logic to resemble relay diagrams. Modern PLCs can communicate over networks and use various programming languages according to standards. PLCs read sensors and control actuators to automate industrial processes, and are well-suited for applications requiring customized control systems that may need to change over time.
INDUSTRIAL TRAINING REPORT EMBEDDED SYSTEM.pptxMeghdeepSingh
This document provides an overview of embedded systems and microcontrollers. It defines a microcontroller as a single-chip computer containing memory, input/output circuitry, and other components to function without additional support. The document describes the features and components of a typical microcontroller, including registers, instruction sets, addressing modes, and peripherals. It compares microcontrollers to microprocessors and provides examples of using LEDs and 7-segment displays with microcontrollers.
This document provides an overview of a basic training course on programmable logic controllers (PLCs). It describes the course objectives which are to describe PLC components, interpret specifications, apply troubleshooting techniques, convert relay logic to PLC language, and operate and program a PLC. The document lists the course contents which include the history of PLCs, programming concepts, and applications. It also provides details on the basic hardware components of a PLC including the processor, memory, I/O modules, and programming device.
This document provides an overview of a basic training course on programmable logic controllers (PLCs). It describes the objectives of the training as teaching the major components of PLCs, programming techniques, and how to troubleshoot applications. The document lists the course contents which cover topics like the history of PLCs, relay logic, the central processing unit, programming concepts, and applications. It also provides examples of PLC components, programming, and a sample control application using a liquid mixing tank.
In this session you will learn:
Programmable Logic Controller(PLC)
Types of PLC’s
PLC architecture
Scan cycles
Scan patterns
PLC programming
Ladder diagram programming
Latch and Unlatch
DCS architecture
Similar to Teach-In : Ladder Logic for PIC Micro (20)
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...University of Maribor
Slides from talk presenting:
Aleš Zamuda: Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapter and Networking.
Presentation at IcETRAN 2024 session:
"Inter-Society Networking Panel GRSS/MTT-S/CIS
Panel Session: Promoting Connection and Cooperation"
IEEE Slovenia GRSS
IEEE Serbia and Montenegro MTT-S
IEEE Slovenia CIS
11TH INTERNATIONAL CONFERENCE ON ELECTRICAL, ELECTRONIC AND COMPUTING ENGINEERING
3-6 June 2024, Niš, Serbia
We have compiled the most important slides from each speaker's presentation. This year’s compilation, available for free, captures the key insights and contributions shared during the DfMAy 2024 conference.
Literature Review Basics and Understanding Reference Management.pptxDr Ramhari Poudyal
Three-day training on academic research focuses on analytical tools at United Technical College, supported by the University Grant Commission, Nepal. 24-26 May 2024
ACEP Magazine edition 4th launched on 05.06.2024Rahul
This document provides information about the third edition of the magazine "Sthapatya" published by the Association of Civil Engineers (Practicing) Aurangabad. It includes messages from current and past presidents of ACEP, memories and photos from past ACEP events, information on life time achievement awards given by ACEP, and a technical article on concrete maintenance, repairs and strengthening. The document highlights activities of ACEP and provides a technical educational article for members.
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTjpsjournal1
The rivalry between prominent international actors for dominance over Central Asia's hydrocarbon
reserves and the ancient silk trade route, along with China's diplomatic endeavours in the area, has been
referred to as the "New Great Game." This research centres on the power struggle, considering
geopolitical, geostrategic, and geoeconomic variables. Topics including trade, political hegemony, oil
politics, and conventional and nontraditional security are all explored and explained by the researcher.
Using Mackinder's Heartland, Spykman Rimland, and Hegemonic Stability theories, examines China's role
in Central Asia. This study adheres to the empirical epistemological method and has taken care of
objectivity. This study analyze primary and secondary research documents critically to elaborate role of
china’s geo economic outreach in central Asian countries and its future prospect. China is thriving in trade,
pipeline politics, and winning states, according to this study, thanks to important instruments like the
Shanghai Cooperation Organisation and the Belt and Road Economic Initiative. According to this study,
China is seeing significant success in commerce, pipeline politics, and gaining influence on other
governments. This success may be attributed to the effective utilisation of key tools such as the Shanghai
Cooperation Organisation and the Belt and Road Economic Initiative.
Introduction- e - waste – definition - sources of e-waste– hazardous substances in e-waste - effects of e-waste on environment and human health- need for e-waste management– e-waste handling rules - waste minimization techniques for managing e-waste – recycling of e-waste - disposal treatment methods of e- waste – mechanism of extraction of precious metal from leaching solution-global Scenario of E-waste – E-waste in India- case studies.
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsVictor Morales
K8sGPT is a tool that analyzes and diagnoses Kubernetes clusters. This presentation was used to share the requirements and dependencies to deploy K8sGPT in a local environment.
International Conference on NLP, Artificial Intelligence, Machine Learning an...gerogepatton
International Conference on NLP, Artificial Intelligence, Machine Learning and Applications (NLAIM 2024) offers a premier global platform for exchanging insights and findings in the theory, methodology, and applications of NLP, Artificial Intelligence, Machine Learning, and their applications. The conference seeks substantial contributions across all key domains of NLP, Artificial Intelligence, Machine Learning, and their practical applications, aiming to foster both theoretical advancements and real-world implementations. With a focus on facilitating collaboration between researchers and practitioners from academia and industry, the conference serves as a nexus for sharing the latest developments in the field.
International Conference on NLP, Artificial Intelligence, Machine Learning an...
Teach-In : Ladder Logic for PIC Micro
1. 50 Everyday Practical Electronics, November 2009
Teach-In 2010
By Walter Ditch
TEACH-IN 2010
LADDER LOGIC PROGRAMMING
FOR THE PIC MICRO
Part 1: Getting Started –
Working with Inputs and
Outputs
T
HIS IS THE ÚRST OF A SERIES OF SIX
ARTICLES
2. WHICH WILL SHOW YOU
HOW TO PROGRAM A VARIETY OF 0)#
MICROCONTROLLERS USING AN APPROACH
KNOWN AS LADDER LOGIC
7HY LADDER LOGIC 7ELL
3. THIS IS
THE PREFERRED SOFTWARE DEVELOPMENT
METHOD FOR A TYPE OF COMPUTER KNOWN
AS A 0,#
5. WHICH ARE COMMONLY USED
IN INDUSTRY TO CONTROL PRODUCTION
LINE OPERATIONS AND PROCESSES 4HEY
ARE DESIGNED TO BE EASILY CONÚGURED
AND USED BY ENGINEERS
6. TYPICALLY TO
PERFORM SIMPLE LOGICAL TASKS AND
SEQUENCES
,ADDER LOGIC HAS HISTORICALLY
PROVED VERY POPULAR WITH ELECTRICAL
ENGINEERS
7. SINCE IT ALLOWS CONTROL
ORIENTED SOFTWARE TO BE CREATED BY
LINKING TOGETHER lELECTRICALm ELEMENTS
SUCH AS INPUTS
13. THE APPROACH IS QUITE INTUITIVE FOR
THOSE FROM AN ELECTRICAL OR ELECTRONIC
BACKGROUND
14. SINCE THE INDIVIDUAL
PROGRAMMING ELEMENTS ARE ALREADY
WELL UNDERSTOOD 4HE RESULTING SOURCE
CODE PROGRAMS ALSO TEND TO BE QUITE
SHORT AND EASY TO INTERPRET
4HIS ÚRST INSTALLMENT OF THE SERIES
CONCENTRATES ON DEVELOPING SIMPLE
0,#
STYLE PROGRAMS TO READ INPUTS
AND TO CONTROL OUTPUTS 7EmLL LOOK
AT THE GRAPHICAL REPRESENTATION OF A
CONTROL
ORIENTED SYSTEM USING A LAD-
DER DIAGRAM
15. AND ITS CONVERSION TO A
SOURCE CODE ÚLE
7EmLL THEN WORK THROUGH THE DE-
TAILED STEPS INVOLVED IN CREATING AND
TESTING 0,#
STYLE APPLICATIONS
16. USING A
VARIETY OF WIDELY AVAILABLE 0)#
BASED
HARDWARE AND SOFTWARE 4HE INTERNAL
METHOD OF OPERATION OF THE SUPPLIED
SOFTWARE WILL ALSO BE DISCUSSED
17. ENA-
BLING YOU TO DECIDE FOR YOURSELF WHEN
AND WHERE THIS APPROACH MIGHT BE
APPLICABLE
3UBSEQUENT PARTS OF THE SERIES WILL
INTRODUCE FURTHER SOFTWARE FEATURES
AND APPLICATIONS
18. INCLUDING
3IMPLE COMBINATIONAL AND SE-
QUENTIAL LOGIC LOGIC GATES AND LATCHES
4IMERS AND SHIFT REGISTERS
#OUNTERS AND PULSE
WIDTH
MODULATED 07- OUTPUTS
3EQUENCERS AND BYTE
ORIENTED
INSTRUCTIONS
! VARIETY OF MICROCONTROLLER
BASED
APPLICATIONS OF LADDER LOGIC WILL ALSO
BE DEVELOPED
29. AVAILABLE FROM THE Everyday Practical
Electronics EPE 2EADERS 3ERVICES
0ROTEUS 63- ELECTRONIC CIRCUIT
SIMULATION SOFTWARE FROM ,ABCENTER
%LECTRONICS www.labcenter.co.uk
(OPEFULLY
30. YOU WILL HAVE ACCESS TO
ONE OF THE ABOVE AND WILL BE ABLE TO
WORK ALONG WITH THE SERIES 3EEING
REALLY IS BELIEVING
31. AND THE BEST WAY
TO LEARN IS TO TRY THE CONCEPTS OUT FOR
YOURSELF )F YOU DO
32. ) GUARANTEE YOUmLL
BE SURPRISED BY THE POWER AND SIMPLIC-
ITY OF LADDER LOGICØ
Comparing PLCs and
microcontrollers
4HE MAIN DIFFERENCES BETWEEN A
0,# AND A MICROCONTROLLER RELATE TO
33. Everyday Practical Electronics, November 2009 51
Teach-In 2010
size, complexity and, of course, cost.
The inputs and outputs circuits of
a PLC, for example, are extremely
rugged, with digital inputs often be-
ing connected via opto-isolators, and
digital output types including transis-
tor, thyristor, triac and relay. This al-
lows the PLC to directly control high
power devices, such as motors, pneu-
matic actuators and the like. A typical
implement combinational and se-
quential logic functions in electrical
control circuits, and it is in part this
electrical basis which makes it easy
for electrical engineers to understand
– even those without a computing
background. Consider, for example, a
simple electrical circuit consisting of
a switch and a lamp, and also its rep-
resentation using a ladder diagram, as
shown in Fig.1.2.
Considering the circuit on the left,
closing the switch will clearly cause
the lamp to light. The ladder diagram
on the right is equivalent, consisting
of a pair of vertical power rails, with
one or more horizontal ‘rungs’. (The
ladder-like appearance gives this
type of diagram its name.) Closing the
normally open switch contacts on the
left of the ladder diagram will con-
nect power through the horizontal
rung, hence lighting the lamp.
Historically, the output would
typically have been a relay coil, thus
allowing a relatively low voltage
control circuit to switch mains oper-
ated power devices. For this reason,
PLC inputs are often referred to as
contacts, while outputs are called
coils. It can be seen from the ladder
diagram that an output coil is rep-
resented graphically using a pair of
curved braces (although a circular
output symbol is sometimes seen).
This extremely simple concept is
the basis of PLC operation, and in part
explains why electrical engineers are
so comfortable writing PLC programs.
This added complexity is avoid-
ed here by the pre-configuration
of default settings, such as port
directions, in the supplied PLC header
ÚLES OR EXAMPLE
35. 0ORT ! IS CONÚGURED TO BE AN
input, while Port B is an output.) You
can, of course, change these settings,
simply by editing the relevant section
OF THE HEADER ÚLE
36. BUT THE SOFTWARE IS
commerciallyavailablePLCisshownin
Fig.1.1, with input connections shown
at the top and outputs at the bottom.
While the I/O connections of a mi-
crocontroller operate at much lower
voltage and current than those of a
PLC, they are essentially the same from
a software point of view. The internal
structure of a microcontroller also
contains many similar elements to
those found inside a PLC, including a
central processing unit, program mem-
ory (ROM), together with a variety of
volatile and non-volatile data memory
types. (The content of volatile memory
types, such as static RAM, is lost when
power is removed, while non-volatile
memory,suchasEEPROM,isretained.)
The allocation of connections as in-
puts or outputs is, of course, pre-deter-
mined by the PLC manufacturer, since
this is a pre-requisite for the connection
of specialised interface circuitry. Not so
inthemicrocontrollerworld,wherethe
assembly language programmer nor-
mally has to decide on port directions,
PLUS A VARIETY OF OTHER CONÚGURATION
settings, prior to actually getting the
microcontrollertodosomethinguseful.
designed to work straight out of the
BOX
37. WITHOUT ANY NEED FOR CONÚGURA-
tion – just like a real PLC.
So, having established that PLCs
and microcontrollers have a lot in
Fig.1.1. A typical industrial PLC
Fig.1.2. A simple switch and lamp circuit (left) and its equivalent ladder
diagram (right)
common, let’s turn our attention to lad-
DER LOGIC
38. AND ÚND OUT WHAT IT HAS TO
offer in terms of software development.
Ladder diagrams and ladder
logic
Ladder logic owes its origin to
the use of switches and relays to
Ladder logic programs are also very
concise, with a section of code to (1)
read an input and then (2) control a
linked output requiring as little as
two lines of code. Listing 1.1 shows
a possible implementation.
In general, a PLC program is cre-
ated by converting each input contact
39. 52 Everyday Practical Electronics, November 2009
Teach-In 2010
and output coil of the system’s ladder
diagram into a series of equivalent
program statements. Execution of the
program is then a continuously operat-
ing sequence of:
Reading inputs
Performing logic-based
calculations
Controlling outputs
This repeating process is known as
the scan cycle, and is shown graphi-
cally for a slightly more complex
example in Fig.1.3.
It can be seen that each rung of the
ladder diagram is evaluated from left
to right, starting at the top rung and
working progressively down (Steps 1
and 2 of Fig.1.3). The End of Program
A number of conclusions may be
immediately drawn from this method
of operation:
1. Execution of a PLC program con-
sists of a continuously operating pro-
gramloop(arepeatingscancycle),even
though this is not explicitly shown in
the program listing or ladder diagram.
2. The time taken for a single scan
cycle will increase in line with the
complexity of the program, since the
execution time for a single instruction
IS ÚXED BY THE MICROPROCESSOR CLOCK
frequency.
Slightly less obviously:
3. An externally applied input signal
WILL NEED TO BE PRESENT FOR A SUFÚCIENT
time to guarantee it being ‘seen’ by
the input phase of the
scanning loop.
4. The average time
taken to react to a
changing input is re-
lated to the scanning
loop duration.
5. It may take more
than one scanning
loop for the results of
complex calculations
to fully propagate
through the system.
This may lead to the
possibility of transient
glitches as calcula-
tions ‘ripple-though’.
In practice, you
SHOULD ÚND THAT LAD-
der logic solutions are
suitableinthemajority
of logic-based control
scenarios, since the computer is typi-
cally operating at much higher speed
than the system being controlled.
Now that the basic principles of
ladder logic programming have been
covered, the next step is to obtain the
required software, which will then
enable us to create and test an execut-
able program.
Obtaining the software
The ladder logic software is designed
to work with the MPLAB Integrated De-
velopmentEnvironment(IDE),whichis
freely available for download from the
Microchip website (www.microchip.
com),oronCD-Rom.Allthatisrequired
is to include a link to the appropriate
HEADER ÚLE FROM WITHIN THE ASSEMBLY
LANGUAGE SOURCE ÚLE
40. AT WHICH POINT A
variety of PLC-style commands become
available for use in your programs.
As mentioned earlier, versions of the
software are available for the following
commonly used PIC microcontrollers:
PIC16F627/PIC16F627A (head-
ER ÚLE l0,#m
PIC16F628/PIC16F628A (head-
ER ÚLE l0,#m
0)# HEADER ÚLE l
PLC’)
PIC16F88 (header files
‘16F88_L.PLC’ and ‘16F88_H.PLC’
offer low voltage and high voltage
program versions respectively)
0)# HEADER ÚLE l
PLC’)
)N PRACTICE
41. THE ÚRST FOUR OF THESE
are all 18-pin ICs, differing mainly in
THE QUANTITY OF ÛASH
BASED PROGRAM
memory, static RAM, or EEPROM-
based non-volatile data memory. The
PIC16F887 is a 44-pin IC, having
enhanced input/output capabilities.
These features are summarised in
Table 1.1.
Inclusion of the appropriate
header file will cause a number of
default settings to be chosen, such
as port directions, oscillator type
and so on. These settings have been
tested with a number of hardware
configurations, and are intended
to simplify the configuration proc-
ess as far as possible. (You should
of course review these settings to
ensure compatibility with your own
requirements.) Default options are
summarised in Table 1.2.
A number of required files are
available in a compressed ZIP file,
which may be obtained from the the
Library Project Code section of
the Everyday Practical Electronics
website (www.epemag.com). The
contents of the ZIP file are given in
Table 1.3.
ld SWITCH ; Read state of Switch
out LAMP ; Output to Lamp
Listing 1.1. A notional section of a PLC program based on the circuit and
ladder diagram of Fig.1.2
Fig.1.3. The repeating scan cycle of a PLC executing
a ladder logic program
statement forces program execution to
RESUME FROM THE BEGINNING OF THE ÚRST
rung (Step 3), causing the program to
run continuously. This program might
be coded using statements such as
those given in Listing 1.2.
ld SWITCH_A ; Read state of Switch A
out LAMP_A ; Output to Lamp A
ld SWITCH_B ; Read state of Switch B
out LAMP_B ; Output to Lamp B
endp ; End of PLC program
Listing 1.2. A PLC program based on the ladder diagram of Fig.1.3
42. Everyday Practical Electronics, November 2009 53
Teach-In 2010
Filename Description
16F627.PLC PLC header file for the PIC16F627/627A microcontroller
16F628.PLC PLC header file for the PIC16F628/628A microcontroller
16F648.PLC PLC header file for the PIC16F648A microcontroller
16F88_L.PLC PLC header file for the PIC16F88 microcontroller – low voltage
programming enabled on pin RB3
16F88_H.PLC PLC header file for the PIC16F88 microcontroller – high voltage
programming enabled, pin RB3 available for general I/O
16F887.PLC PLC header file for the PIC16F887 microcontroller
PIC16F627.DSN Proteus VSM simulation – PIC16F627A based Digital I/O Board
PIC16F88.DSN Proteus VSM simulation – PIC16F88 based Digital I/O Board
PIC16F887.DSN Proteus VSM simulation – PIC16F887A based Digital I/O Board
Lst1_3.asm Source code file for Listing 1.3
Lst1_4.asm Source code file for Listing 1.4
Lst1_5.asm Source code file for Listing 1.5
Lst1_6.asm Source code file for Listing 1.6
Assembling and execut-
ing simple PLC-style
programs
In this section you will see
just how easy it is to create and
assemble simple programs and
then run them on a variety of
different PIC-based systems. I
recommend that you try these
activities out for yourself, if at
all possible.
Begin by extracting the entire
CONTENTS OF THE :)0 ÚLE TO A CON-
venient folder and then use the
MPLAB IDE’s File Open menu
OPTION TO DISPLAY THE ÚLE l,ST?
asm’, the content of which is
GIVEN IN ,ISTING
/UR ÚRST PROGRAM IS FUNCTION-
ally identical to the code snippet
PREVIOUSLY SEEN IN ,ISTING
43. BUT BASED ON THE 0)#
microcontroller. It is suitable
for use either with the PICkit 2
Debug Express board, or with
Proteus VSM electronic simu-
lation software. (Note that the
PICkit 2 board has a single input
SWITCH
45. WHICH IS
CONNECTED TO THE LEAST SIGNIÚCANT
bit of Port B, plus eight LEDs
connected to Port D – which
explains the choice of inputs
AND OUTPUTS IN ,ISTING
Having displayed the source
ASM ÚLE IN -0,!
46. THE NEXT
step is to assemble it, in order
to create a machine code (.hex)
ÚLE
47. WHICH CAN LATER BE DOWN-
loaded and programmed. The
ÚRST STEP IS TO CHOOSE THE RE-
quired microcontroller type by
selecting the #ONlGUREªª3ELECTª
Device menu option, and then
selecting the PIC16F887 from
the Device drop-down list. Next
click on the blue title bar of the
SOURCE CODE ÚLE TO ENSURE IT IS
highlighted and then assemble
THE ÚLE BY SELECTING THE Project
Quickbuild Lst1_3.asm menu
option. If everything has gone
TO PLAN YOU SHOULD SEE A ÛURRY
OF ACTIVITY AS THE ÚLE IS ASSEM-
BLED
48. CULMINATING IN A lUILD
Succeeded’ message, displayed in
the Build tab of the Output window.
The MPLAB IDE has now done its
JOB AND A ,ST?HEX ÚLE WILL HAVE
been created in the same directory
AS THE SOURCE CODE ÚLE
49. READY TO BE
programmed.
Device Program
(kWords)
RAM
(bytes)
EEPROM
(bytes)
Max I/O
(bits)
Other
Features
PIC16F627 1 224 128 16 2 comparators
PIC16F628 2 224 128 16 2 comparators
PIC16F648 4 256 256 16 2 comparators
PIC16F88 4 368 256 16 2 comparators
7-channel ADC
PIC16F887 8 368 256 35 2 comparators
14-channel ADC
Table 1.1. Major features of supported PIC microcontrollers
Device Inputs Outputs Other Features
PIC16F627 / 628
/ 648
Port A (5 bits) Port B (8 bits) Comparators disabled, pull-ups disabled
4MHz external crystal oscillator selected
Timer 0 configured for use by PLC software
MCLR enabled, Watchdog timer enabled
PIC16F88 Port A (5 bits) Port B (8 bits) Comparators disabled, pull-ups disabled
4MHz external crystal oscillator selected
Timer 0 configured for use by PLC software
MCLR enabled, Watchdog timer enabled
ADC disabled
PIC16F887 Port A (8 bits)
Port B (8 bits)
Port E (4 bits)
Port C (8 bits)
Port D (8 bits)
Comparators disabled, pull-ups disabled
4MHz internal oscillator selected
Timer 0 configured for use by PLC software
MCLR disabled, Watchdog timer enabled
ADC disabled
4ABLEªª$EFAULTª0)#ªSOFTWAREªCONlGURATIONªOPTIONS
Table 1.3. File contents of ‘PLC1.zip’
include 16F887.PLC ; Defines PLC instructions
ld PORTB, 0 ; Read Port B bit 0
out PORTD, 0 ; Output to Port D bit 0
endp ; End of PLC program
Listing 1.3. Reading a switch and outputting to an LED (Lst1_3.asm)
50. 54 Everyday Practical Electronics, November 2009
Teach-In 2010
Syntax Function Ladder Diagram Symbol
ld REGISTER, BIT[0-7] Read an I/O bit
ld_not REGISTER, BIT[0-7] Read an I/O bit (inverted)
out REGISTER, BIT[0-7] Send to output bit
out_not REGISTER, BIT[0-7] Send to output bit (inverted)
Table 1.4. Bit input/output commands
Fig.1.4. A Proteus VSM simulation of the PIC16F887 microcontroller
What happens next depends on how
you intend to actually run the program.
If you are using the PICKit 2 board
then the next step is to run the PICkit
2 programmer application, then use
the File Import Hex menu option
TO OPEN THE MACHINE CODE HEX ÚLE
created earlier. Next, click the Write
button to program the PIC16F887 mi-
crocontroller. You should see a green
Programming Successful message in
the programmer window at this stage.
Finally, apply power to the board by
clicking the On checkbox situated just
under the VDD PICkit 2 label
at the upper right.
Pressing Switch 1 will
now cause the LED con-
nected to RD0 to toggle on
and off. However, you may
note that the LED actually
goes out when the switch
is pressed, which is the
opposite of what you might
have expected. Examin-
ing the schematic diagram
supplied with the PICkit 2
documentation solves the
mystery, revealing that SW1
normally reads as a logic-1,
providing a logic-0 when
pressed. The required logic of our
program may be easily restored by
replacing the ‘ld’ instruction with its
negative logic ‘ld_not’ equivalent, as
given in Table 1.4.
From Table 1.4, we can also see
that a negative logic output command
51. Everyday Practical Electronics, November 2009 55
Teach-In 2010
(out_not) is available. Thus, we can
create a logical inversion either by
using ‘ld_not’ followed by ‘out’, or
‘ld’ followed by ‘out_not’. If you are
using the PICkit 2 board, then you
can use this information to modify the
program of Listing 1.3 so that pressing
the switch causes the LED to come on,
rather than go out.
If you are lucky enough to have the
full version of Proteus VSM, Version
7.0 or later, then this may be used to
simulate the operation of the program
of Listing 1.3. Begin by using Proteus
to open the supplied PIC16F887.DSN
ÚLE
52. WHICH WILL APPEAR AS SHOWN IN
Fig.1.4.
include 16F627.PLC ; Defines PLC instructions
ld PORTA, 0 ; Read Port A bit 0
out PORTB, 0 ; Output to Port B bit 0
ld PORTA, 1 ; Read Port A bit 1
out PORTB, 1 ; Output to Port B bit 1
endp ; End of PLC program
Listing 1.4. Reading and controlling multiple inputs and outputs (Lst1_4.asm)
Controlling multiple inputs
and outputs
To take a slightly more complex
example, suppose we wanted to con-
trol several inputs and outputs. This
could be achieved as illustrated by
Listing 1.4, shown for a PIC16F627-
based system.
Assuming you have a suitable PIC
programmer and experimentation
board, such as the Velleman K8048, the
ÚRST STEP IS TO USE THE -0,! )$% TO
CREATE A MACHINE CODE ÚLE REMEMBER-
ing of course to set the device type to
either the PIC16F627 or PIC16F627A,
as appropriate). Next, connect the
Fig.1.5. The output produced by Listing 1.4, running on a Velleman K8048 board
include 16F887.PLC ; Defines PLC instructions
ld PORTE, 3 ; Read Port E bit 3 (ICSP pin 1)
out PORTD, 3 ; Output to Port D bit 3
ld PORTB, 7 ; Read Port B bit 7 (ICSP pin 4)
out PORTD, 2 ; Output to Port D bit 2
ld PORTB, 6 ; Read Port B bit 6 (ICSP pin 5)
out PORTD, 1 ; Output to Port D bit 1
ld_not PORTB, 0 ; Read Port B bit 0 inverted (SW1)
out PORTD, 0 ; Output to Port D bit 0
endp ; End of PLC program
Listing 1.5. Controlling up to four inputs using the PICkit 2 Debug Express
(Lst1_5.asm)
programmer to your PC via the sup-
plied serial cable and then download
and execute the program. When the
program is executed, pressing a switch
CONNECTED TO THE ÚRST TWO BITS OF 0ORT
A should cause the corresponding bit
of Port B to be activated, as shown in
Fig.1.5.
If you have access to the Proteus
VSM software then you use this to load
the ‘PIC16F627.DSN’ simulation and
then follow the procedure described
earlier to load and execute the program
of Listing 1.4.
Surprisingly, it is also possible to
develop similarly complex programs
for the PICkit 2 Debug Express board,
despite the fact that the PCB is limited
to a single physical input switch! The
trick in this case is to use the PICkit 2
Logic Tool application to control up to
three additional digital input signals
via the In Circuit Serial Programming
(ICSP) interface, which links the ‘black
box’ to the PIC16F887 PCB. When not
being used to download programs,
the Logic tool allows inputs RE3, RB7
and RB6 to be controlled by activating
pins 1, 4 and 5 of the ICSP interface
respectively.
To see this in action for yourself,
begin by assembling the program of
Listing 1.5, and then download the
RESULTING MACHINE CODE ÚLE TO THE
PIC16F887 in the normal way.
Next, enable power to the PCB by
clicking the On check-box and then
select the Tools Logic Tool option
from the pull-down menu, which will
display the PICkit 2 Logic Tool dialog
of Fig.1.6.
Ensure the Mode option is set to
Logic I/O by clicking the button at the
upper right, and then click the Enable
Our machine code program created
earlier must be logically attached to
the PIC16F887, prior to running the
simulation. To do this, right-click on
component U1 and select the Edit
Properties option from the context
menu to display the Edit Component
dialog. From here, you can click the
YELLOW FOLDER ICON AND BROWSE TO ÚND
THE l,ST?HEXm ÚLE CREATED EARLIER
Close the dialog and then click the Play
button at the lower left of the Proteus
window to run the simulation. You’ll
then be able to click on the input con-
nected to bit 0 of Port B, which should
cause the corresponding bit of Port D
to change (as illustrated by Fig.1.4).
53. 56 Everyday Practical Electronics, November 2009
Teach-In 2010
Fig.1.6. Controlling digital inputs via the PICkit 2 Logic Tool dialog
IO button to allow logic levels to be
directly observed or controlled. Next,
set pins 4 and 5 to be outputs, at which
point you should be able to control the
state of the LEDs connected to outputs
RD0-RD3, with the program of Listing
1.5 running. (Note that Pin 6 in Fig.1.5
IS IDENTIÚED ON THE SCHEMATIC DIAGRAM
as an Auxiliary signal. This pin is not
connected to the PIC16F887 IC, by
default, and so is not used here.)
Using the PICmicro MCU
development board
4HE ÚNAL PIECE OF HARDWARE TO LOOK
at in this installment is the Version 3
PICmicro MCU Development board,
as shown in Fig.1.7.
This comprehensive board is avail-
able from the EPE Readers’ Services,
and is supplied as standard with a
PIC16F88 microcontroller, although
a wide variety of other PICs are also
supported.
The board brings out the inputs
of Port A and the outputs of Port B
via switches and LEDs at the lower
left and lower right respectively. A
16MHz crystal oscillator is supplied
IN A SOCKET AT THE LOWER RIGHT
54. WHICH IS
four times faster than the 4MHz default
used by the PLC software. If you are
PLANNING TO DO SERIOUS WORK WITH THE
PLC software, I’d recommend replac-
ing this with a 4MHz crystal – which
will ensure that time-dependent
programs covered in later parts of
the series run at the correct speed.
)NCIDENTALLY
55. THE 0,# HEADER ÚLE IS
CONÚGURED TO AUTOMATICALLY ENABLE
an internal RC oscillator at 4MHz in
the event that the external oscillator
fails to start.)
A USB cable is supplied as standard,
although the board can also accommo-
date an external DC supply (shown at
the upper left of Fig.1.7). If the board is
powered from the USB cable, then the
PIC must be programmed using ‘low
VOLTAGE PROGRAMMINGm
56. WHICH MAKES
use of Port B, bit 3 (RB3). To use LVP
with the PIC16F88, the upper (RB3)
jumper to the left of the LCD display
must be positioned to the left, as
shown in the image. (Be sure to do this
with the power removed, and be very
careful which jumper you enable, to
avoid damaging the PIC microcon-
troller.)
4WO VERSIONS OF THE HEADER ÚLE
are provided, supporting low volt-
age or high voltage programming
(‘PIC16F88_L.PLC’ and ‘PIC16F88_H.
PLC’ respectively). Listing 1.6 shows
a suitable test program, which also
demonstrates the use of active-low
inputs and outputs, as originally seen
in Table 1.4.
4HE PROGRAM IS ÚRST ASSEMBLED IN
the normal way, by using the MPLAB
IDE. A supplied PIC programming
APPLICATION 000 IS THEN USED TO ÚRST
OPEN THE ASSEMBLED (EX ÚLE AND THEN
transfer it via the USB cable to the
PIC micro. The program will then run
automatically.
A Proteus simulation of the 16F88
microcontroller (PIC16F88.DSN) is
also provided, for those readers with
access to this powerful software.
Operation is the same as that described
earlier – see Fig.1.4 and associated text
for details.
Troubleshooting tips
While operation should be mostly
trouble free, the following trouble-
shooting tips will help you to resolve
ANY ISSUES AS QUICKLY AS POSSIBLE
1.TheMPASMassemblerusedbythe
MPLAB IDE is case sensitive and it is
a requirement that all PLC commands
should be entered in lower case, and
any parameters IN UPPER CASE 4HE ÚRST
STEP IS THEREFORE TO CAREFULLY CHECK THE
listing for typographical errors.
Fig.1.7. Running a simple bit input/output program on the PICmicro MCU
development board
57. Everyday Practical Electronics, November 2009 57
Teach-In 2010
2. Ensure that the relevant include
ÚLE IS IN THE SAME DIRECTORY AS THE
ASSEMBLER SOURCE ÚLE
59. CHECK THAT YOU HAVE SELECTED THE
CORRECT MICROCONTROLLER TYPE
60. PRIOR
TO ATTEMPTING TO ASSEMBLE THE SOURCE
CODE ÚLE
4HE ASSEMBLER CREATES A NUMBER
OF OTHER ÚLES WHICH MAY CONTAIN USEFUL
DIAGNOSTIC INFORMATION )N PARTICULAR
61. AN ERROR ERR ÚLE IS CREATED WITH DETAILS
OF ANY ERRORS
62. AND A LISTING LST ÚLE
WILL CONTAIN FULL DETAILS OF THE SOURCE
CODE
64. PLUS ANY ERRORS
4RY TO KEEP ÚLENAMES AND ÚLE
PATHNAMES SHORT 3OME VERSIONS OF THE
-0!3- ASSEMBLER WILL GIVE AN ERROR IF
THE ÚLENAME PORTION OF THE SOURCE ÚLE
NAME IS LONGER THAN EIGHT CHARACTERS
9OU MAY ALSO GET AN ERROR IF THE FULL
PATHNAME IS LONGER THAN CHARACTERS
; (Low voltage programming version
; with RB3 used as the LVP pin)
ld PORTA, 0 ; Read Port A bit 0
out PORTB, 2 ; Output to Port B bit 2
ld_not PORTA, 1 ; Read Port A bit 1 (inverted)
out PORTB, 5 ; Output to Port B bit 5
ld PORTA, 2 ; Read Port A bit 2
out_not PORTB, 6 ; Output to Port B bit 6 (inverted)
ld_not PORTA, 3 ; Read Port A bit 3 (inverted)
out_not PORTB, 7 ; Output to Port B bit 7 (inverted)
endp ; End of PLC program
Listing1.6.ControllingnormalandinvertedsignalswiththePIC16F88(Lst1_6.asm)
#ONSIDER TEMPORARILY COMMENT-
ING OUT LINES WHICH YOU SUSPECT MAY
BE CAUSING AN ERROR 9OU CAN DO THIS
BY ADDING A SEMICOLON TO THE START
OF THE LINE )T MAY ALSO BE USEFUL TO
TEMPORARILY ADD ADDITIONAL LINES TO
YOUR PROGRAM
66. THE 7ATCH WIN-
DOW MAY PROVIDE
USEFUL DEBUGGING
INFORMATION 7EmLL
LOOK AT THIS 0ROTEUS
FEATURE LATER IN THE
SERIES
Final thoughts
)N THIS ÚRST ARTICLE
WEmVE FOCUSED ON
READING AND CON-
TROLLING INDIVIDUAL
INPUTS AND OUTPUTS
EAR IN MIND THAT
THIS IS ONLY A SMALL
PORTION OF THE AVAILABLE COMMAND SET
67. AND WEmLL BE PROGRESSIVELY INTRODUCING
ADDITIONAL FEATURES OF THE SOFTWARE IN
THE REMAINING ÚVE PARTS OF THE SERIES
7EmVE ALSO DEMONSTRATED THAT THE
SOFTWARE CAN BE USED WITH A VARIETY OF
0)# MICROCONTROLLERS
69. AND EVEN WITH ELECTRONIC
CIRCUIT SIMULATION SOFTWARE
4HE NEXT INSTALLMENT WILL BEGIN BY
USINGLADDERLOGICELEMENTSTOCONSTRUCT
SIMPLE COMBINATIONAL LOGIC CIRCUITS
BASED ON OOLEAN OPERATORS SUCH AS
!.$
77. AND A
PULSED ARMEDDISARMED ,%$
COOL
COMPONENTS
Established in 2004, Cool Components supplies
interesting, useful and powerful electronic
components at excellent prices.
Arduino Boards +
Shields
Fast Update GPS
Modules
Olimex PIC, AVR + ARM
Boards
Serial Bluetooth
Adaptors
Plug-In Media Player
Modules
Serial Controlled
OLED Displays
Iron-On PCB
Fabrication
Servos + Servo
Controllers
WWW.COOLCOMPONENTS.CO.UK
Follow product news on:
twitter.com/coolcomponents
0871 288 7685
We work with manufacturers including Sparkfun,
Olimex, Arduino and many others to bring you
the best from the cutting edge of new electronic
technology.
include 16F88_L.PLC ; Defines PLC instructions
78. Everyday Practical Electronics, December 2009
By Walter Ditch
TEACH-IN 2010
LADDER LOGIC PROGRAMMING
FOR THE PIC MICRO
Part 2: Working with
Combinational and
Sequential Logic
T
HIS is the second instalment of
a six-part series, discussing the
use of ladder logic programming
methods with PIC microcontrollers.
Ladder logic is the fundamental basis
of Programmable Logic Controllers
(PLCs), which are a specialised type
of industrial computer, designed to
be easily programmed by engineers.
Thus, the aim of using ladder logic is
to simplify the development process,
making PIC programming accessible to
the widest possible audience.
You may recall that last month we
discussed the use of ladder diagrams to
graphically represent simple electrical
circuits, and converted these to execut-
able machine code programs for the
PIC micro by using commands such as:
‘ld’(readaninputbit);‘out’(sendresult
toanoutputbit);plustheirnegativelog-
ic counterparts ‘ld_not’ and ‘out_not’
respectively. We saw that a PLC-style
programexecutesbyfollowingarepeat-
ing cycle of reading inputs, performing
calculations and controlling outputs,
known as the scan cycle.
The PLC software itself consisted of
A SERIES OF lHEADER ÚLESm
79. AVAILABLE FOR A
number of common PIC microcontrol-
lers, including the 16F627A, 16F628A,
16F648, PIC16F88 and PIC16F887.
By including the appropriate header
ÚLE INTO OUR SOURCE CODE PROGRAMS
80. WE
were able to use the freely available
MPLAB Integrated Development Envi-
ronment (IDE) to assemble our ladder
logicprogramsintoexecutablemachine
code programs, which could then be
downloaded to a variety of commonly
available PIC development boards.
Hardware demonstrated in Part 1
includedtheVellemanK8048board,Mi-
crochip Direct’s PICkit 2 Debug Express
board, Matrix Multimedia’s PICmicro
MCU Development board, plus Proteus
VSM electronic circuit simulation soft-
ware from Labcenter Electronics.
Moving on
In this second instalment, we’ll
continue our tour of ladder logic by
looking at:
Creation of repeating waveforms
by using ‘oscillators’
Combining inputs using simple
combinational logic operators (AND
and OR)
Availability of other logical func-
tions (NOT, NAND, NOR, XOR, and
XNOR)
Using internal memory locations
(auxiliary relays) to hold intermedi-
ate results and to solve complex logic
networks
Creationoflatched(stored)outputs
to capture momentary input signals,
including the provision of set and reset
inputs outputs.
We’ll then use these concepts to de-
velop a simple and extendable alarm
circuit, using just a few lines of code,
and suitable as the basis of either a
car alarm or burglar alarm. Features
will include multiple input sensors,
a latched alarm status output, and a
pulsed armed/disarmed LED.
Simple systems
The above concepts will be drawn
together to create a number of simple
BUTUSEFULSYSTEMS
81. INCLUDINGAÛASHING
‘system armed’ indicator, plus a simple
alarm circuit. These simple building
blocks may be used as the basis of a
wide variety of more complex systems,
with potential applications being
mainly limited by your imagination.
The article concludes by discussing
the PLC software’s internal operation
in a little more detail. This knowledge
willproveusefulwhendebuggingyour
own programs, or should you decide to
modify or extend the PLC software to
suit your own purposes.
All program listings for this article
are available from the Library Project
Code section of the Everyday Practical
Electronics website (http://www.epe
mag.com/ 9OUmLL ALSO NEED THE ÚLES
from Part 1 – particularly the various
0)# HEADER ÚLES q SO )mD SUGGEST THAT
YOU lUNZIPm ALL ÚLES INTO A SINGLE FOLDER
Also, make sure you have installed
82. Everyday Practical Electronics, December 2009
the freely available MPLAB
IDE software, which will be
needed to actually assemble
the example programs. And
of course, in order to actually
test the programs, you will
need a suitable PIC develop-
ment board or simulation
software.
Creating repeating waveforms
by using oscillator bits
The PLC software provides two 8-bit
registers, OSCH and OSCL, which
contain a total of 16 oscillators, with
periodic times ranging from 512Ps to
16.77 seconds, based on the default
clock frequency of 4MHz. Available
periodic times and frequencies are
shown in Table 2.1.
is important to also be aware that they
are also used internally as time refer-
ences by several other PLC commands
yet to be considered, including timers
and PWM (pulse width modulated)
outputs.Forthisreason,theuseofadif-
ferent clock frequency to the assumed
value of 4MHz is likely to cause time-
critical programs to run correspond-
ingly faster or slower.
Simple combinational logic
functions
Simple switch-based and ladder
logic circuits may easily be developed
to implement Boolean logic functions
such as AND and OR, as shown in
Fig.2.1.
Two or more switches in series cre-
ates an AND function, since all input
contacts must be simultaneously
closed to activate the output device (or
output coil). Similarly, parallel switch
contacts will provide a logical OR ar-
rangement, with one or more closed
contacts creating a route for the power
TO ÛOW ALONG THE RUNG
83. THUS ACTIVATING
the output device.
Notice in Fig.2.1 that all inputs and
outputs have been labelled, thus it is
possible to state the logical operation
of the upper and lower systems in
Fig.2.1 as:
‘LAMP = A AND B’, (switches in
series), and
‘LAMP = A OR B’ (switches in
parallel).
The example program of Listing
2.2 shows a possible coding for these
logical operations, based on the 16F88
microcontroller.
In this case, the output on Port B bit
0 is generated by ANDing the lower
two input bits on Port A, while Port B
bit 1 is the result of ORing bits 2 and 3
of Port A. This method is extendable,
simply add successive logical opera-
tors in order to increase the number
of inputs. Also, note that NAND or
NOR operators may easily be created
by replacing the ‘out’ instruction with
its negative logic equivalent ‘out_not’.
A simple application which com-
bines oscillators with logic functions
Waveform production
OR THE BENEÚT OF INQUISITIVE READERS
84. this section explains how the oscilla-
tor waveforms are produced, and also
covers the derivation of the periodic
times of Table 2.1. (This is not essential
reading, so you can skip this and come
back to it later.)
Recall from Part 1 that the PLC soft-
ware assumes an oscillator frequency
of4MHz.Thissignalisusedtogenerate
a number of other waveforms, includ-
26+
+LJK )UHTXHQF 2VFLOODWRUV
86. %LW SRVLWLRQ 3HULRGLF 7LPH)UHTXHQF %LW 3RVLWLRQ 3HULRGLF 7LPH)UHTXHQF
0
1
3
6
7
ȝV N+]
PV +]
PV +]
PV +]
PV +]
PV +]
PV +]
PV +]
0
1
3
6
7
PV +]
PV +]
PV +]
V +]
V +]
V +]
8.389 s / 0.119 Hz
16.77 s / 0.06 Hz
Table 2.1. Square wave signals available from the OSCH and OSCL registers
An obvious application of these
SIGNALS IS TO CREATE A ÛASHING OUTPUT
using an LED. All that is needed is
to load the required oscillator bit and
then send it to the desired output port.
This is illustrated by the example of
Listing 2.1, which is suitable for use
either with the PICkit 2 Debug Express
board, or with Proteus VSM electronic
simulation software.
Note: The examples in this series
are written for a variety of PIC mi-
CROCONTROLLERS
87. IN ORDER TO REÛECT THE
wide range of devices commonly
available. You can easily adapt any
of the programs in this series to
work with other supported PIC mi-
CROCONTROLLERS q JUST MODIFY THE ÚRST
line to load the appropriate header
ÚLE
88. AND THEN CHANGE THE IDENTITY OF
input and output port bits to suit
those available. Use the information
previously given in Part 1 as a guide
(see Table 1.2 and associated text for
more details).
In the next section, we’ll see how
oscillators may be usefully combined
with simple Boolean logic functions,
SO THAT AN OUTPUT ÛASHES ONLY WHEN A
predetermined condition is true.
ing four non-overlapping (quadrature)
1MHz waveforms (Q1, Q2, Q3, Q4) and
also a basic 1MHz square waveform,
AS MAY BE CONÚRMED BY STUDYING THE
appropriate PIC data sheet. The PLC
software uses this 1MHz square wave
signal to continuously increment an
8-bit timer register (Timer0, also re-
ferred to as OSCH here), but using a
1:256 prescaler (frequency divider).
Thus, the OSCH register increments
once every 256Ps.
A 0 1 transition followed by a 1 0
transition is required to produce one
complete square waveform, resulting
in the stated periodic time of 512Ps
for bit 0 of OSCH. Periodic times of
subsequent bits are derived by repeat-
edly doubling this initial value (and
frequencies are, of course, calculated
as the reciprocal of periodic times.)
The PLC software uses a Timer0
(OSCH) overflow interrupt to incre-
ment the low frequency oscillator
register (OSCL), in effect creating
a 16-bit timer register in software,
from the 8-bit timer provided in
hardware.
These waveforms may be used di-
rectly in user programs. However, it
Listing 2.1. Creating a 2Hz pulsed output (Lst2_1.asm)
89. Everyday Practical Electronics, December 2009
wouldbetoenableapulsedoutputonly
when a key is pressed. A simple exam-
ple is shown in Listing 2.3 – this time
written for for the PIC16F627/627A
microcontroller.
of connecting a virtual oscilloscope
to Port B bit 1 using the Proteus VSM
software.
As can be seen, the measured peri-
odic time of 530Ps, obtained using the
be ‘seen’ by the PLC software until
its next pass through the scan cycle.)
Other logical operations
It was previously seen from Fig.2.1
that two normally-open switches in
series creates a logical AND function,
while parallel switches provide a logi-
cal OR (inclusive-OR to be precise).
The related exclusive-OR function
provides an output if precisely one of
the inputs is true, which is logically
equivalent to the statement ‘The out-
put is true if (A is true and B is false)
OR (A is false and B is true)’. Listing
2.4 gives an example.
In addition to optionally inverting
the output bit, as previously discussed,
it is also possible to perform logical
operations where one of the input bits
is inverted. The full range of Boolean
logic functions, based on normally-
open or normally-closed input con-
tacts, is shown in Table 2.2.
Using internal memory to
hold intermediate results
While the above methods may be
used to solve simple Boolean logic cir-
cuits, more complex logical problems
may require an alternative technique.
Consider for example the ladder dia-
gram of Fig.2.3.
The trick in this case is to use
standard logical operators to solve
each horizontal ‘rung’ of the lad-
der diagram, writing the result to
a series of auxiliary relays. These
intermediate results may then be
combined using standard logical
commands to calculate the final
output state.
Listing 2.5 demonstrates the use
OF THE LEAST SIGNIÚCANT BIT OF REGISTER
AUX0 to hold the intermediate result
FROM THE ÚRST RUNG
90. THIS BEING LOGI-
cally combined with the result from
THE SECOND RUNG TO PRODUCE THE ÚNAL
output on bit 0 of Port B.
You should now have a good un-
derstanding of the ‘single bit’ combi-
national logic capabilities of the PLC
software. For future reference, it is
worth mentioning that a number of
‘byte oriented’ logical commands are
also available, which will be discussed
later in the series.
The next section demonstrates how
the application of feedback from out-
put to input may be used to create a
simple latch, which is, of course, the
basis of sequential logic.
Fig.2.1. Switch-based and ladder logic versions of Boolean logic functions
Listing 2.2. Simple logical functions (Lst2_2.asm)
Listing2.3.Generatingwaveformsusingoscillatorsandsimplelogic(Lst2_3.asm)
This example demonstrates the
wide range of frequencies available,
with the high frequency signal on Port
B being much too fast to see with the
naked eye. Fig.2.2 shows the result
Proteus VSM simulation, compares
quite well with the predicted value
of 512Ps from Table 2.1. (Some ran-
DOM ÛUCTUATION IS INEVITABLE
92. Everyday Practical Electronics, December 2009
Using feedback to create
latched outputs
Surprisingly, it is possible to read
the state of an output in just the same
way as an input. This allows feedback
to be applied, which in turn enables
the creation of circuits where a mo-
mentary input signal causes an output
to be Set or latched until it is manually
cancelled. Fig.2.4 shows the creation
of a latch circuit using standard ladder
logic commands.
In this case a momentary signal on
the Set input, Port A bit 0, enables
the latch output (commonly referred
to as Q in bistable circuits), which is
connected to Port B bit 0. The key to
understanding this circuit is to notice
from Fig.2.4 that the state of the Q out-
put is also connected in parallel with
the Set input, proving a logical OR
arrangement. Thus, the latch is held
in the on state once the momentary Set
input is removed. The circuit remains
enabled until the normally closed Re-
set input (Port A, 1) is pressed, which
breaks the circuit and resets the latch.
The ladder diagram also contains an
optional second rung which reads the
Q output (Port B bit 0) and generates an
inverted (Not Q) output on Port B bit
1. A program listing is given in Listing
2.6, which is suitable for use with the
PIC16F88 microcontroller.
The PLC software also includes a
dedicated latch command, which pro-
vides an alternative to using separate
ladder logic commands. Fig.2.5 shows
a ladder diagram incorporating the
latch, while Listing 2.7 gives a modi-
ÚED LISTING
93. ALSO BASED ON THE
microcontroller
While the use of the latch command
does reduce the source code by a cou-
ple of lines, the actual machine code
generated is identical in either case.
Which approach to use is therefore a
matter of personal preference.
Fig.2.2. Connecting a virtual scope to the Port B bit 1 output in Proteus VSM
Listing 2.4. The exclusive-OR operator (Lst2_4.asm)
Table 2.2. Single-bit Boolean logic commands
Fig.2.3. A complex logic circuit
requiring a two-stage approach
94. Everyday Practical Electronics, December 2009
Building simple systems
To bring together some of the con-
cepts discussed, let’s begin by creating
A BRIEÛY ÛASHING ,%$ OUTPUT
95. AS MIGHT
be found in the ‘system armed’ output
of an immobiliser circuit. We’ll use
a latch to arm or disarm the circuit,
statements are optional, having the
effect of reducing the pulse width to
1/8 of its initial value.
The program may be executed either
using the appropriate Proteus VSM
simulation (for those readers with ac-
cess to this software), or by using the
Listing 2.5. Using internal relays to solve complex logic circuits (Lst2_5.asm)
The program uses bits 0 to 2 of Port
A as input sensors, and Port A bit 3
as a Reset signal (1 = reset, 0 = system
armed). Notice that the sensor status
automatically becomes the input to the
latch, with the latch output being sent
TO AN ,%$ CONNECTED TO OUTPUT 0/24
bit 0 (this might be a buzzer or sounder
in a real alarm). Momentarily pressing
the switch connected to Port A bit 3
resets the latch, cancelling the alarm.
A possible program for the 16F627
MICROCONTROLLER IS GIVEN IN ,ISTING
Possible enhancements would in-
clude a pulsed alarm output, and the
provision of a ‘system armed’ indica-
tor, similar to that seen previously.
These additions are left as exercises
for the reader.
A further potential development
would be the automatic cancellation
of the alarm after a given period of
time, in order to prevent unnecessary
annoyance due to false triggering.
This enhancement will have to wait
until next month, when timers will
be covered.
Internal operation of the PLC
software
A more detailed understanding of
THE UNDERLYING OPERATION OF THE 0,#
software is useful at this stage, not only
for curiosity’s sake, but also to explain
the types of error messages which will
inevitably be encountered as you begin
to write programs of your own.
!S YOU WILL BE AWARE
96. THE -0,!
)NTEGRATED $EVELOPMENT %NVIRONMENT
)$% USES AN ASSEMBLER TO TRANSFORM
YOUR SOURCE CODE TEXT ÚLE INTO AN
Fig.2.4. Creation of a latched output by
usingstandardladderlogiccommands
Fig.2.5. Using a dedicated latch, rather
than separate ladder logic commands
WITH THE OUTPUT BEING SENT IN THE ÚRST
instance to an auxiliary relay. When
enabled, the output will be made to
ÛASH BY !.$ING WITH A (Z OSCILLA-
tor signal, and the pulse width will
THEN BE REDUCED BY !.$ING TOGETHER
several higher frequency oscillator
BITS ,ISTING SHOWS A POSSIBLE
SOLUTION
97. BASED ON THE 0)#
microcontroller.
)T CAN BE SEEN FROM ,ISTING THAT
THE LATCH USES 0ORT BITS AND AS THE
Set and Reset inputs, with the latch
output being sent initially to auxiliary
relay AUX bit 0. The latched signal
IS MADE TO PULSE AT (Z BY !.$ING
with low frequency oscillator register
/3#, BIT
98. AND IS DISPLAYED BY OUT-
PUTTING TO THE ,%$ CONNECTED TO 0ORT
$ BIT 4HE INTERVENING THREE !.$
Fig.2.6. Ladder diagram for a simple
alarm with three sensors
0)#KIT $EBUG %XPRESS BOARD )N THE
latter case, recall from Part 1 of the se-
RIES THAT YOU CAN USE THE 0)#KIT ,OGIC
Tool to set and reset the bistable. Pin 5
IS CONNECTED TO 0ORT BIT
100. WHILE 0IN 0ORT BIT
acts as Reset. (Slightly confusingly,
YOU NEED TO CONÚGURE THESE TWO PINS
AS OUTPUTS IN THE ,OGIC 4OOL SINCE THEY
are used to drive the corresponding
INPUTS ON THE 0)#
/UR ÚNAL EXAMPLE IS A SIMPLE ALARM
circuit with three sensor inputs and
a latched alarm output. If one or
more of the sensors is momentarily
activated then the alarm will be trig-
gered, and remain in this state until
the alarm is manually cancelled.
The ladder diagram for the alarm is
shown in Fig.2.6.
101. Everyday Practical Electronics, December 2009
executable machine code
program. This powerful
software has a macro facil-
ity, which allows a text
string to be automatically
replaced by a section of
USER
DEÚNED TEXT
102. PRIOR TO
ASSEMBLY 4HE MACRO DEÚNI-
tion may optionally expect
one or more arguments
(text strings), and the user
supplied values will be
automatically inserted into
the output text by the assem-
bler, prior to conversion to
machine code. Consider the
implementation of the ‘ld’
instruction as an example,
as shown in Fig.2.7.
As can be seen, the ‘ld’
macro accepts two argu-
ments, ld_arg1 and ld_arg2.
The macro substitution
causes the original source
code line to be replaced
by three lines of assembly
language. It is important to
be aware that any assembler
errors are likely to relate to
the source code after the
macro substitution, which
does admittedly make the
debugging process a little
MORE DIFÚCULT
Notice that the above
section of code results in
the logic level present on
the input port being placed
INTO THE LEAST SIGNIÚCANT BIT
of the (LSB) Working regis-
ter (W), which is actually a
general feature of the PLC
software. The correspond-
ing ‘out’ instruction, for
example, simply takes
WHATEVER IT ÚNDS IN THE ,3
of the W register and sends
it to the selected output
PORT
103. AS MAY BE CONÚRMED
by examining the appro-
PRIATE HEADER ÚLE IN A TEXT
editor such as Windows
Notepad.
An interesting observa-
tion at this stage relates to
the ‘endp’ or end program
PLC instruction, which is of
course, yet another macro.
Anexaminationoftheheader
ÚLE SHOWS THAT THIS IS SIMPLY
a jump instruction, which
forcesthePLCprogramtorun
Listing 2.6. Creating a self-latching circuit by reading the state of an output (Lst2_6.asm)
Listing 2. 7. Using the latch command (Lst2_7.asm)
,ISTINGªª#REATINGªAª@SYSTEMªARMED ªmASHINGªOUTPUTª ,ST?ASM
Listing 2.9. A simple alarm program (Lst2_9.asm)
104. Everyday Practical Electronics, December 2009
continuously–thisbeingthebasisofthe
PLC’s repeating scan cycle.
An obvious conclusion based on the
above macro substitution is that any
machine code programs are likely to
be considerably larger than the source
code might suggest. Thus, the main
advantage of the ladder logic approach
IS IN SIMPLIÚCATION OF THE DESIGN PROC-
ess, rather than reduction in code size.
Summary and next steps
This second part of the series began
BY CONSIDERING THE CREATION OF ÛASHING
outputsofawiderangeoffrequenciesby
using oscillator bits. We also looked at
single-bitcombinationallogicfunctions,
including AND, OR and Exclusive-OR,
and discussed the potential incorpora-
tion of inverted inputs and outputs
(NAND and NOR for example). More
complex logical circuits were solved by
use of internal storage (auxiliary relays)
to hold intermediate results. We then
used feedback from outputs in order
to create simple self-latching circuits
(simple sequential logic) and combined
THESE CONCEPTS TO CREATE A SIMPLE ÛASH-
ing ‘system armed’ warning light and an
alarm circuit.
Wealsodiscussedthemacrosubstitu-
tion method used by the PLC software,
AND SAW THAT THE ÚNAL MACHINE CODE
programwillbeconsiderablylargerthan
the source code would suggest.
Hopefully, the power of ladder logic
as a design tool has been in part demon-
strated by the fact that a simple burglar
alarm system could be created in ap-
PROXIMATELY ÚVE LINES OF SOURCE CODE
(as seen in Listing 2.9), and without any
need to delve into the internal architec-
ture of the chosen PIC microcontroller.
The next part of the series will con-
tinue the tour of the sequential logic ca-
pabilitiesofthePLCsoftware,bylooking
at timers and shift registers. The use of
timers will enable an action to be per-
formed for a given period of time, while
shift registers will make it easy to create
simple running light displays.
Fig.2.7. Macro substitution, as used by the PLC software’s ‘ld’ instruction
Please add £2.75 pp per order. Prices include UK VAT.
See website for overseas prices.
Special Offer prices for limited period or while stocks last.
Peak Electronic Design Ltd, West Road House, West Road,
Buxton, Derbyshire, SK17 6HF.
tel. 01298 70012 www.peakelec.co.uk sales@peakelec.co.uk
Measure capacitance and ESR!
Capacitance from 1uF to 22,000uF
ESR from 0.01 ohms to 20 ohms
Battery included + Gold plated croc clips
This new model of the famous offers
all the great features of the ESR60 but with
extended measurement range and audible alerts.
Atlas ESR
Atlas ESR PlusThis is the !
The New Atlas ESR Plus, Model ESR70
Atlas SCR - Model SCR100 Atlas ESR - Model ESR60
£89 inc VAT
£75 inc VAT
£79 inc VAT
Passive component analyser.
Automatically identify and measure
inductors, capacitors and resistors.
Auto frequency selection.
Removable probes.
1uH - 10H
1pF - 10,000uF
1 Ohms - 2M
Atlas LCR - Model LCR40
£79 inc VAT
NEW MODEL
Special Offer!
Includes the Atlas LCR Passive Component
Analyser (model LCR40), Atlas DCA
Semiconductor Analyser (model DCA55),
premium padded carry case and user guides.
Complete with extra spare battery.
You’re ready to go!
Atlas Star Pack (LCR/DCA)
£125 inc VAT
Ideal Gift and Money Saving too!
This pack saves you £20
Connect Triacs or Thyristors any way round.
Auto part identification and pinout display.
Categorises gate from 100uA to 100mA.
Load conditions regulated at 12V, 100mA,
even for a dying battery.
Measures gate voltage drop.
Long life alkaline battery supplied.
Supplied with premium probes.
electronic design ltd
Christmas gift ideas...
Capacitance from 1uF to 22,000uF.
ESR from 0.01 ohms to 40 ohms.
Great for ESR and low resistance
measurements (short tracing etc).
Automatic controlled discharge function.
Audible Alerts (for good ESR, poor ESR,
open circuit and more).
Gold plated croc clips.
User Guide and Battery included.
was £97 was £87
Atlas DCA - Model DCA55
£55 inc VAT
Darlingtons
MOSFETs
Diodes
Transistors
LEDs
and more...
The famous Peak Atlas, now with
fitted premium probes. Just connect any way
round to identify the type of
semiconductor, pinout and
lots of parameters too.
Complete with battery,
user guide and probes.
Look! New Probes.
Reduced Price!
...and if you change your mind after Christmas then no worries,
you can have an exchange or refund without question.
“ “
105. HandsOn Technology
http://www.handsontec.com
ISP to ICP Programming Bridge: HT-ICP200
In-Circuit-Programming (ICP) for P89LPC900
Series of 8051 Flash Controllers. ICP uses a
serial shift protocol that requires 5 pins to
program: PCL, PDA, Reset, VDD and VSS.
ICP is different from ISP (In System
Programming) because it is done completely
by the microcontroller’s hardware and does
not require a boot loader.
Program whole series of P89LPC900
µController from NXP Semiconductors…
USB-RS232 Interface Card: HT-MP213
A compact solution for missing ports…
Thanks to a special integrated circuit from Silicon
Laboratories, computer peripherals with an RS232
interface are easily connected to a USB port. This
simple solution is ideal if a peripheral does not have a
USB port, your notebook PC has no free RS232 port
available, or none at all !
Classic P89C51 Development/Programmer Board: HT-MC-02
HT-MC-02 is an ideal platform for small to
medium scale embedded systems
development and quick 8051 embedded
design prototyping.
HT-MC-02 can be used as stand-alone
8051 C
Flash programmer or as a development,
prototyping, industry and educational
platform.
For professional, hobbyists…
106. 42 Everyday Practical Electronics, January 2010
Teach-In 2010
By Walter Ditch
TEACH-IN 2010
LADDER LOGIC PROGRAMMING
FOR THE PIC MICRO
Part 3: Timers and Shift
Registers
P
ART three of this series on
ladder logic (PLC-style) pro-
gramming for the PIC micro
continues the tour of sequential logic
by looking at timers and shift registers.
This builds upon previous coverage of
input/output commands, oscillators,
combinational logic and self-latching
circuits, allowing an increasingly wide
variety of systems to be developed.
Timers often prove useful when
building ladder-logic-based systems,
making it easy to add time delays and
timed outputs. For example, delaying
AN ACTION FOR A SPECIÚC INTERVAL AN ON
delay timer) or performing a task for a
given period of time (a pulsed timer
output).Timerapplications considered
here will include an automatic alarm
timer and a switch de-bounce circuit.
Shift registers
Shift registers are also valuable,
allowing a binary pattern held in a
register to be shifted to the left or right.
A typical shift register application
would be the creation of a moving
light display, although they have many
other uses.
The present article will also delve
into the PLC software’s use of internal
memory (registers). This knowledge
mayberequiredwhenwritingprograms,
andoftenprovesusefulwhendebugging
ladder logic software applications. For
example, the internal state of a timer or
counter is normally only visible to the
PROGRAMMER AS A SINGLE ÚNISHEDNOT
ÚNISHEDSTATUSBIT
107. BUTTHEINTERNALCOUNT
valueisalsoavailableasabytevalue–if
you know where to look.
In passing, a few of the PLC soft-
ware’s byte processing commands will
be introduced, these being used to sim-
plify the coding of some of the example
programs. A byte I/O command, for
example, will be used to display the
internal content of a shift register on
a chosen output port. We’ll also make
use of a byte comparison command to
simplify the coding of a rudimentary
‘KnightRider’ style display.
Coverage of the sequential logic
capabilities of the PLC software will
continue next month with the intro-
duction of counters and pulse-width-
modulated (PWM) signals.
As discussed previously, all pro-
gram listings for this article are avail-
able from the Library Project Code
section of the Everyday Practical
Electronics website (www.epemag.
com). It is suggested that you copy
THE ÚLES FROM EACH PART OF THE SERIES
into a single folder on your com-
puter, which will ensure you have
EASY ACCESS TO THE 0,# HEADER ÚLES
supplied with Part 1. You should
also have installed the MPLAB IDE
software, and of course you will need
a suitable PIC development board or
simulation software in order to actu-
ally try out your programs. Please see
earlier articles for further details of
the development process, supported
PIC microcontrollers, and associated
hardware and software.
Also, remember that the example
programs may easily be converted to
run on any of the supported PIC micro-
CONTROLLERS 4O DO THIS
109. AND THEN CHANGE
input and output port assignments to
suit those available with the chosen
microcontroller.
Using low speed timers
So far, most of the programs consid-
ered have either produced an output
IF A SPECIÚC CONDITION IS TRUE AT THAT
instant (combinational logic), or have
latched a momentary input signal (sim-
ple sequential logic). This has allowed
the development of some useful ap-
plications, including the simple alarm
circuit of Listing 2.9, as seen in Part 2.
A useful addition to this circuit
would be the use of a timer to cancel
the alarm after a period of inactivity.
4O THAT END
111. AND THEN USE
a timer with a simple alarm circuit.
The PLC software provides up to
16 built-in timers, eight of which
are ‘low speed’, with the remainder
112. Everyday Practical Electronics, January 2010 43
Teach-In 2010
An important difference between
a timer and a latch is that the en-
able input needs to be continuously
applied, in order to ‘enable’ the timer
to count. If a momentary enable input
is required, then this should be used
TO ÚRST SET A LATCH
113. WITH THE LATCHED
output enabling the timer. A typical
example would be the addition of a
timeout feature to the alarm circuit
previously considered in Part 2, List-
ING ! POSSIBLE MODIÚED PROGRAM
is given in Listing 3.2, based on the
PIC16F627/627A microcontroller.
Considering the program opera-
tion, it can be seen that Port A bits
0-2 act as three separate input sen-
sors. The combined sensor status is
stored temporarily in auxiliary relay
Begin counting
An enable signal derived from
Port A bit 0 causes the timer to begin
COUNTING 4HE TIMER IS PRECONÚGURED
WITH A ÚNAL VALUE IN THE RANGE OF TO
255, which allows time delays of up
to 255 seconds to be achieved. The
timer’s status bit becomes set after the
time period has expired. Removing
the enable bit resets the timer to its
initial value and clears the output bit
of the timer. Thus, the timer has three
possible states.
1. Reset (enable input = 0, status
output = 0)
2. Timer in progress (enable input
= 1, status output = 0)
4IMER ÚNISHED ENABLE
114. STATUS
= 1)
Fig.3.1. Using a low-speed timer to
GIVEªAªlVE
SECONDªDELAY
being ‘high speed’. For time delays
in the range 4ms to 1
second, you can use a
high-speed timer, while
longer delays, in the
range 1 to 255 seconds,
may be achieved with a
low-speed timer. (Even
longer delays are pos-
sible by using ‘custom
timer’ circuits, as will be
seen in Part 4.)
The creation of a sim-
ple time delay using
a low-speed timer is
shown in the ladder
diagram of Fig.3.1 above.
This example provides
A ÚVE
SECOND TIME DELAY
(an on-delay timer), with
the timer’s output bit
TIML bit 0, going high
five seconds after the
input bit PORTA bit 0.
An equivalent program,
based on the PIC16F88
microcontroller, is given
in Listing 3.1
4HE ÚRST ARGUMENT SUP-
plied to the low-speed
timer command ‘timl’ is
thetimernumber,whichis
intherange0to7.Thecor-
responding bit of register
TIML(0-7)holdsthestatus
bitforfortheselectedlow-
speed timer. (Thus, TIML
bit0holdsthestatusbitfor
low-speed timer 0, and so
on).RecallalsofromPart1,
that PLC command names
arelowercase(timl),while
register names are upper
case (TIML).
include 16F88_L.PLC ; Defines PLC instructions
; (Low voltage programming enabled)
ld PORTA, 0 ; Read Enable input
timl 0, 05H ; Low Speed Timer 0, final value = 5 seconds
ld TIML, 0 ; Read low speed timer 0 status bit
out PORTB, 0 ; Output timer 0 status to Port B bit 1
endp ; Marks end of PLC program
,ISTINGªª#REATINGªAªlVEªSECONDªDELAYªUSINGªAªLOW
SPEEDªTIMERª ,ST?ASM
; I/O Schedule
; Sensors = Port A bits 0-2 (1 = active)
; Armed/Reset = Port A bit 3
; (1 = armed / 0 = reset)
; Output = Port B bit 0 (1 = triggered)
include 16F627.PLC ; Defines PLC instructions
ld PORTA, 0 ; Load Sensor 1
or PORTA, 1 ; Or with Sensor 2
or PORTA, 2 ; Or with Sensor 3
out AUX0, 0 ; Output Alarm Sensor Status to AUX0, 0
ld AUX0, 0 ; Read Alarm Sensor status (Set input)
latch AUX0, 1, AUX0, 2 ; Latched Alarm Status to AUX0 bit 1
; Reset = AUX0 bit 2
ld AUX0, 1 ; Read Latched Alarm status
timl 0, 0x05 ; Low Speed Timer 0 with 5 second timeout
ld TIML, 0 ; Read Alarm Timeout (1 = timeout reached)
and_not AUX0, 0 ; Don't reset if active (* optional *)
or_not PORTA, 3 ; OR with inverted Arm/Disarm input
; (0 = disabled)
out AUX0, 2 ; Output Reset Alarm signal
ld AUX0, 1 ; Read Latched Alarm signal
and_not TIML, 0 ; Disable if timed out (* optional *)
out PORTB, 0 ; Alarm output to buzzer / indicator
endp ; Marks end of PLC program
,ISTINGªª!DDINGªAªTIMEOUTªTOªAªSIMPLEªALARMª ,ST?ASM
115. 44 Everyday Practical Electronics, January 2010
Teach-In 2010
AUX0 bit 0, which in turn is used as
the Set input to a latch circuit. The
Q output of the latch is sent to bit 1
of register AUX0, while bit 2 of the
same register provides the Reset input
signal to the latch.
Next, the latch output becomes the
INPUT TO A ÚVE
SECOND TIMER
118. but a longer time delay would, of
course, be used in practice). Finally,
an audible or visible alarm output is
generated by copying the latch output
state to an appropriate output port bit
(Port B bit 0 in this example).
Notice that two of the program
lines are marked as ‘optional’ in the
comments at the right. Try adding and
removing these lines to see the differ
ent behaviours of the alarm, following
a timeout. With both lines removed,
the alarm will automatically reset after
A TIME
OUT
119. THUS RE
ENABLING THE ALARM
(suitable for a retail exit barrier alarm,
for example).
However,thisbehaviourmightcause
annoyanceinaresidential
burglar alarm, where a
faulty sensor could cause
THEALARMTOBERE
TRIGGERED
REPEATEDLYAFTEREACHTIME
out. In the latter case,
adding the two optional
LINES HAS THE EFFECT OF ÚRST
preventing a reset while
a sensor remains active,
and second, cancelling
theoutputifthealarmhas
timed out.
High-speed timer
applications
Operation of the eight
HIGH
SPEED TIMERS IS AL
most identical to that al
READYSEENWITHLOW
SPEED
timers, but with three
SIGNIÚCANT DIFFERENCES
120. AS
given below.
4HE lTIMHm HIGH
speed timer) command
is used in place of ‘timl’.
!S WITH LOW
SPEED TIM
ers, remaining command
arguments are the timer
number (0 to 7) followed
BY THE ÚNAL TIMER VALUE IN
the range 1 to 255.
2. The high speed tim
er’s status bit is available
from the appropriate bit of the TIMH
register, with a value of ‘1’ indicat
ING THAT THE TIMER IS ÚNISHED 2ECALL
that low speed timers use the TIML
register.)
3. The timer’s internal count value
increments once every four millisec
onds, giving possible time delays from
4ms to approximately one second.
Note: As you may have already
GUESSED
121. LOW
SPEED AND HIGH
SPEED
timers are actually implemented as
counters, with the input to the coun
ter being derived from an appropriate
oscillator bit. This knowledge will
prove useful in Part 4, when we build
a custom timer.
On the bounce
One problem often encountered
when dealing with input switches is
that of contact bounce. This mechani
cal effect is analogous to dropping a
tennis ball onto a hard surface, and
then watching it bounce several times
before settling.
Exactly the same effect occurs when
the mechanical contacts of a switch are
closed,butwiththetimeforthecontacts
tosettlebeingmeasuredinmilliseconds.
Contact bounce can be particularly
troublesome where an input switch is
directly connected to a counter, with a
single switch press causing the counter
to increment multiple times.
A useful high speed timer applica
tion would be a switch debounce cir
CUIT
122. WITH A TO MS ON
DELAY TIMER
being typically suitable. The output of
THE ON
DELAY TIMER MAY THEN BE USED
as the debounced input signal. Listing
3.3 gives a simple example, written
this time for the PIC16F887 microcon
troller, and making use of a repeating
input waveform being derived from an
oscillator bit.
Pulsed outputs
The timers considered so far have all
BEEN OF THE lON
DELAYm VARIETY )T IS ALSO
possible to produce a pulse output by
MAKING A RELATIVELY SMALL MODIÚCATION
to the program. The trick in this case is
to realise that during the timer period
the enable input will be high, while
at the same time the status bit will be
include 16F887.PLC ; Defines PLC instructions
ld OSCH, 7 ; Read a 15.26 HZ waveform (T = 65.54 ms)
out PORTD, 0 ; Send waveform to Port D bit 0
ld PORTD, 0 ; Read Port D bit 0
; (15.26 Hz waveform = Enable input)
timh 0, 03H ; High Speed Timer 0, final value = 3
; (T = 3 x 4 ms = 12 ms)
ld TIMH, 0 ; Read timer status bit
out PORTD, 1 ; Output debounced signal
endp ; Marks end of PLC program
Listing 3.3. A switch debounce circuit based on a high speed timer (Lst3_3.asm)
include 16F887.PLC ; Defines PLC instructions
ld OSCH, 7 ; Read a 15.26 HZ waveform (T = 65.54 ms)
out PORTD, 0 ; Send waveform to Port D bit 0
ld PORTD, 0 ; Read Port D bit 0
; (15.26 Hz waveform = Enable input)
timh 0, 03H ; High Speed Timer 0, final value = 3
; (T = 3 x 4 ms = 12 ms)
ld TIMH, 0 ; Load timer status bit
out PORTD, 1 ; Output debounced (on-delay) signal
ld OSCH, 7 ; Read high speed timer Enable input
and_not TIMH, 0 ; AND with inverted Status bit
out PORTD, 2 ; Output pulse waveform to Port D bit 2
endp ; Marks end of PLC program
Creation of on-delay and pulse output waveforms (Lst3_4.asm).Listing 3.4. Creation of on-delay and pulse output waveforms (Lst3_4.asm)
123. Everyday Practical Electronics, January 2010 4
Teach-In 2010
outputs respectively. Notice
that, based on the timebase of
5ms per division, the pulse width
is approximately 12ms, which is
in agreement with the delay value
selected in Listing 3.4.
Use of internal storage
and debugging programs
An understanding of the PLC
software’s use of internal memory
is useful when debugging pro-
grams, and may in some cases be
required when actually writing
programs (as will be seen in the
next section).
The PLC software uses a variety of
PIC registers to hold its internal state,
some of which have already been
introduced. Each of these registers
(around 100 in total) holds a single
byte of data. Addresses associated with
these registers, and others yet to be
introduced, can be viewed by opening
ANY OF THE 0,# HEADER ÚLES IN A TEXT
editor. Listing 3.5 shows a short (and
SLIGHTLY SIMPLIÚED EXTRACT
Considering the timers discussed
in the previous section, each of the
low and high frequency timers uses a
dedicated register to hold its internal
COUNT VALUE
124. IN ADDITION TO THE ÚN-
ISHEDNOT ÚNISHED STATUS BITS HELD IN
the TIMH and TIML registers. Under
normal circumstances, the internal
count values are not directly visible
to the programmer. However, it may
be useful to view these registers when
debugging programs – after, of course,
ÚNDING THE APPROPRIATE ADDRESSES FROM
THE HEADER ÚLE
Available debugging options related
to the display of internal registers
include:
1. Adding one or more ‘watch’ com-
mands in an Integrated Development
low. Listing 3.4 shows the creation of
bothon-delayandpulsedoutputs,once
again using a repeating oscillator bit as
the input.
Resulting waveforms are shown in
Fig.3.2, which was produced with the
program of Listing 3.4 running on a
PICkit 2 Debug Ex-
press development
board, and viewed
using a Tektronix
TDS2004B four-
channeldigitalstor-
age oscilloscope.
In this case, the
original wave-
form is shown in
orange, while the
blue and magenta
traces give the on-
delay and pulse
Fig. 3.2.Output waveforms viewed using an
oscilloscope
OSCH E H 01 ; High fre uency oscillator register
A 0 E H 20 ; Internal relay outputs
A 1 E H 21
A 2 E H 22
A 3 E H 23
A 4 E H 24
A 5 E H 25
A 6 E H 26
A 7 E H 27 ; (8 bytes x 8 bits = 64 internal relays)
OSCL E H 28 ; Low fre uency oscillator register
Listing 3.5. A small selection of internal memory used by the PLC software
Fig.3.3. Debugging with the aid of the Watch window in Proteus VSM software
125. 4 Everyday Practical Electronics, January 2010
Teach-In 2010
Notice that the above listing uses
THE l8m PREÚX TO INDICATE A NUMBER
IN HEXADECIMAL FORMAT 4HIS FORMAT
WAS ALSO SEEN WHEN ADDING A WATCH
STATEMENT IN 0ROTEUS 63-
126. IN IG
AND THE ASSOCIATED TEXT 4HE -0,!
)$% ASSEMBLER -0!3- ACCEPTS NU-
MERIC DATA IN A VARIETY OF OTHER NUMBER
BASES RADIXES AND FORMATS
132. WITH THE ÚRST CHAR-
ACTER BEING ACCEPTED IN EITHER UPPER
OR LOWER CASE /NE WHICH IS MOST
SUITABLE DEPENDS ON YOUR PERSONAL
PREFERENCE
133. TOGETHER WITH THE APPLI-
CATION 3EE THE -0!3- ASSEMBLERmS
HELP ÚLE FOR A FULL LIST OF SUPPORTED
NUMBER FORMATS
7EmLL REVISIT THE USE OF BYTE TRANSFER
INSTRUCTIONS IN THE NEXT SECTION
134. WHERE
THEY WILL BE USED WITH SHIFT REGISTER
PROGRAMS TO MAKE THE RESULT VISBLE ON
A BANK OF OUTPUT ,%$S
Shift registers
3HIFT REGISTERS ARE USEFUL CIRCUITS
138. OR
EVEN THE TEMPORARY STORAGE OF PASS
FAIL INFORMATION RE-
LATED TO COMPONENTS
passing along a pro-
DUCTION LINE 4HE IN-
TERNAL STRUCTURE OF A
SIMPLE SHIFT REGISTER
IS SHOWN IN IG
4HIS SIMPLE SHIFT
REGISTER HOLDS A
NUMBER OF DATA BITS
INSIDE AN INTERNAL
WORKING REGISTER
%ACH CLOCK PULSE
CAUSES THE DATA TO
BE SHIFTED ONE PLACE
TO THE RIGHT
139. IN THE
DIRECTION OF THE AR-
ROWS .EW DATA IS SHIFTED IN AT THE LEFT
HAND SIDE SUPPLIED BY AN EXTERNAL
SOURCE
140. WHILE OLD DATA IS SHIFTED OUT
AT THE RIGHT BEING EITHER DISCARDED
OR USED ELSEWHERE !LTHOUGH THIS
SIMPLE SHIFT REGISTER IS UNIDIRECTIONAL
152. IF REQUIRED
4HE SYNTAX OF THE SHIFT REGISTER COM-
MAND HAS THE FOLLOWING GENERAL FORM
shift NUMBER[0-7],
CLOCK_REG, CLOCK_BIT[0-7],
RESET_REG, RESET_BIT[0-7],
DIRECTION_REG, DIRECTION_
BIT[0-7]
Syntax Function
puti TE, RE ISTER Loads an immediate byte value into a destination register (puti = put
immediate).
putr RE 1, RE 2 Copies the content of a source register to a destination register, leaving
the source unaltered (putr = put register).
Table 3.1. Available byte transfer commands
include 16F627.PLC ; Defines PLC instructions
puti 0x0F, A 0 ; Load 0x0F (hex.) into register A 0
putr A 0, PORT ; Copy A 0 register to Port
endp ; Marks end of PLC program
Listing 3.6. Transferring data bytes between registers (Lst3_6.asm)
%NVIRONMENT )$%
153. IN ORDER TO VIEW
THE STATE OF INTERNAL REGISTERS AS THE
PROGRAM IS RUNNING WHICH IS GENERALLY
THE PREFERRED METHOD
154. IF AVAILABLE
5SING A BYTE TRANSFER COMMAND TO
TEMPORARILY COPY AN INTERNAL REGISTER
TO AN OUTPUT PORT
155. ALLOWING ITS STATE TO
BE DIRECTLY VIEWED ON EXTERNALLY CON-
NECTED ,%$S OR
SEGMENT DISPLAYS
Byte transfer
OREXAMPLE
159. RIGHT
CLICK ON THE DISPLAYED 7ATCH WINDOW
AND SELECT THE !DD )TEMS Y !DDRESS
OPTION FROM THE CONTEXT MENU
%NTER THE NAME OF THE REGISTER TO BE
OBSERVED
160. ITS ADDRESS WITH THE PREÚX
l8m INDICATING A HEXADECIMAL NUMBER
AND THE REQUIRED DISPLAY FORMAT IG
SHOWSTHEADDITIONOFAWATCHSTATEMENT
IN ORDER TO VIEW THE INTERNAL COUNT AS-
SOCIATEDWITHLOW
SPEEDTIMER REGISTER
4)-,
161. THIS BEING SUITABLE FOR DEBUG-
GING THE PROGRAM OF ,ISTING
3HOULD A FULL
BLOWN )$% NOT BE AVAIL-
ABLE
162. THEN AN ALTERNATIVE WOULD BE TO
USE A BYTE COPY COMMAND TO COPY THE
REGISTER OF INTEREST TO AN UNUSED OUTPUT
PORT YTE )/ COMMANDS MAY BE USED
EITHER TO LOAD AN IMMEDIATE PROGRAM
SPECIÚED BYTE VALUE INTO A REGISTER
163. OR
TO COPY A BYTE VALUE FROM ONE REGISTER TO
ANOTHER 4ABLE GIVES THE SYNTAX AND
OPERATION OF THE TWO AVAILABLE VARIANTS
4HE USE OF BYTE TRANSFER COMMANDS
IS NOT MANDATORY
164. BUT IS CERTAINLY MUCH
QUICKER THAN THE REPETITIVE COPYING
OF INDIVIDUAL BITS WITH lLDm AND lOUTm
COMMANDS 4HE EXAMPLE OF ,ISTING
ILLUSTRATES JUST HOW EASY IT IS TO LOAD A
BYTEVALUEINTOATEMPORARYREGISTERAND
THEN COPY THE RESULT TO AN OUTPUT PORT
Fig.3.4. A simple shift register
165. Everyday Practical Electronics, January 2010 4
Teach-In 2010
Fig.3.5. Ladder diagram for a simple
shift register program
The trick in this case is to under-
stand exactly how data enters and
exits each shift register. As already
seen, the data input to a shift register is
supplied by the result of the previous
command. Similarly, data shifted out
of one shift register becomes available
to the next command (or is discarded
if unused). Thus, all that is necessary
to cascade multiple shift registers is to
write each shift register command on
successive lines, so the output of one
shift register then becomes the input
to the next.
Use of one or more Watch state-
ments is a useful strategy when debug-
ging programs containing multiple
shift registers, as long as a suitably
equipped IDE is available. You may
then create a watch statement for
each shift register and observe data
rippling through from one working
register to the next. (Note in relation
to Listing 3.8 that registers SHIFT0-
SHIFT2 make use of memory loca-
tions 0x47-0x49.)
Light chaser
4HE ÚNAL EXAMPLE FOR THIS PART OF THE
series involves repeatedly moving a
single illuminated LED to the left and
right of an output port, which is the
basis of the well known KnightRider
display (from the classic TV series of
the same name). This is shown graphi-
cally in Fig.3.6.
A latch is used to control the di-
rection of the shift register, with the
latch being automatically set and
reset as the illuminated bit ‘bounces’
off each side of the output register.
Changing the direction of the shift
register is achieved in software by
linking the latch’s Q output to the
Fig.3.6. Animating a simple ‘KnightRider’ display
A simple shift register application
is shown by the ladder diagram of
Fig.3.5.
The example program uses a 0.25Hz
input signal as the
data input to a shift
register, with the clock
being driven by a 1Hz
signal. This creates an
alternating pattern of
two ones, followed
by two zeros, since
the clock frequency is
four times faster than
that of the data input.
A visible output is
produced by the ‘putr’
command, which
copies the shift reg-
ister’s output register
(SHIFT0)acrosstoPort
B. The equivalent pro-
gramisgiveninListing
3.7, in this case based
on the PIC16F627 mi-
crocontroller.
It is also straight-
forward to link or
‘chain’ multiple shift
registers, as shown in
the example of Listing
3.8, this time written
for the PIC16F887
microcontroller.
include 16F887.PLC ; Defines PLC instructions
ld OSCL, 7 ; Read OSCL bit 7 (Data input)
shift 0, OSCL, 3, PORTA, 0, PORTA, 1
; Shift register 0
; Data in = OSCL bit 7
; Clock = OSCL bit 3
; Reset = Port A bit 0
; Direction = Port A bit 1
shift 1, OSCL, 3, PORTA, 0 , PORTA, 1
; Chained shift register 1
shift 2, OSCL, 3, PORTA, 0 , PORTA, 1
; Chained shift register 2
putr SHIFT0, PORTD ; Copy SHIFT0 working register to Port D
endp ; Marks end of PLC program
Listing 3.8. Chaining multiple shift registers (Lst3_8.asm).Listing 3.8. Chaining multiple shift registers (Lst3_8.asm)
include 16F627.PLC ; Defines PLC instructions
ld OSCL, 5 ; Read OSCL bit 5 (Data input)
shift 0, OSCL, 3, PORTA, 0, PORTA, 1
; Shift register 0
; clock = OSCL bit 3,
; Reset = Port A bit 0,
; Direction = Port A bit 1
putr SHIFT0, PORT ; Copy SHIFT0 working register to Port
endp ; Marks end of PLC program
Listing 3.7. A simple shift register program (Lst3_7.asm)Listing 3.7. A simple shift register program (Lst3_7.asm)
166. 4 Everyday Practical Electronics, January 2010
Teach-In 2010
shift register’s direction input and
then using the state of the left and
right bits of the shift register’s output
register to set and reset the latch,
respectively.
If a single illuminated bit can
somehow be ‘injected’ into the
shift register then this pattern will
continuously shift left and right,
as the latch is set and reset. Thus,
the remaining problem is to inject
an illuminated bit into the working
REGISTER IN THE ÚRST PLACE
In comparison
One answer would be to design
a combinational logic circuit that
would detect the binary pattern ‘0000
0000’ and then automatically inject a
logic 1 into the shift register. This is
quite feasible, but a simpler solution
would be to introduce an appropriate
instruction from the byte comparison
family of commands.
These commands either allow a reg-
ister to be compared with a numeric
value (immediate value), or permit
two registers to be compared, with the
command outputting a logic 1 if the
result of the comparison is true. Avail-
able byte comparison types include:
Greater than (immediate and
register-based – gti and gtr commands)
Greater than or equal (immedi-
ate and register-based – gtei and gter
commands)
Equal (immediate and register-
based – eqi and eqr commands)
Not equal (immediate and register-
based – nei and ner commands)
Less than (immediate and register-
based – lti and ltr commands)
Less than or equal (immediate and
register-based–lteiandltercommands).
Thus, we can use the ‘eqi’ (equal
to an immediate value) command
to inject a logic 1 into the shift
register, should the output register
be empty. The resulting program is
given in Listing 3.9, written for the
PIC16F627/627A microcontroller.
Notice that the program uses bit 0
of Port A as the reset input. This is
ÚNE IF YOU WANT THE ABILITY TO MANU-
ally enable and disable the output
display. If you want to run the shift
register continuously then it is pos-
sible to permanently disable the
reset input, either in hardware or in
software. The hardware approach is
to physically ground the reset input,
although this effectively wastes an
input port bit.
You can also disable the reset input
in software, by replacing the refer-
ence to PORTA, 0 with a reference
which always returns a ‘0’. To this
end, the PLC software provides a reg-
ister with the name ‘LOGIC’, with bit
1 of this register preprogrammed to a
value of ‘1’ and bit 0 of the same reg-
ister containing ‘0’. Thus, replacing
the reference to ‘PORTA, 0’ in Listing
3.9 with ‘LOGIC, 0’ will permanently
disable the reset function.
This is clearly a remarkably com-
pact program, considering the com-
plexity of the task performed. The
main sub-tasks performed by the
program are:
1. Using a latch to control the shift
register direction.
2. Setting and resetting the latch
when a non-zero bit reaches bits 7 and
0 of the shift register’s working register,
respectively.
3. Injecting a logic 1 into the shift
register if the working register is
empty.
4. Copying the shift register’s work-
ing register to an output port, in order
to make it visible.
5. Optionally allowing
the display to be blanked
by resetting the shift
register.
4OCONÚRMYOURUNDER-
standing of the program’s
operation,youshoulden-
sure that you can match
eachoftheabovedescrip-
tive points to the actual
section of code perform-
ing that task.
Note that we’ll be
using a sequencer com-
mand later in the series
to create much more
POWERFUL AND ÛEXIBLE ANIMATED DIS-
plays than those seen so far – and
the associated programs will be even
shorter!
Summary
Part 3 of the series has contin-
ued the tour of the PLC software’s
sequential logic capabilities, focus-
ing on timers and shift registers.
Low-speed and high-speed timers
have been introduced, offering time
delays ranging from four millisec-
onds to approximately 255 seconds.
4HE CONÚGURATION OF ON
DELAY AND
pulse output timers has been dis-
cussed, and these have been applied
in applications as diverse as alarms
and switch debounce circuits.
A range of shift register applica-
tions has also been developed. This
has included the use of single and
chained shift registers, repeating
pattern displays based on oscilla-
tor bit inputs, and even a simple
KnightRider-style display.
We have looked at the use of in-
ternal memory by the PLC software,
and have seen how this knowledge
could be used when debugging PLC
software, either by adding watch
statements, using a suitably capable
IDE, or by adding debugging instruc-
tions to programs. A number of byte
processing instruction categories has
also been introduced and used to sim-
plify the coding of programs (selected
byte transfer and byte comparison
commands were used).
Next month
The next part of the series will in-
troduce further sequential logic capa-
bilities of the PLC software, including
counters and the creation of pulse-
width-modulated (PWM) signals.
include 16F627.PLC ; Defines PLC instructions
; Latch controls shift direction
; (direction changes when 1 reaches end)
ld SHIFT0, 7 ; MSb of working register = Set input
latch A 0, 0, SHIFT0, 0 ; A 0, 0 = output
; LSb of working register = Reset input
e i PORT , 0x00 ; Input a logic-1 if Port = 00000000
shift 0, OSCL, 0, PORTA, 0, A 0, 0
; Shift register 0, clock = OSCL bit 0,
; Reset using Port A bit 0 = 1
; Direction = output of latch
putr SHIFT0, PORT ; Copy SHIFT0 working register to Port
endp ; Marks end of PLC program
Listing 3.9. A simple light chaser program
167. HandsOn Technology is a manufacturer of high
quality educational and professional electronics
kits and modules, uController
development/evaluation boards. Inside you will
find Electronic Kits and fully assembled and
tested Modules for all skill levels. Please check
back with us regularly as we will be adding
many new kits and products to the site in the
near future.
Do you want to stay up to date with electronics
and computer technology? Always looking for
useful hints, tips and interesting offers?
http://www.handsontec.com
Inspiration and goals...
HandsOn Technology provides a multimedia and
interactive platform for everyone interested in
electronics. From beginner to diehard, from student to
lecturer... Information, education, inspiration and
entertainment. Analog and digital; practical and
theoretical; software and hardware...
HandsOn Technology provides Designs, ideas and
solutions for today's engineers and electronics
hobbyists.
Creativity for tomorrow's better living...
HandsOn Technology believes everyone should have the tools, hardware, and resources to play with
cool electronic gadgetry. HandsOn Technology's goal is to get our hands On current technology
and information and pass it on to you! We set out to make finding the parts and information you need
easier, more intuitive, and affordable so you can create your awesome projects. By getting technology
in your hands, we think everyone is better off
We here at HandsOn like to think that we exist in the same group as our customers curious
students, engineers, prototypers, and hobbyists who love to create and share. We are snowboarders
and rock-climbers, painters and musicians, engineers and writers - but we all have one thing in
common...we love electronics! We want to use electronics to make art projects, gadgets, and robots.
We live, eat, and breathe this stuff!!
If you have more questions, go ahead and poke around the website, or send an email to
sales@handsontec.com. And as always, feel free to let your geek shine - around here, we encourage
it...
168. Everyday Practical Electronics, February 2010 49
Teach-In 2010
By Walter Ditch
TEACH-IN 2010
LADDER LOGIC PROGRAMMING
FOR THE PIC MICRO
Part 4: Counters and Pulse-
Width-Modulated Waveforms
P
ART four of this series on ladder
logic (PLC-style) programming
for the PIC micro continues the
tour of sequential logic features by
looking at counters and the genera-
tion of pulse-width-modulated (PWM)
waveforms. (Recall that previous in-
stalments have covered topics includ-
ing inputs and outputs, combinational
logic, oscillators, latches, timers, shift
registers, byte transfer and byte com-
parison commands.)
Thesebuildingblockshavebeenused
toconstructanumberofsimplesystems,
using a programming approach called
ladderlogic,whichhascloseparallelsto
thedesignandconstructionofelectronic
circuits. Thus, the designer (that’s you!)
simply uses ladder logic program state-
ments to connect together the required
electronic building blocks in order to
construct a fully working system.
A machine code program is then
automatically generated for the chosen
PIC microcontroller by using the as-
sembler’s macro substitution feature.
This process has close parallels with
the use of a compiler to convert a high
levellanguageprogram(suchasBASIC,
PascalorC)intomachinecode–includ-
ing, of course, the inevitable increase in
SIZE OF THE ÚNAL MACHINE CODE PROGRAM
It must be admitted that the macro
substitution method used here lacks
some of the sophistication of a true
high level language, such as syntax
checking and meaningful (high level)
error messages. However, electronics
ENTHUSIASTS SHOULD ÚND IT RELATIVELY
easy to write ladder-logic-style pro-
grams, and the source code programs
are normally very concise.
I hope that you will use the tech-
niques presented here in order to adapt
the example programs, and to develop
new ladder logic programs. It really is
most satisfying to see your own design
running on a small piece of silicon, per-
forming tasks exactly as you intended!
Software
Asexplainedpreviously,allprogram
listingsforthisseriesareavailablefrom
theLibraryProjectCodesectionofthe
Everyday Practical Electronics website
(www.epemag.com). You’ll also need
THE HEADER ÚLES SUPPLIED WITH 0ART
169. which should be ‘unzipped’ into a
single folder, together with the sample
ÚLES FROM EACH PART OF THE SERIES
Make sure you have installed the
freely available MPLAB IDE software,
which will be needed to assemble the
example programs. And of course, in
order to actually test the programs, you
will need a suitable PIC development
BOARD
170. ÚTTED WITH ONE OF THE SUPPORTED
PIC microcontroller types, or simula-
tion software such as Proteus VSM
from Labcenter Electronics.
Counter applications
As their name suggests, counters are
used when you need to keep track of
the number of times an event has oc-
curred. In its most basic application,
the counter simply provides a signal
when the predetermined number of
input signals has been detected – as
in a simple unidirectional counter.
Counters are also available which can
count up or down – a bidirectional
counter. Both types of counter main-
tain a running total of the number of
inputs received, in addition to the
MORE BASIC ÚNISHEDNOT ÚNISHED STATUS
output.
Counters may be used as build-
ing blocks in a wide variety of more
complex designs, with motor control
being a typical application. For ex-
ample, linking a counter to a stepper
motor controller will allow a simple
position control system to be created.
It is also possible to vary the speed of
a DC motor by using a counter as the
input to a variable PWM waveform.
In this case, a unidirectional counter
would provide a ‘soft start’ feature, and
a bidirectional counter would allow
the motor speed to be dynamically
increased or decreased.
Unidirectional counters may also
be combined with oscillator signals to
create custom time delays, as will be
seen shortly.
171. 50 Everyday Practical Electronics, February 2010
Teach-In 2010
on a simulator, such as Proteus VSM,
compared to a real PIC development
board – and the difference is no fault of
the simulator. Switch bounce is an un-
wanted effect associationed with real
switches, and can cause the counter
to jump forward by an unpredictable
number of steps for each key-press.
Fortunately, a software-based switch
debounce circuit has already been
developed (refer back to Listing 3.3
and associated text) which can be
easily added, as given in the program
of Listing 4.2.
On-delay timer
You can see that the original input
to the counter (bit 0 of Port A) is now
used to drive an on-delay timer hav-
ing a delay of 12ms. The output of the
on-delay timer (bit 0 of register TIMH)
in turn becomes the input to the coun-
ter, with the remainder of the second
PROGRAM BEING IDENTICAL TO THE ÚRST !
useful exercise is to load the programs
of Listings 4.1 and 4.2 on to a suitable
development board, comparing the ac-
tual number of switch presses required
to set the counter’s Status bit – the
ÚRST MAY VARY AND THE SECOND WILL BE
exactly ten switch presses every time.
As mentioned earlier, it is easy to
create a custom timer by combining
an oscillator waveform and a unidirec-
tional counter. Referring back to Part 2,
Table 2.1, it can be seen that a variety
Unidirectional counters
The PLC software provides up to
eightunidirectional(uponly)counters,
plus a further eight bidirectional
counters. Operation of a basic unidi-
rectionalcounterisquitesimilartothat
alreadyseenwithtimers,whichshould
come as no surprise, since a timer is
little more than a counter with an oscil-
lator hard-wired to its input. A simple
unidirectional counter application is
illustrated by the example of Fig.4.1.
include 16F88_L.PLC ; Defines PLC instructions
; (Low voltage programming enabled)
ld PORTA, 0 ; Read Port A bit 0 (clock input)
ctr 0, 0AH, PORTA, 1 ; Counter 0
; Final value = 10 (0AH),
; Reset = Port A bit 1
ld CTR, 0 ; Read counter 0 status bit (1 = finished)
out PORTB, 0 ; Output counter 0 status to Port B bit 0
endp ; Marks end of PLC program
The previous input value provides
the clock input to the counter, which is
typically the result of a
‘ld’ or ‘ld_not’ instruc-
TION 4HE ÚRST PARAM-
eter actually supplied
to the ‘ctr’ command
is the counter number,
which must be in the
range 0-7. Remaining
PARAMETERS ARE THE ÚNAL
value (1-255), followed
by the reset register and
reset bit (0-7).
Each rising edge of
the Clock input causes
the internal counter
register to increment.
The counter’s Status
bit becomes set when
the counter reaches its
PRE
PROGRAMMED ÚNAL
value, which is in the
range 1-255 (a final
value of 10 is shown in
the example of Fig.4.1).
The counter’s status bit
is available from the
Listing 4.1. Counting pulses using a unidirectional counter (Lst4_1.asm)
equivalent bit of the CTR register (so,
for example, bit 0 of the CTR register
holds the status bit for counter 0).
Both the internal count value and the
status bit are cleared by applying a
logic 1 to the Reset input. So, the Reset
input must be held low during normal
operation of the counter.
The internal count value is not re-
quired in simple counter programs, so
IT IS SUFÚCIENT TO KNOW THAT THE COUNTER
IS EITHER ÚNISHED 3TATUS
173. INTERNAL
count values are available, if required,
fromregistersCTR0-CTR7respectively,
and this running total may be used in
more advanced applications. (An in-
ternal count value will be used later as
partofamotorspeedcontrollersystem,
and further counter-based applications
will be explored in Part 6.)
An equivalent program is given in
Listing 4.1, written for the PIC16F88
microcontroller, and with low volt-
age programming enabled on bit 3 of
Port B.
The program uses the result from the
previous command as the Clock input
(obtained by reading the state of Port A
bit 0), while Port A bit 1 provides the
Reset input to the counter. The Status
bit for counter 0 is loaded from bit 0
of the CTR register and is displayed
on Port B bit 0.
This is one program which may give
a visibly different result when tested
Fig.4.1. A simple counter circuit,
shown in ladder diagram form
include 16F88_L.PLC ; Defines PLC instructions
; (Low voltage programming enabled)
ld PORTA, 0 ; Read Port A bit 0 (Count input)
timh 0, 03H ; High Speed Timer 0, final value = 3
; (T = 3 x 4 ms = 12 ms)
ld TIMH, 0 ; Read timer status bit (debounced input)
ctr 0, 0AH, PORTA, 1 ; Counter 0, final value = 10 (0AH),
; Reset = Port A bit 1
ld CTR, 0 ; Read counter 0 status bit (1 = finished)
out PORTB, 0 ; Output counter 0 status to Port B bit 0
endp ; Marks end of PLC program
Listing 4.2. Adding a debounced switch input to the simple counter application (Lst4_2.asm)