electronics engineering n2no - eeweb...

113
Electronics Engineering N2NO Newbie-2-Novice-Outline Written By: Thomas G (08/2014) Feel free to use: no strings attached (text content only / images respectfully referenced) Table of Contents 1. INTRODUCTION ......................................................................................................................................2 2. SYSTEM CIRCUITS .................................................................................................................................2 2.1 Processors ..........................................................................................................................................3 2.1.1 Market ..........................................................................................................................................3 2.1.2 Instruction Set Architecture (ISA) ..................................................................................4 2.1.3 Micro-Architecture (uArch) ...............................................................................................4 A. Control Unit (CU) ......................................................................................................................5 B. Algorithmic Logic Unit (ALU) ..............................................................................................6 C. Interrupt Requests (IRQ) ......................................................................................................6 D. Bit-Numbering (Endianness) ..............................................................................................6 E. Timing ............................................................................................................................................6 2.2 Memory ................................................................................................................................................6 2.2.1 Market ..........................................................................................................................................6 2.2.2 Hierarchy ....................................................................................................................................6 A. Processor Registers .................................................................................................................7 B. Cache ...............................................................................................................................................7 C. Main Memory ..............................................................................................................................8 D. Secondary Memory ..................................................................................................................8 2.2.3 Management ..............................................................................................................................8 A. Memory Management Unit (MMU) ..................................................................................8 B. Memory Controller (MEMC) ..............................................................................................8 2.3 Peripheral Buses ..............................................................................................................................9 2.3.1 Overview ..................................................................................................................................10 2.3.2 I2C ................................................................................................................................................10 2.3.3 Industry Standard Architecture (ISA) ........................................................................10 2.3.4 General Purpose I/O (GPIO) ...........................................................................................10 2.3.5 Serial Peripheral Interface (SPI) ...................................................................................11 2.3.6 Joint Test Action Group (JTAG) ......................................................................................11 2.3.7 Peripheral Component Interconnect (PCI / PCIe) ................................................11 2.3.8 Serial Communication Interfaces (SCI / RS-XXX) .................................................11 2.3.9 Serializer/Deserializer (SERDES) ................................................................................11 2.3.10 Universal Async Receiver/Transmitter (UART) ..................................................11 2.3.11 Universal Serial Bus (USB) ............................................................................................12 A. Abstraction Layers ................................................................................................................12 B. Functional Layer .....................................................................................................................12 C. Logical Layer .............................................................................................................................13 D. Physical Layer ..........................................................................................................................14 2.3.12 VGA Interface Spec ............................................................................................................15 3. CIRCUIT THEORY ................................................................................................................................15 3.1 Analog ................................................................................................................................................16 3.1.1 Analysis .....................................................................................................................................16 3.1.2 Transistors ...............................................................................................................................17 A. CE Amp (DC Analysis) ..........................................................................................................18 B. Dual Stage NPN PNP Amplifier (AC Analysis) ..........................................................18 3.1.3 Inductors/Coils .....................................................................................................................20 A. Series RL AC Circuits - Low Pass Filtering .................................................................20 3.2 Digital .................................................................................................................................................20 3.2.1 Sequential Logic (RTL) ......................................................................................................20 A.1 Synchronous (In-Sync) ..............................................................................................21 A.2 Asynchronous (Transparent) .................................................................................21 A.3 Implementation ............................................................................................................21 A.3.1 Finite State Machine (FSM) ................................................................................21 A.3.2 Pipe-Lining .................................................................................................................21 3.2.2 Combinational Logic ...........................................................................................................21 A. Algorithmic Circuits ..............................................................................................................21 B. Arithmetic Circuits ................................................................................................................21 B.1 Negative numbers (0x7F) ........................................................................................22 B.2 Adder .................................................................................................................................22 B.3 Boolean Algebra ............................................................................................................22 3.2.3 Logic Gates ...............................................................................................................................22 3.2.4 Discrete Logic .........................................................................................................................23 A. 7400-Series ICs .......................................................................................................................23 3.3 Mixed-Signal ( Analog & Digital ) ..........................................................................................23 4. CIRCUIT DESIGN STEPS ...................................................................................................................23 4.1 Planning ............................................................................................................................................24 4.1.1 System Buses ..........................................................................................................................25 4.1.2 IP-Cores (Re-Use) .................................................................................................................25 4.1.3 Design For Testability (DFT) ...........................................................................................26 4.2 Schematic Entry ............................................................................................................................26 4.3 HDL Entry ........................................................................................................................................27 4.3.1 Verilog ........................................................................................................................................27 A. Module ........................................................................................................................................28 B. Parameter ..................................................................................................................................28 C. Connectors .................................................................................................................................28 D. Bit-Literals .................................................................................................................................28 E. Logic Gates .................................................................................................................................28 F. Algorithmic ................................................................................................................................28 G. Abstraction (Generate, Sub, etc) .....................................................................................28 H. Compiler Directives ..............................................................................................................29 I. Behavioral (Always@) ...........................................................................................................29 I.1 If Else ...................................................................................................................................29 I.2 Case ......................................................................................................................................29 J. Task ................................................................................................................................................29 4.3.2 VHDL Syntax ...........................................................................................................................29 A. Include (LIBRARY / USE) ...................................................................................................29 B. External I/O (ENTITY...GENERIC/PORT) ....................................................................29 C. ARCHITECTURE (Declarations) ......................................................................................30 C.1 COMPONENT .................................................................................................................30 C.2 CONFIGURATION ..........................................................................................................30 D. BEGIN (Structural Design) ................................................................................................31 D.1 <= and => (SIGNAL Assignment) ..........................................................................31 D.2 Logic Gates ......................................................................................................................31 D.3 GENERATE .......................................................................................................................31 D.4 WHEN...ELSE ..................................................................................................................31 D.5 WITH...SELECT ..............................................................................................................31 D.6 Arithmetic & Casting ..................................................................................................31 E. PROCESS (Sequential Design) ..........................................................................................31 E.1 VARIABLE .........................................................................................................................31 E.2 IF...THEN ...........................................................................................................................31 E.3 WAIT ...................................................................................................................................32 E.4 CASE...WHEN ..................................................................................................................32 E.5 FOR...LOOP .......................................................................................................................32 E.6 WHILE...LOOP ................................................................................................................32 F. PACKAGE .....................................................................................................................................33 4.3.3 VHDL Usage .............................................................................................................................33 A. Simulation (TestBench) ......................................................................................................33 B. ClockDiv Circuit ......................................................................................................................34 C. Package Example ....................................................................................................................34 D. Common Errors ......................................................................................................................35 4.4 Synthesis ( Decoding / Compiling ) .....................................................................................35 4.5 Verification .....................................................................................................................................36 4.5.1 Simulation ( SPICE / NetList ) ........................................................................................36 4.6 Target Hardware ( Fitting / Layout ) ..................................................................................37 4.6.1 Integrated Circuits (IC) ......................................................................................................37 A. Data-Base Release (DBR) ...................................................................................................37 B. Wafer Fabrication (FAB) .....................................................................................................38 C. Wafer Sort (Probe) ................................................................................................................38 D. Dice & Packaging ....................................................................................................................39 E. Final / Back-End Test ...........................................................................................................39 4.6.2 Programmable IC(s) ............................................................................................................39 A. Field Programmable Gate Array (FPGA) .....................................................................39 B. Programmable Logic Devices (PLD) .............................................................................41 4.6.3 Printed Circuit Assemblies (PCA) .................................................................................41 5. CIRCUIT DESIGN SOFTWARE (EDA / ECAD) .........................................................................41 5.1 Altera Quartus-II ...........................................................................................................................42 5.1.1 Qsys Designer (SOPC) ........................................................................................................44 5.1.2 Soft Core Processors ...........................................................................................................44 5.1.3 IP-Cores .....................................................................................................................................45 5.1.4 Schematic & HDL Editors .................................................................................................46 5.1.5 Design Simulation ( Debug / Performance ) ...........................................................46 A. Simulation .................................................................................................................................46 B. TimeQuest Timing Analyzer .............................................................................................46 C. ELA – Embedded Logic Analyzer ....................................................................................46 5.1.6 Bugs / Gotchas .......................................................................................................................46 5.2 Xilinx ISE / Vivado .......................................................................................................................47 A. System-Level Tools ................................................................................................................47 B. Circuit-Level Tools .................................................................................................................47 5.3 ModelSim .........................................................................................................................................48

Upload: hoangnhi

Post on 12-Apr-2018

224 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

Electronics Engineering N2NONewbie-2-Novice-Outline

Written By: Thomas G (08/2014) Feel free to use: no strings attached (text content only / images respectfully referenced)

Table of Contents1. INTRODUCTION......................................................................................................................................22. SYSTEM CIRCUITS.................................................................................................................................2

2.1 Processors..........................................................................................................................................32.1.1 Market..........................................................................................................................................32.1.2 Instruction Set Architecture (ISA)..................................................................................42.1.3 Micro-Architecture (uArch)...............................................................................................4

A. Control Unit (CU)......................................................................................................................5B. Algorithmic Logic Unit (ALU)..............................................................................................6C. Interrupt Requests (IRQ)......................................................................................................6D. Bit-Numbering (Endianness)..............................................................................................6E. Timing............................................................................................................................................6

2.2 Memory................................................................................................................................................62.2.1 Market..........................................................................................................................................62.2.2 Hierarchy....................................................................................................................................6

A. Processor Registers.................................................................................................................7B. Cache...............................................................................................................................................7C. Main Memory..............................................................................................................................8D. Secondary Memory..................................................................................................................8

2.2.3 Management..............................................................................................................................8A. Memory Management Unit (MMU)..................................................................................8B. Memory Controller (MEMC) ..............................................................................................8

2.3 Peripheral Buses..............................................................................................................................92.3.1 Overview..................................................................................................................................102.3.2 I2C................................................................................................................................................102.3.3 Industry Standard Architecture (ISA)........................................................................102.3.4 General Purpose I/O (GPIO)...........................................................................................102.3.5 Serial Peripheral Interface (SPI)...................................................................................112.3.6 Joint Test Action Group (JTAG)......................................................................................112.3.7 Peripheral Component Interconnect (PCI / PCIe)................................................112.3.8 Serial Communication Interfaces (SCI / RS-XXX).................................................112.3.9 Serializer/Deserializer (SERDES)................................................................................112.3.10 Universal Async Receiver/Transmitter (UART)..................................................112.3.11 Universal Serial Bus (USB)............................................................................................12

A. Abstraction Layers................................................................................................................12B. Functional Layer.....................................................................................................................12C. Logical Layer.............................................................................................................................13D. Physical Layer..........................................................................................................................14

2.3.12 VGA Interface Spec............................................................................................................153. CIRCUIT THEORY................................................................................................................................15

3.1 Analog................................................................................................................................................163.1.1 Analysis.....................................................................................................................................163.1.2 Transistors...............................................................................................................................17

A. CE Amp (DC Analysis)..........................................................................................................18B. Dual Stage NPN PNP Amplifier (AC Analysis)..........................................................18

3.1.3 Inductors/Coils.....................................................................................................................20A. Series RL AC Circuits - Low Pass Filtering.................................................................20

3.2 Digital.................................................................................................................................................203.2.1 Sequential Logic (RTL)......................................................................................................20

A.1 Synchronous (In-Sync)..............................................................................................21A.2 Asynchronous (Transparent).................................................................................21A.3 Implementation............................................................................................................21A.3.1 Finite State Machine (FSM)................................................................................21A.3.2 Pipe-Lining.................................................................................................................21

3.2.2 Combinational Logic...........................................................................................................21A. Algorithmic Circuits..............................................................................................................21B. Arithmetic Circuits................................................................................................................21

B.1 Negative numbers (0x7F)........................................................................................22B.2 Adder.................................................................................................................................22B.3 Boolean Algebra............................................................................................................22

3.2.3 Logic Gates...............................................................................................................................223.2.4 Discrete Logic.........................................................................................................................23

A. 7400-Series ICs.......................................................................................................................233.3 Mixed-Signal ( Analog & Digital )..........................................................................................23

4. CIRCUIT DESIGN STEPS...................................................................................................................234.1 Planning............................................................................................................................................24

4.1.1 System Buses..........................................................................................................................254.1.2 IP-Cores (Re-Use).................................................................................................................254.1.3 Design For Testability (DFT)...........................................................................................26

4.2 Schematic Entry............................................................................................................................26

4.3 HDL Entry........................................................................................................................................274.3.1 Verilog........................................................................................................................................27

A. Module........................................................................................................................................28B. Parameter..................................................................................................................................28C. Connectors.................................................................................................................................28D. Bit-Literals.................................................................................................................................28E. Logic Gates.................................................................................................................................28F. Algorithmic................................................................................................................................28G. Abstraction (Generate, Sub, etc).....................................................................................28H. Compiler Directives..............................................................................................................29I. Behavioral (Always@)...........................................................................................................29

I.1 If Else...................................................................................................................................29I.2 Case......................................................................................................................................29

J. Task................................................................................................................................................294.3.2 VHDL Syntax...........................................................................................................................29

A. Include (LIBRARY / USE)...................................................................................................29B. External I/O (ENTITY...GENERIC/PORT)....................................................................29C. ARCHITECTURE (Declarations)......................................................................................30

C.1 COMPONENT .................................................................................................................30C.2 CONFIGURATION..........................................................................................................30

D. BEGIN (Structural Design)................................................................................................31D.1 <= and => (SIGNAL Assignment)..........................................................................31D.2 Logic Gates......................................................................................................................31D.3 GENERATE.......................................................................................................................31D.4 WHEN...ELSE..................................................................................................................31D.5 WITH...SELECT..............................................................................................................31D.6 Arithmetic & Casting..................................................................................................31

E. PROCESS (Sequential Design)..........................................................................................31E.1 VARIABLE.........................................................................................................................31E.2 IF...THEN...........................................................................................................................31E.3 WAIT...................................................................................................................................32E.4 CASE...WHEN..................................................................................................................32E.5 FOR...LOOP.......................................................................................................................32E.6 WHILE...LOOP................................................................................................................32

F. PACKAGE.....................................................................................................................................334.3.3 VHDL Usage.............................................................................................................................33

A. Simulation (TestBench)......................................................................................................33B. ClockDiv Circuit......................................................................................................................34C. Package Example....................................................................................................................34D. Common Errors......................................................................................................................35

4.4 Synthesis ( Decoding / Compiling ).....................................................................................354.5 Verification .....................................................................................................................................36

4.5.1 Simulation ( SPICE / NetList )........................................................................................364.6 Target Hardware ( Fitting / Layout )..................................................................................37

4.6.1 Integrated Circuits (IC)......................................................................................................37A. Data-Base Release (DBR)...................................................................................................37B. Wafer Fabrication (FAB).....................................................................................................38C. Wafer Sort (Probe)................................................................................................................38D. Dice & Packaging....................................................................................................................39E. Final / Back-End Test...........................................................................................................39

4.6.2 Programmable IC(s)............................................................................................................39A. Field Programmable Gate Array (FPGA).....................................................................39B. Programmable Logic Devices (PLD).............................................................................41

4.6.3 Printed Circuit Assemblies (PCA).................................................................................415. CIRCUIT DESIGN SOFTWARE (EDA / ECAD).........................................................................41

5.1 Altera Quartus-II...........................................................................................................................425.1.1 Qsys Designer (SOPC)........................................................................................................445.1.2 Soft Core Processors...........................................................................................................445.1.3 IP-Cores.....................................................................................................................................455.1.4 Schematic & HDL Editors.................................................................................................465.1.5 Design Simulation ( Debug / Performance )...........................................................46

A. Simulation.................................................................................................................................46B. TimeQuest Timing Analyzer.............................................................................................46C. ELA – Embedded Logic Analyzer....................................................................................46

5.1.6 Bugs / Gotchas.......................................................................................................................465.2 Xilinx ISE / Vivado.......................................................................................................................47

A. System-Level Tools................................................................................................................47B. Circuit-Level Tools.................................................................................................................47

5.3 ModelSim.........................................................................................................................................48

Page 2: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

5.3.1 Projects.....................................................................................................................................486. SYSTEM SOFTWARE & FIRMWARE............................................................................................48

6.1 Bootloaders and Interfaces.....................................................................................................496.2 Board Support Package (BSP)................................................................................................506.3 Operating Systems (OS)............................................................................................................51

6.3.1 Real Time Operating System (RTOS)..........................................................................516.3.2 OS Memory Management.................................................................................................516.3.3 OS Process Management...................................................................................................516.3.4 DLL/IDL/COM.......................................................................................................................52

A. Component Object Model (COM)....................................................................................536.3.5 MS-DOS......................................................................................................................................54

A. >path............................................................................................................................................546.4 Device Drivers................................................................................................................................54

6.4.1 Device Tree / Driver Stack...............................................................................................566.4.2 Driver Development Kits (DDK)....................................................................................566.4.3 Kernel-Mode Driver Framework (KMDF)................................................................57

A. DriverEntry()...........................................................................................................................58B. EvtDeviceAdd().......................................................................................................................59

B.1 Plug and Play (PnP).....................................................................................................61B.2 Power Management....................................................................................................62B.3 File / Context.................................................................................................................63B.4 Device................................................................................................................................63B.5 Interface...........................................................................................................................63B.6 I/O Handling...................................................................................................................63

C. Callback Functions.................................................................................................................666.4.4 User-Mode Driver Framework (UMDF).....................................................................70

A. Reference...................................................................................................................................706.4.5 Linux...........................................................................................................................................71

A. Overview....................................................................................................................................71B. Code..............................................................................................................................................71

6.5 Programming Concepts.............................................................................................................716.5.1 Compilers/Interpreters....................................................................................................726.5.2 Common Notations..............................................................................................................726.5.3 File Extensions.......................................................................................................................726.5.4 Object Oriented Programming (OOP)........................................................................726.5.5 Toolkits / Libraries..............................................................................................................746.5.6 Language Comparisons.....................................................................................................756.5.7 Data Models (Serialization).............................................................................................75

6.6 Programming Languages..........................................................................................................776.6.1 Assembly Language (ASM)..............................................................................................776.6.2 C & C++......................................................................................................................................78

A. Compilers (GCC/MSVC)......................................................................................................78B. C++................................................................................................................................................79

B.1 Header File......................................................................................................................80

B.2 #Pre-processor directives........................................................................................80B.3 #Include/Using.............................................................................................................80B.4 Namespace/Class/Struct/Union..........................................................................80B.5 Source File.......................................................................................................................81B.6 Details................................................................................................................................82

C. Qt....................................................................................................................................................83D. Makefile......................................................................................................................................83

6.6.3 Java..............................................................................................................................................846.6.4 C#.................................................................................................................................................846.6.5 VB6 & VBA...............................................................................................................................85

A. VB(6&A) – Learned Items..................................................................................................857. INDUSTRIAL CONTROL SYSTEMS (ICS)...................................................................................88

7.1 Allen-Bradley PLC........................................................................................................................887.2 Siemens.............................................................................................................................................897.3 Omron................................................................................................................................................897.4 Ladder-Logic on PLC...................................................................................................................897.5 Human Machine Interface (HMI)..........................................................................................897.6 Instrumentation............................................................................................................................90

8. NETWORKING.......................................................................................................................................918.1 IT Distributed Management (DMTF)..................................................................................918.2 Cellular Networking....................................................................................................................918.3 Area Networking (LAN/WAN)...............................................................................................92

8.3.1 OSI Protocol Model..............................................................................................................95A. Application Layer-7 (HTTP/POP3)...............................................................................95B. Presentation (Layer-6)........................................................................................................96C. Session (Layer-5)...................................................................................................................96D. Transport Layer-4 (TCP/UDP – Data Segment)......................................................96E. Network Layer-3 (IP – Packet Data)..............................................................................96

E.1 Internet Protocol (IP).................................................................................................97E.2 Subnet................................................................................................................................98

F. Data-Link Layer-2 (MAC – Frame Data).......................................................................98G. Physical Layer-1 (PHY – Bit Data)..................................................................................99

G.1 WAN Physical Layer.................................................................................................1008.4 Reference / Tools.......................................................................................................................1008.5 Cisco Systems..............................................................................................................................101

9. RESOURCES.........................................................................................................................................1019.1 Engineering Models..................................................................................................................1019.2 Market Segments.......................................................................................................................102

9.2.1 Market-Specific Standards............................................................................................1029.2.2 General Purpose Standards..........................................................................................103

9.3 Embedded System IDE............................................................................................................1039.4 Symbols..........................................................................................................................................104

9.4.1 Timing Diagrams...............................................................................................................1049.4.2 Schematic Symbols...........................................................................................................104

1. INTRODUCTION

Electronics Engineering Newbie-2-Novice Outline (N2NO) provides a quick outline of subjects related to the electronics engineering field. Topics will be touched upon briefly in a bullet type format. Many finer details will be left up to the reader to investigate at-will using supplied web-links.

✔ Top-Level Terms◌ Architecture - Model = A model that defines structure, components, behavior and/or view of a system.◌ Circuit - Electrical Network = An electrical network of interconnected discrete electronic elements.◌ System - Integrated Whole = A set of interacting independent components forming an integrated whole.

◌ Component - Part or Element = Relative term; A smaller, self-contained part of a larger entity. (e.g. The “parts” of an integrated whole)◌ Interface - Interacting Boundary = The shared boundary across which two separate components exchange information.◌ Protocol - Interface Standards = Predefined standard of rules & regulations that determines “how” an interface exchanges information.◌ Bus - Collective = Term that entails all related connections, software and protocols used to interface components.

✔ See Also◌ Wiki Discrete Components http://en.wikipedia.org/wiki/Electronic_component◌ Wiki Dictionary – Component http://en.wiktionary.org/wiki/component◌ Wiki Interface http://en.wikipedia.org/wiki/Interface_%28computing%29◌ Wiki Bus http://en.wikipedia.org/wiki/Bus_%28computing%29◌ Wiki Protocols http://en.wikipedia.org/wiki/Protocol

2. SYSTEM CIRCUITS

✔ Categories◌ Computer System - Software Operated = Preforms a variety of functions by means of loading a list of execution instructions (ie: Software)◌ Embedded System - Firmware Operated = Dedicated function by means of “fixed-in-hardware” list of execution instructions (ie: Firmware)◌ Consumer Electronics - Circuit Operation = Electronic equipment for everyday use that may or may not contain a Computer or Embedded System.

✔ Implementation Hardware

Page 3: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

◌ SOC - System On a Chip = Hard-Processor, Memory and Peripherals integrated on a single IC ( e.g. Microcontroller )◌ SOPC - System On a Programmable Chip = Soft-Processor, Memory and Peripherals integrated on a single Programmable IC◌ PCA - Printed Circuit Assembly = System implemented on a Printed Circuit Assembly (PCA) like a PC-Motherboard or Daughter Card

✔ System Components◌ Processor - Obeys Instructions = Named circuits that processes instructions as defined by a processor's Instruction Set Architecture (ISA)◌ Memory - Stores Instructions / Data = Electrical signal storage typically used to store the list of instructions and other data◌ Peripheral Buses - Processor IO = Communication (ie: Input/Output(IO)) bus between processor and an Internal/External device◌ System Buses - Internal Processor IO = Embedded Systems can use standard interconnect fabric between internal components

✔ System Software◌ Implementation Categories

▪ Software = Dynamic execution instructions typically for computer system.▪ Firmware = (ie: Embedded Software); Static Instructions that are an essential part to hardware control.

◌ Purpose Categories▪ System Software = Software or Firmware designed to Isolate Application Software from hardware control by providing a standard “platform”.▪ Application Software = Software or Firmware designed for the system user; Including the programming languages used to create system software.

✔ See Also◌ http://en.wikipedia.org/wiki/Computer Covers many details of low/high level programming and Processor architectures◌ http://en.wikipedia.org/wiki/Embedded_system Details including ASIC and FPGA solutions◌ http://en.wikipedia.org/wiki/Electronic_control_unit (Example of an Embedded System / Microcontroller ) Automotive Engine Controller

2.1 Processors

✔ Processor tasks 1. Drive Address Bus 2. Activate Enable 3. Fetch Data from Data Bus 4. Control Unit - receives instructions from RAM 5. Interrupt Handling

✔ Processor Architecture Groups◌ Instruction Set Architecture (ISA) A Processors programming standards (ie: Machine Language; Instruction set / Data handling / Interrupt methods)◌ Micro-Architecture Hardware design; How the processor is designed to perform the tasks in the Instruction Set Architecture (ISA)

✔ See Also◌ Wiki Computer Architectures http://en.wikipedia.org/wiki/Computer_architecture ◌ Wiki List of Architectures http://en.wikipedia.org/wiki/List_of_CPU_architectures◌ Wiki Micro-Architecture http://en.wikipedia.org/wiki/Microarchitecture ◌ YouTube; How a CPU works https://www.youtube.com/watch?v=cNN_tTXABUA -

2.1.1 Market

✔ Market Categories

◌ Purpose/Usage Categories▪ General Purpose = Performs different tasks under the control of software

▫ CPU - Central Processing Unit = CPU can infer box, board or processor chip

▪ Dedicated Purpose = Designed to preform one specific task (ie: embedded system microprocessors)▫ MCU - Micro-controller Unit = Processor + Memory + IO Control on one chip http://en.wikipedia.org/wiki/Microcontroller

Page 4: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

▫ DSP - Digital Signal Processor = Optimized for digital signal processing from analog signals http://en.wikipedia.org/wiki/Digital_signal_processor

▫ GPU - Graphics Processing Unit = Optimized for image and frame buffers for displays http://en.wikipedia.org/wiki/Graphics_processing_unit

◌ Architecture Categories▪ Microprocessor - Discrete components = Processor is a discrete device physically separate from the memory.▪ Microcontroller - Hardware control purpose = Typically any Processor + Memory integrated circuit (IC) centered at controlling hardware.

◌ Implementation Categories▪ HPS - Hard-Core Processor System = Processor circuit is hard-wired▪ SPS - Soft-Core Processor System = Processor circuit is loaded into a Programmable IC

✔ Development Tools◌ Processor Emulators

▪ Wiki list http://en.wikipedia.org/wiki/Comparison_of_platform_virtual_machines▪ Bochs – Emulates x86, x86-64 http://en.wikipedia.org/wiki/Bochs▪ QEMU Emulator – Emulates x86, ARM, SPARC and Power-PC processors http://en.wikipedia.org/wiki/QEMU

◌ Boards▪ Microprocessor SOC Development Boards ( Microprocessor System Design Prototyping )

▫ http://en.wikipedia.org/wiki/Microprocessor_development_board▫ http://en.wikipedia.org/wiki/Single-board_computer▫ MS Windows compatible development boards - http://msdn.microsoft.com/en-US/windows/hardware/dn770216

Name Processor Software Links

Galileo Intel Quark SoC X1000 http://www.intel.com/content/www/us/en/do-it-yourself/galileo-maker-quark-board.html

Intel Shark Cove Intel Atom MS-VS http://www.sharkscove.org/ (Dev Board recommended by MS for driver design)

▪ Microcontroller Development boards ( Microcontroller System Design Prototyping )

✔ Common Processors◌ ARM (by Acorn Computers Ltd) - Power optimized (Fab-less design company). http://www.arm.com/products/processors/◌ Intel

✔ See Also◌ Wiki http://en.wikipedia.org/wiki/Microcontroller ◌ Wiki micro-controller list http://en.wikipedia.org/wiki/List_of_common_microcontrollers◌ Wiki microprocessor list http://en.wikipedia.org/wiki/Category:Lists_of_microprocessors◌ Wiki Soft-Core Processor list http://en.wikipedia.org/wiki/Soft_microprocessor

2.1.2 Instruction Set Architecture (ISA)

✔ Instruction Set Architecture (ISA) - Defines a processors programmable standards (ie: Machine Code / Assembly Language Standards)◌ OpCode - Operation Codes = List of supported Instructions/Commands a processor can execute (e.g. x86 instruction set)◌ Operand - Data = Unit of data or memory location the OpCode applies to◌ IRQ - Interrupt Request = Defines how interrupt requests are processed and activated◌ Access - Memory Architecture = Defines how internal registers/cache memory is accessed and lay-ed out

✔ Application-Specific ISA Models - Specific Purpose processors (e.g. GPU(s), DSP(s))◌ Controller Model = Non-complex; specific purpose; slave processors (e.g. TV receiver board)◌ Data-path Model = Repeatedly preforms same computations on a stream of data (e.g. Digital Signal Processors - DSP's)◌ Finite State Machine w/Data-path (FSMD) = Combination of Controller/Datapath typically implemented on FPGA(s) and/or PLD(s) (e.g. MPEG Decoder)◌ Java Virtual Machine (JVM) = Some processor's ISA can run Java byte-code via hardware (e.g. aJile's aj-80, aj-100)

✔ General-Purpose ISA Models◌ CISC - Complex Instruction Set Computer = Less registers, more clock cycles, more circuitry for heavy-use functions, variable bit-width instructions◌ RISC - Reduced Instruction Set Computer = More registers, less clock cycles, compiler optimization, fixed bit-width instructions (16/32/64-bits)

◌ Examples:▪ CISC Processors; Intel x86, MCS-51/8051

Page 5: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

▪ RISC Processors; ARM (by ARM Holding Co), AVR (by Atmel Technologies), PowerPC, SPARC/LEON, MIPS, Nios

◌ Instruction-Level Parallelism ISA▪ Single Instruction Multiple Data (SIMD) = Processes a single OpCode on multiple Operands▪ Super-scalar Machine = Processes multiple OpCodes per clock cycle through multiple functional components

▪ Very Long Instruction Word (VLIW) = Combining typically single operations into a multi-operational OpCode which later are broken and executed in parallel

✔ See Also◌ Wiki Instruction Set http://en.wikipedia.org/wiki/Instruction_set◌ Wiki List of Instruction Sets http://en.wikipedia.org/wiki/List_of_instruction_sets

2.1.3 Micro-Architecture (uArch)

Micro-Architecture - (ie: Computer Organization) is the “WAY” a given Instruction Set Architecture (ISA) is implemented.

In 1945 John von Neumann published his “First Draft of a Report on the EDVAC” which outlined the first digitally stored-program computer model.

✔ Computer Architecture

◌ Von Neumann Architecture (ie: Princeton Architecture)▪ Shares a common bus for both instructions and data▪ Fetch-execute cycle▪ Commonly referred to as a sequential system

◌ Harvard Architecture▪ Separate storage and signal pathways for instructions and data▪ Can fetch both instruction and data in one cycle▪ An extension to the Von Neumann Architecture

◌ Modified Harvard Architecture▪ Allows instruction memory to carry data▪ Memory cells typically contain “tags” that identify data in instructional memory

✔ See Also◌ http://en.wikipedia.org/wiki/First_Draft_of_a_Report_on_the_EDVAC◌ http://en.wikipedia.org/wiki/Von_Neumann_architecture◌ http://en.wikipedia.org/wiki/Harvard_architecture◌ http://en.wikipedia.org/wiki/Modified_Harvard_architecture◌ http://en.wikipedia.org/wiki/Turing_machine◌ https://www.youtube.com/watch?v=7dg96tefnEU◌ http://en.wikipedia.org/wiki/Microarchitecture

A. Control Unit (CU)

✔ Control Unit (CU) Tasks

1. Generates Timing Signals 2. Reset Vector Offset Address of very first instruction after Power-On / Reset De-Assert 3. Run-Cycle Fetch → Decode (May route to ALU) → Execute the Instructions on Data 4. Program Increment Increments the Instruction Pointer (IP) or Program Counter (PC) register

◌ Controls Data-path Controls the control bus of the data-path using a finite state machine (FSM) and thus is a “Sequential Circuit”◌ Maintains “State History” Which accommodates Interrupts and Exception handling

✔ Containing Circuits◌ Address Generation Unit◌ Branch Prediction Unit Processes branch instructions◌ Sequencer Centralized control of Instruction flow

Page 6: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

◌ Instruction Queue Stores the “next” instruction to be processed and dispatches “next” instruction to the queue to appropriate execution

✔ See Also◌ Wiki Control Unit http://en.wikipedia.org/wiki/Control_unit

B. Algorithmic Logic Unit (ALU)

✔ Preforms◌ Mathematical operations◌ Comparison operations◌ Logic operations

✔ ALU is typically an asynchronous circuit◌ Does not store/transfer; Two inputs → One output◌ Inputs do have bus registers to hold data (Input A, Input B(temp register to store from bus), Input TYpe of OPeration, COmpare Flags - CU, Output f)

C. Interrupt Requests (IRQ)✔ Interrupts Stop standard execution to execute event-based (ie: OnEvent) functions (e.g. hardware issues, resets)

D. Bit-Numbering (Endianness)

✔ 8-bits = 1-byte✔ Word = 16-bits (2-bytes) (0xFFFF)✔ Double Word = 32 – bits (4-bytes) (0xFFFF_FFFF)

✔ Endianness is also called byte-ordering✔ Endianness = Is a BYTE(8-bits) level order (2-digit HEX Swap)

◌ Little-endian = Least significant byte is at byte(0) in Left → Right.◌ Big-endian = Most significant byte is at byte(0) in Left → Right.

✔ Bit-Significance◌ LSB - Least significant bit ◌ MSB - Most significant bit

✔ Timing◌ Time handling makes sure logic-element-1 has evaluated before its output is fed into logic-element-2◌ Register = Is a Flip-Flop circuit that holds it's output state (has memory).

✔ See also: http://en.wikipedia.org/wiki/Bit_numbering

E. Timing

✔ See Also◌ http://en.wikipedia.org/wiki/Processor_register◌ http://computer.howstuffworks.com/microprocessor2.htm◌ http://en.wikipedia.org/wiki/Register_transfer_level◌ Firmware::Assembly Language◌ https://www.youtube.com/watch?v=cNN_tTXABUA◌ http://en.wikipedia.org/wiki/Microarchitecture

2.2 Memory ✔ Market✔ Hierarchy✔ Management

◌ MMU - Memory Management Unit◌ MPU - Memory Protection Unit◌ MEMC - Memory Controller

2.2.1 Market

✔ Random Access Memory (RAM) "volatile"◌ Dynamic random-access memory (DRAM) – Capacitor Storage

▪ SDRAM = Synchronous Dynamic RAM– Requires a refresh clock and synchronous clock (storage cells are made of capacitors)▪ RDRAM▪ DDR-SDRAM = Double data rate▪ OTHERS : FPM-DRAM, EDO-DRAM, VRAM, SGRAM, PSRAM

◌ Static random-access memory (SRAM)▪ SRAM is basically a network of Flip-Flops

✔ Read Only Memory (ROM) / ie: “non-volatile” memory (NVM) / ie: Permanent memory◌ ROM - Read Only Memory◌ MROM - Mask ROM = Manufacturing etching facility etches data into the memory circuit◌ PROM - Programmable ROM = Programmed once; outside the manufacturing etching facility

Page 7: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

◌ OTP - One-Time Programmable = Alias term to PROM◌ EPROM - Erasable PROM = Ultra-violet light to erase selective or the entire memory & electronic programming. (Uses FAMOS transistors)◌ EEPROM - Electronic EPROM = Electronic erase and programming (Uses FLOTOX transistors) – must be erased entirely

✔ See Also◌ http://en.wikipedia.org/wiki/Static_random-access_memory◌ http://en.wikipedia.org/wiki/Semiconductor_memory

2.2.2 Hierarchy

✔ Memory Hierarchy◌ Processor Registers = (ie: Register File) Is the fastest closest memory to store operands that are being frequently used◌ Cache◌ Main Memory◌ Secondary Memory

✔ See Also◌ Wiki Memory Hierarchy http://en.wikipedia.org/wiki/Memory_hierarchy

A. Processor Registers

✔ Register Categories

◌ User-Accessible▪ Data▪ Address▪ GPR - General Purpose Registers▪ Conditional▪ FPR - Floating Point Registers▪ Constant▪ Vector▪ SPR - Special Purpose Registers

▫ Control▫ Status▫ IAP - Instruction Address Pointer▫ Flags - Bit-wise control/status

▪ MTRR - Memory Type Range Registers▪ Shift - Specifically for bit shifting▪ Counter - Specifically for increments or decrements

◌ Internal▪ Instruction▪ MBR - Memory Buffer Register▪ MDR - Memory Data Register▪ MAR - Memory Address Register▪ Memory Data (▪ Memory Address (MAR)▪ Accumulator - (ie: Summation) Stores numeric values Floating Point

◌ Load-Store Model (RAM -> Register)◌ In-line barrel shift-er◌ MMIO = Memory Mapped Input Output - Peripheral control is accessed by vendor implemented memory addresses (ie: Registers)

✔ See Also◌ Wiki Processor Registers http://en.wikipedia.org/wiki/Processor_register◌ Wiki Digital Registers http://en.wikipedia.org/wiki/Category:Digital_registers

B. Cache

✔ Cache◌ Cache Hit Memory data resides in the cache◌ Cache Miss Memory data must be gotten from a higher-level memory source

✔ Cache Schemes

Page 8: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

◌ Direct Mapped Data in cache is located by its associated block address in memory (ie: Tagged)◌ Set Associative Cache is divided into sets where multiple blocks can be placed; Blocks are located according to an index field that maps into a set◌ Full Associative Blocks are placed anywhere in cache and must be located by searching the entire cache memory each time◌ Transfers from main-memory using one-word or multi-word blocks; Blocks contain the data and main memory location (ie: Tags)

✔ Cache Levels◌ L0 Micro-operations cache◌ L1 Separate Instruction/Data Cache◌ L2 Shared Instruction/Data Cache◌ L3 Shared Cache; 6MiB; 100 GB/s◌ L4 Shared Cache; 128Mib; 40GB/s

✔ Reference◌ Wiki CPU Cache http://en.wikipedia.org/wiki/CPU_cache◌ Cache http://en.wikipedia.org/wiki/Cache_%28computing%29

C. Main Memory✔ Main Memory Only implemented “On-Chip” on Micro-Controllers✔ Permanent Memory Only implemented “On-Chip” via Flash on Micro-Controllers

D. Secondary Memory✔ Memory Hardware

◌ Hard Disk Drive◌ Tape Backup◌ Flash Memory

2.2.3 Management

✔ Memory Management Groups◌ Hardware Memory Management - Typically resides in the Processor IC but can reside as a separate IC.◌ OS Memory Management◌ Application Memory Management

✔ Memory Architecture◌ Linear = Memory address arranged 0 → 2^(N-1)◌ Segmented = Memory address arranged with offsets Base Address::Offset

✔ Addressing Architecture◌ Load-Store = Only allows OpCodes on Operands in register memory◌ Register-Memory = Allows OpCodes on both register and other memory locations

✔ Memory Addressing - A Processors ISA defines how the processor “sees” the data (ie: Operand) storage and addressing modes◌ Logical◌ Virtual◌ Physical = Actual (Row,Col) addressing; no encoding/decoding of addresses◌ Memory Map (MM) = Processor/Software treats memory as one large one-dimensional array

▪ Direct Mapping = TAG / CACHE / OFFSET▪ Associative Cache =

✔ See Also◌ http://en.wikipedia.org/wiki/Category:Memory_management

A. Memory Management Unit (MMU)

✔ Cache memory can be behind an MMU or skip the MMU◌ Translation Look-aside Buffer (TLB) Portions of cache allocated as buffers for mapping logical addresses → physical addresses

✔ Supports schemes in translating addresses (The memory scheme is determined by the OS Software – MMUs and OS manage virtual memory)◌ segmentation Dividing logical memory into large variable-size sections◌ paging Dividing logical memory into smaller fixed-sized units◌ both

Page 9: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

✔ MMU is used to allow Direct Memory Access (DMA) where off-chip memory can be accessed directly by slave processors w/o going through the main processor✔ Translates logical addressing into physical addressing (ie: Memory mapping)✔ Handles security, controls cache, bus arbitration (between Processor and Memory) and generates exceptions✔ Security Memory Protection Schemes

◌ Shared, RW, or RO access To various pages and/or segments (If access isn't allowed an interrupt is triggered)◌ Page Fault A page/segment isn't accessible during address translation – In that case secondary memory would need to be used

✔ See Also◌ Wiki Memory Management Unit http://en.wikipedia.org/wiki/Memory_management_unit ◌ Wiki Page Table http://en.wikipedia.org/wiki/Page_table

a) Note:: Some chips don't have Memory-Mapped I/O (have instruction 'OUT' and 'IN') this route is mostly historical. (x86 has it?)

B. Memory Controller (MEMC)✔ Manages/Merges the many “banks” of different type memory

◌ DRAM Controller An MEMC that manages only DRAM type memory◌ Cache Controller An MEMC that manages only Cache type memory◌ Physical addressing◌ Glue-less interface One set of addresses for many different types of memory (Manages/Merges the many “banks” of memory)◌ Synchronizes access◌ Verifies integrity

✔ RAM Address → Data✔ BUS Registers / Latches

◌ Just like RAM but inside CPU (Register has set/enable lines set=save, enable=read) All on CPU BUS.✔ ECC = ECC - Error correction code (Corrects bad bits in memory)✔ Reference

◌ Wiki Memory Controller http://en.wikipedia.org/wiki/Memory_controller

2.3 Peripheral Buses Peripheral Devices and Interconnection Standards can often go hand-in-hand since every peripheral device requires a standard connection bus

✔ Processor I/O Items◌ Transmission Medium Wireless, Wired – Physical item that communications are “routed” on◌ Communication Port What the Transmission Medium connects “to”; In wireless the item that receives the signal◌ Communication Interface Encoding/Decoding Communication Standards between the “Master Processor” and I/O devices or controllers◌ Controller Slave Processor that manages the I/O device◌ Bus Connection between board I/O and “Master Processor”◌ Master Processor Integrated I/O

✔ Processor I/O ↔ Peripheral Buses Categories◌ Networking and Communications I/O Physical Layer of OSI-Model◌ Input Keyboard, Mouse, Remote Control, Voice, Sensors, etc...◌ Graphics and Output I/O Touch Screen, CRT, Printers, LEDs, etc..◌ Storage I/O CD, Magnetic Disk and Tape Controllers◌ Debugging I/O BDM, JTAG, Serial Port, Parallel Port, etc...◌ Real-Time & Miscellaneous I/O Timers/Counters, Analog-to-Digital Converter (ADC), Digital-to-Analog Converter (DAC), switches, etc...

1. Terms a) DDIO – Double data rate I/O = Data is transferred at both the rising and falling edges of a master clock b) LVDS – Low Voltage Differential Signal = Logic signals 1 and 0 are transferred using a “difference” between 2-line voltages c) GSPS – Giga Samples per Second. d) TLP – Transaction Layer Packets (PCIe)

2. How to Find Hardware Interface / Protocol Standards http://en.wikipedia.org/wiki/International_Organization_for_Standardization a) ISO = International Standards Organization – Technical Management Board members is responsible for over 250 technical Committees.) b) ISO/IEC = International Electra-technical Commission – Is a Technical Committee of ISO for electrical, electronic and related technologies. (

http://www.iec.ch/ ) c) JEDEC = Joint Electron Device Engineering Council – Global standards for the microelectronics industry http://www.jedec.org/ d) AEC = Automotive Electronics Council – http://www.aecouncil.com/

e) The organization's headquarters were in Arlington, Virginia. The EIA divided its activities into the following sectors:• ECA – Electronic Components, Assemblies, Equipment & Supplies Association • JEDEC – JEDEC Solid State Technology Association, former Joint Electron Devices Engineering Councils • GEIA – (now part of TechAmerica), Government Electronics and Information Technology Association • TIA – Telecommunications Industry Association • CEA – Consumer Electronics Association

3. List of Common Peripherals a) Discrete IO

• GPIO - General Purpose Input/Output• PIO - Parallel Input/Output• SSD - 7-Segment Display

b) Debugging• JTAG - IEEE standard interface for chip ID activation and for testing/programming.• ISP• ICSP

Page 10: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

• BDM Port• BITP• DP9 Port

c) SCI - Serial Communication Interfaces• RS-232• RS-422• RS-485 and etc...

d) SSCI - Synchronous Serial Communication Interfaces• I2C -• SPI - Serial Peripheral Interface• SSC -• ESSI - Enhanced Synchronous Serial Interface

e) USB - Universal Serial Bus f) Multi Media Cards

• SD Cards• Compact Flash

g) Networks• MAC/PHY - Ethernet Interface• Ethernet• LonWorks

h) Fieldbus• CAN-Bus• LIN-Bus• PROFIBUS

i) Timers• PLL - Phase Lock Loop• Capture/Compare• Time Processing Units

j) Analog-to-Digital (ADC) / Digital-to-Analog (DAC)

✔ See Also◌ http://en.wikipedia.org/wiki/Bus_%28computing%29#Examples_of_internal_computer_buses - List of common External and Internal Bus Standards◌ http://www.xilinx.com/ise/embedded/edk_ip.htm◌ http://www.bottomupcs.com/peripherals.html◌ http://en.wikipedia.org/wiki/List_of_device_bandwidths - Bandwidth of Common Peripheral Buses◌ http://en.wikipedia.org/wiki/Peripheral

2.3.1 Overview✔ Serial Interfaces

◌ Capabilities▪ Simplex Either Sends OR Receives Permanently ▪ Half Duplex Sends OR Receives at one direction at a time▪ Full Duplex Sends AND Receives at the same time (e.g. Twisted Pair)

◌ Synchronization▪ Synchronous Continuous stream at regular intervals (clocked)▪ Asynchronous Intermittent at random intervals (Includes a START/STOP bit signal)

✔ Serial Communication Controller (SCC)✔ Serial Management Controller (SMC)

✔ FIFO Buffer First In – First Out Buffer

✔ Serial links are describe in frequency (cycles per second (Hz))✔ Amount of data that can be carried in a Serial Link is called “Bandwidth”

▪ Bandwidth is measured in the amount of data-bits per second that the serial channel can carry.

2.3.2 I2C

✔ Conditions◌ START = SDA line transitions from HIGH->LOW while SCLK is HIGH◌ STOP = SDA line transitions from LOW->HIGH while SCLK is HIGH

✔ Rules◌ SDA must never change while SCLK is HIGH (Unless marking a Condition change)◌ 8-bits is always transfered at once (followed by 9th bit a read-back ACKnowledge)◌ 1st 8-bits are the SHIP Address or CHIP ID address which is actually 7-bit with 8th bit indicating Read/Write

SDA/SCL in an idle state are required to be pulled high to VDD_IO level. This can be done with either 1K pull-up resistors on the probe-card or using the tester to hold the levels high.

CHIP_ID | 11-1111-1111-22222 0123-4567-|-8901-2345-6789-01234-------------------------------------- |CHIPID| |-16BIT REG ADDR -|1st - 0010-0000-L-0000-0000-0000-00002nd - 0010-0001-L-VVVV-VVVV-VVVV-VVVV | | ^ACK

Page 11: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

| ^Read=1,Write=0 ^t_i2c_st

I2C CLK can run at typically 100KHz (standard) or 400KHz (high-speed)

✔ See Also◌ Spec Sheet @ http://www.i2c-bus.org/fileadmin/ftp/i2c_bus_specification_1995.pdf◌ Wiki @ http://en.wikipedia.org/wiki/I%C2%B2C◌ Nice Tutorial @ http://www.esacademy.com/en/library/technical-articles-and-documents/miscellaneous/i2c-bus.html

2.3.3 Industry Standard Architecture (ISA)

2.3.4 General Purpose I/O (GPIO)

2.3.5 Serial Peripheral Interface (SPI)

Full-Duplex, Master(Initiates data frame)/Slave(Multiple w/Chip Select), 4-wire Serial Bus, often called SSISynchronous Transmission

✔ See Also◌ Wiki http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus (by Motorola)

◌ Full-Duplex, Master(Initiates data frame)/Slave(Multiple w/Chip Select), 4-wire Serial Bus, often called SSI

2.3.6 Joint Test Action Group (JTAG)✔ IEEE 1149.1 Standard Test Access Port and Boundary-Scan ie: Scan Chain STUCK_AT✔ Wiki http://en.wikipedia.org/wiki/JTAG✔ Pins

◌ TDI (Test Data In)◌ TDO (Test Data Out)◌ TCK (Test Clock)◌ TMS (Test Mode Select)◌ TRST (Test Reset) optional.

2.3.7 Peripheral Component Interconnect (PCI / PCIe)

http://www.techfest.com/hardware/bus/pci.htm Specification document http://komposter.com.ua/documents/PCI_Express_Base_Specification_Revision_3.0.pdf

2.3.8 Serial Communication Interfaces (SCI / RS-XXX) 1. SCI = Serial Communication Interfaces (RS-232, RS-422, RS-485)

2.3.9 Serializer/Deserializer (SERDES)✔ SERDES A Pair of functional blocks that convert between serial & parallel in both directions

◌ PISO Parallel In – Serial Out◌ SIPO Serial In – Parallel Out

✔ Reference◌ Wiki SerDes http://en.wikipedia.org/wiki/SerDes

2.3.10 Universal Async Receiver/Transmitter (UART)✔ UART = Universal Asynchronous Receiver/Transmitter) Translates parallel to serial and vice versa

◌ Asynchronous Transfer◌ Full Duplex◌ Based on the 8251 UART Controller◌ Pins

▪ TXDx Transmit Pins▪ RXDx Recieve Pins▪ CDx Carrier Detect Pins▪ CTSx Clear To Send▪ RTS Request To Send Pins

Page 12: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:
Page 13: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

2.3.11 Universal Serial Bus (USB)

✔ USB Flavors (USB = Universal Serial Bus)USB Speed (Name) Host Controller

_ 1.0_ 1.1

Low-Speed(1.5Mbit/s) / Full-Speed(12Mbit/s)Same speeds as 1.0 with added functionality

UHCI = Universal Host Controller Interface by IntelOHCI = Open Host Controller Interface by Others

_ 2.0 High-Speed(480Mbit/s) EHCI = Enhanced Host Controller Interface

_ 3.0 Super-Speed(5Gbit/s) – has more connectors XHCI = eXtensible Host Controller Interface

◌ USB 1.0 released in 1996; USB 1.1 released in 1998 (clarification & improvements only over USB 1.0)◌ Device Controller (DC)◌ On-The-Go (OTG)

▪ A supplement protocol specifically for embedded systems that implements a “switch-in USB Host controller” in a USB device (ie: non-PC USB Host)▪ Typically for products like cell-phones and mobile devices that often need to preform as both a Device and a Host for other devices.

A. Abstraction Layers

Functional Layer (Software)View-point that abstracts (removes) logical & physical layer details[ Client Software ] → >> Pipes >> → [ Device Function Interfaces ]* Pipe = Virtual Communication Channels a) Control Pipes = Bi-directional (Default Control Pipe) b) Data Pipes = Uni-directional “one-way”Each device can contain multiple “pipes” through which the host may communicate with the device.

Logical Layer (Controllers)View-point that abstracts (removes) functional & physical layer details. [ Host ] → [ Pipes ] → [ Device::endpoint(#) ]Client SW → (USBD) → System SW → (HCD) → Device::endpoint(#)

* USBD = USB Driver* HCD = Host Controller Driver* Enumeration = USB Device initialization* Endpoint = Addressable buffer ( holder for to/fro host data )

Physical Layer ( Wire/Bus )View-point of electrical wire/signal connections removing logical & functional.

Host (typically a PC containing a “host controller” & “host/root hub”) - Initiates all communication and polls devices for receivable data. - Communication between host / devices is preformed via data Packets. a) OUT transfer = Host → Device b) IN transfer = Device → Host

* SIE = Serial Interface Engine - used to parse incoming traffic.Compound/Composite Devices have multiple interfaces (e.g. fax, scan, print)

B. Functional Layer✔ Communication duties

◌ Host controls all communications◌ System SW maintains “ownership” of the Default Control Pipe (ie: Endpoint(0))◌ Client SW requests data transfer via I/O Request Packets (IRP) to a pipe.

▪ IRP details are part of the hosts operating system (OS)

✔ Enumeration Process (ie: Device Initialization / Introduction) 1. USB device is connected to a host and drives (D+) or (D-) high 2. Host sends device a Reset (ie: D+/D- held low for 3-ticks 'SE0') 3. Host requests USB device descriptors using the Default Control Pipe (ie: Device(00h)::Endpoint(0h)) 4. Device Responds with it's descriptor information. 5. Host assigns the device a 7-bit address 6. Host uses the newly assigned device address to request device descriptors a 2nd time. (ie: Device(#)::Endpoint(0h)) 7. Device Responds with it's descriptor information. 8. Host locates the device drivers by reading (.INF) file for driver location and loading driver (.SYS) 9. Host selects the appropriate configuration for the device and device is set to a 'configured' state.

✔ Device Descriptors◌ Device Descriptor ( Only 1 per device )

Offset Field Bytes Value Description0 bLength 1 Number Size of the Descriptor in Bytes (18 bytes)1 bDescriptorType 1 Constant Device Descriptor (0x01)2 bcdUSB 2 BCD USB Specification Number which device complies too.4 bDeviceClass 1 Class Class Code (Assigned by USB Org)

If equal to Zero, each interface specifies it’s own class codeIf equal to 0xFF, the class code is vendor specified.Otherwise field is valid Class Code.

5 bDeviceSubClass 1 SubClass Subclass Code (Assigned by USB Org)6 bDeviceProtocol 1 Protocol Protocol Code (Assigned by USB Org)7 bMaxPacketSize 1 Number Maximum Packet Size for Zero Endpoint. Valid Sizes are 8, 16, 32, 648 idVendor 2 ID Vendor ID (Assigned by USB Org)

10 idProduct 2 ID Product ID (Assigned by Manufacturer)12 bcdDevice 2 BCD Device Release Number14 iManufacturer 1 Index Index of Manufacturer String Descriptor15 iProduct 1 Index Index of Product String Descriptor16 iSerialNumber 1 Index Index of Serial Number String Descriptor

Page 14: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

17 bNumConfigurations 1 Integer Number of Possible Configurations

◌ Configuration Descriptor (Only one active at a time – user / driver selects the configuration – typically there is only one)Offset Field Bytes Value Description

0 bLength 1 Number Size of Descriptor in Bytes1 bDescriptorType 1 Constant Configuration Descriptor (0x02)2 wTotalLength 2 Number Total length in bytes of data returned4 bNumInterfaces 1 Number Number of Interfaces5 bConfigurationValue 1 Number Value to use as an argument to select this configuration6 iConfiguration 1 Index Index of String Descriptor describing this configuration7 bmAttributes 1 Bitmap D7 Reserved, set to 1. (USB 1.0 Bus Powered)

D6 Self PoweredD5 Remote WakeupD4..0 Reserved, set to 0.

8 bMaxPower 1 mA Maximum Power Consumption in 2mA units

◌ Interface Descriptors (Function Interfaces – Multiples allowed in a Compound/Composite devices (e.g. fax, scan, print))▪ Each Interface can have alternate settings (ie: Various switchable blocks of endpoint settings)

Offset Field Bytes Value Description0 bLength 1 Number Size of Descriptor in Bytes (9 Bytes)1 bDescriptorType 1 Constant Interface Descriptor (0x04)2 bInterfaceNumber 1 Number Number of Interface3 bAlternateSetting 1 Number Value used to select alternative setting4 bNumEndpoints 1 Number Number of Endpoints used for this interface5 bInterfaceClass 1 Class Class Code (Assigned by USB Org)6 bInterfaceSubClass 1 SubClass Subclass Code (Assigned by USB Org)7 bInterfaceProtocol 1 Protocol Protocol Code (Assigned by USB Org)8 iInterface 1 Index Index of String Descriptor Describing this interface

◌ Endpoint Descriptors

Offset Field Bytes Value Description0 bLength 1 Number Size of Descriptor in Bytes (7 bytes)1 bDescriptorType 1 Constant Endpoint Descriptor (0x05)2 bEndpointAddress 1 Endpoint Endpoint Address

Bits 0..3b Endpoint Number.Bits 4..6b Reserved. Set to ZeroBits 7 Direction 0 = Out, 1 = In (Ignored for Control Endpoints)

3 bmAttributes 1 Bitmap Bits 0..1 Transfer Type 00 = Control01 = Isochronous10 = Bulk11 = Interrupt

Bits 2..7 are reserved. If Isochronous endpoint, Bits 3..2 = Synchronisation Type (Iso Mode)

00 = No Synchonisation01 = Asynchronous10 = Adaptive11 = Synchronous

Bits 5..4 = Usage Type (Iso Mode) 00 = Data Endpoint01 = Feedback Endpoint10 = Explicit Feedback Data Endpoint11 = Reserved

4 wMaxPacketSize 2 Number Maximum Packet Size this endpoint is capable of sending or receiving6 bInterval 1 Number Interval for polling endpoint data transfers. Value in frame counts. Ignored for Bulk & Control Endpoints.

Isochronous must equal 1 and field may range from 1 to 255 for interrupt endpoints.

✔ Device Class Codes = Predefined standard USB device/driver collections that allows standard OS drivers to handle typical devices* Class codes are set in the Device Descriptor byte-4 and Interface descriptor byte-6* Bluetooth also uses the USB device classes

◌ Human Interface Devices (HID)◌ Mass Storage Devices (MSD)◌ Communication Device Class (CDC)◌ Vendor Specific – No standard USB driver; A custom vendor specific driver needs to be created.

▪ There are two levels of APIs related to USB HID: the USB level and the operating system level. At the USB level, there is a protocol for devices to announce their capabilities and the operating system to parse the data it gets. The operating system then offers a higher-level view to applications, which do not need to include support for individual devices but for classes of devices. This abstraction layer allows a game to work with any USB controller, for example, even ones created after the game.

✔ Reference◌ USB Device classes http://en.wikipedia.org/wiki/USB#Device_classes ◌ Microsoft USB-Viewer (Part of WDK – Windows Driver Kit)

C. Logical Layer✔ Endpoint = A communication pipe ending created during device design (ie: Part of the USB devices architecture)

◌ Endpoints other than Endpoint(0) must be configured by the host before data transfer can occur on them.◌ Endpoints are defined and explained to the host using endpoint descriptors (see above in Functional Layer)◌ Endpoints are addressed using the [ Device-ID | Endpoint # | Data Direction ] combination.◌ Each Device can support up to 15-IN and 15-OUT endpoints as a Full-Speed device.

✔ Endpoint(0) = (ie: The default control pipe ending) that must be implemented on ALL USB devices for deviceenumeration

✔ Pipes = Representation of data movement between host software (via Memory Buffers) and endpoints on devicesTransfer-Type Pipe Mode Description Transaction Packets

Control Message Device initialization and pipe control; Bi-directional simple commands / status Endpoint(0) = Default Control Pipe

Page 15: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

Control Pipe

Bulk StreamData Pipe

Large payloads, uni-directional per endpoint (file transfers) s

Interrupt StreamData Pipe

Timely and reliable, uni-directional (guaranteed pick-up response rates) s

Isochronous StreamData Pipe

Pre-negotiated bandwidth (streaming real time transfers) guaranteed data rate (audio / video) s

◌ Transfer-Type specifies and typically consists of multiple packets▪ Data format imposed by the USB▪ Direction of communication flow▪ Packet size constraints▪ Bus access constraints▪ Latency constraints▪ Required data sequences▪ Error Handling▪ Example Low-Speed Interrupt pipe OUT packets are: [PRE] → [Token] → [PRE] → [Data] → [Handshake]

◌ Pipe Modes▪ Message Pipes = Bi-Directional to endpoints (ie: Allows IN/OUT Token packets) as defined by “Control Transfer” in the USB specification document.▪ Stream Pipes = Uni-Directional to endpoints; Data stream (FIFO) through data-packet portion of bus transactions; No USB required structure.

✔ Framing (Each Transfer-Type defines what transactions are allowed within a frame) for anendpoint.

◌ Full/Low-Speed devices – 1-Frame = 1mS◌ High-Speed devices – 1-Frame = 125uS (Also called a “micro-frame”)◌ Host Controller Polls Devices by sending them a Start-Of-Frame(SOF) Packet.

D. Physical Layer

1. Device Introduction ( ie: Device is plugged physically into a USB port ) a) SE0 State = Single-Ended '0' – Both data-lines are at GND indicating a “reset-device” or “no-device connected” state. b) J-State = Idle State – Device pulls a data line high (D+(full speed) /D- (low-speed)) over-ridding the hosts SE0 initial state and setting /

defining the J-State. c) K-State = Opposite J-State – The differential data-lines pair implement NRZI line coding data representation.

d) NRZI line coding = Non Return to Zero Inverted• '0' = D+/D- compliment (ie: Inverse) previous voltage levels (ie: J → K or K → J)• '1' = No-change on D+/D- through a data cycle.

e) Reset / Data Polling• USB 2.0 – Host controller polls the bus for traffic (throughput is the slower one of either host / device )• USB Reset = A Prolonged (10 to 20 mS) of the SE0-State• Low-Speed USB – Requires a Keep-Alive signal (An EOP) every 1 ms to keep device from entering suspended mode.

2. Packet Communications – (8)bit bytes least significant bit (NOTE: not byte) first (LSb)

a) Sync = Initiates communication and synchronizes / defines the data cycle speed (ie: Clock) – All packets begin with a 'Sync' Host drives 'Sync' signals on the data lines that determines the data cycle speed and signals the start of a packet communication.

• USB Low/Full Speed Length: 1-byte (ie: 8-bits)• USB High-Speed Length: 4-bytes (ie: 32-bits)• Contains: '0000_0001' (ie: “KJKJKJKK” states) same KJ repeat for 32-bit ending with a double KK which signals ( end-of-sync →

start-of-PID)

b) PID = Packet ID – The Packet Type being communicated (e.g. Token, Data, Handshake, Special)• Length: 1-byte (ie: 8-bits)• Contains: [ 4-bit PID Value | 4-bit Inverted PID Value ]

TypePID value

(msb-first)

Transmitted byte(lsb-first) Name Description

Reserved 0000 0000 1111

Token1000 0001 1110 SPLIT High-bandwidth (USB 2.0) split transaction. Sends data at high-bandwidth to a high-bandwidth HUB where it

will be transferred to a full/low bandwidth to slower devices.

0100 0010 1101 PING Check if endpoint can accept data (USB 2.0) – after getting a 'NYET'

Special1100 0011 1100

PRE Low-Speed packet preamble for HUB (USB 2.0 devices ignore this packet)

Handshake

ERR Split transaction error from a HUB (USB 2.0 devices ignore this packet)

0010 0100 1011 ACK Data packet accepted (ONLY Handshake the Host can produce)

1010 0101 1010 NAK Data packet not accepted; please re-transmit

0110 0110 1001 NYET Data not ready yet; Device isn't ready to receive another packet yet (USB 2.0 ONLY)

1110 0111 1000 STALL Transfer impossible; do error recovery

Page 16: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

Token

0001 1000 0111 OUTContents: [Sync |PID (OUT) |7-bit Device ADDR |4-bit ENDP # |5-bit CRC |EOP ]Purpose: (Host → Device) Precedes data from host to device transfers. Followed by Host driven DATAx frame. Device response (ACK, NAK, NYET or STALL)

1001 1001 0110 IN

Contents: [Sync |PID (IN) |7-bit Device ADDR |4-bit ENDP # |5-bit CRC |EOP ]Purpose: (Device → Host) Request device sends data to hostResponse: Expects a response from the device. (NAK, STALL) Or DATAx Frame which would be followed by a Host-ACK.

0101 1010 0101 SOFContents: [Sync |PID (SOF) |11-bit Frame # |5-bit CRC |EOP ]Purpose: Start of frame marker (sent each ms) with incremented Frame number(revolving) in place of device address. For isochronous and interrupt data transfers. (2.0 @ 125uS)

1101 1011 0100 SETUP Contents: [Sync |PID (SETUP) |7-bit Device ADDR |4-bit ENDP # |5-bit CRC |EOP ]Purpose: Address for host-to-device control transfer; Follows an 8-byte DATA0 frame

Data

Data Transfers includes: [IN/OUT/SETUP Token] → [Data Packet] → [ACK Handshake Packet]Payload Size Limits: HS 1024-bytes, FS 64-bytes, LS 8-bytes ( 2-packet type provides 1-bit seq number req by Stop-and-Wait ARQ.)

0011 1100 0011 DATA0Contents: [Sync |PID (DATA0) |Payload |16-bit CRC |EOP ]Purpose: Even-numbered data packet (Data toggles between DATA0/DATA1 for each successful packet transfer)Response: 'ACK' is expected from either host/device (depending on IN or OUT Token)

1011 1101 0010 DATA1Contents: [Sync |PID (DATA1) |Payload |16-bit CRC |EOP ]Purpose: Odd-numbered data packet (Data toggles between DATA0/DATA1 for each successful packet transferResponse: 'ACK' is expected from either host/device (depending on IN or OUT Token)

0111 1110 0001 DATA2Contents: [Sync |PID (DATA2) |Payload |16-bit CRC |EOP ]Purpose: Data packet for high-bandwidth isochronous transfer (USB 2.0)Response: 'ACK' is expected from either host/device (depending on IN or OUT Token)

1111 1111 0000 MDATAContents: [Sync |PID (MDATA) |Payload |16-bit CRC |EOP ]Purpose: Data packet for high-bandwidth isochronous transfer (USB 2.0)Response: 'ACK' is expected from either host/device (depending on IN or OUT Token)

• ADDR::ENDP = Target “device::endpoint” the packet will be received by◦ Default: “x00” is the ADDR::ENDP during device enumeration.◦ Low-Speed functions are limited to 2-optional endpoints beyond the 2 required at endpoint(0)◦ Full-Speed devices can have 15 IN & OUT endpoints

• SOF = Start of Frame(#); Frame Time Markers (keep in-sync with host) full/high-speed ONLY.◦ Frames are a single or a collection of packets that can fit within a Frame-Time◦ Each Frame amount of Time must start with a SOF packet.◦ SOF must be sent every 3 mS to keep device from entering suspend mode.◦ High-Speed devices send SOF packet every 125uS but frame increments at 1mS

• EOP = End of Packet◦ Signaled by 2-bit times of SE0 (Single ended zero / both D+ and D- @ GND) then 1-cycle of J-State and held in the J-State (idle)

• Data Communications: [ IN/OUT – Token ] → [ Data Packet ] → [ Handshake ] Reciever → Transmitter ] ◦ Data Packets always follow an IN/OUT/SETUP Token◦ PID toggles between DATA0 and DATA1 for each successful data packet transfer.◦ NOTE: USB has a bit stuffing rule whereas any six consecutive '1' bits must be followed with a '0' bit. **

✔ See Also◌ USB Packet Sniffer – Free Device Monitoring Studio http://www.hhdsoftware.com/Downloads/device-monitoring-studio◌ Windows USB View Hardware debug application http://code.msdn.microsoft.com/windowshardware/USBView-sample-application-e3241039 ◌ Creates C structures from USB HID Report Descriptors http://sourceforge.net/projects/hidrdd/ ◌ Cypress Introduction to USB AN57294 http://www.cypress.com/?docID=33237 ◌ USB 2.0 Specification Documents and USB Vendor ID (for $5000) http://www.usb.org/◌ USB Specification Website http://www.beyondlogic.org/usbnutshell/usb1.shtml ◌ Altera DE2 FPGA dev board as a USB Device (No Nios) VHDL code http://mzakharo.github.io/usb-de2-fpga/

2.3.12 VGA Interface Spec✔ RGB Signals are Analog (Nominal Voltage 0.7Vdc)

◌ Monitor sinks 75-Ohms on each signal.✔ Horizontal Sync (HS) and Vertical Sync (VS) are digital signals = these are active low✔ Picture is generated left-to-right(line-by-line), top-to-bottom

◌ HS signals a new line◌ VS signals top of screen (top-line)◌ 640 x 480 = 60Hz(VS) and 31.5kHz(HS)

✔ Reference◌ http://www.fpga4fun.com/PongGame.html◌ http://martin.hinner.info/vga/

3. CIRCUIT THEORY✔ Circuit Purpose Groups

◌ Processors - Circuits that execute code (Typically in IC form) ◌ Digital Logic - Circuits that an upper-voltage level to represent binary '1' and typically no/little voltage to represent binary '0'

✔ See Also◌ http://commons.wikimedia.org/wiki/Category:Electronic_circuits Symbols, Circuit examples◌ http://en.wikibooks.org/wiki/Subject:Electrical_engineering

Page 17: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

✔ Quick and Simple http://www.tutorialspoint.com/computer_logical_organization/index.htm✔ http://www.allaboutcircuits.com/✔ Things to memorize

◌ Period = 1 / Frequency◌ Frequency = 1 / Period

▪ ½ = 0.500 Per (<>1) (=1)▪ 1/3 = 0.333 mS = Hz → kHz(k)▪ ¼ = 0.250 uS = kHz → Mega(M)▪ 1/5 = 0.200 nS = MHz → Giga(G)▪ 1/6 = 0.166▪ 1/7 = 0.142 Convert from Period <=> Frequency ask what is 1/x 1 0 1:1 else inverse count▪ 1/8 = 0.125 Then switch the Eng Notation as listed above.▪ 1/9 = 0.111 Ex. 2nS ½ = 0.5 500MHz (0-0s = 2-0s)▪ 1/10 = 0.100 Ex. 20nS ½ = 0.5 50MHz (1-0s = 1-0s)▪ x Ex. 200nS ½ = 0.5 5MHz (2-0s = None)

✔ Basic Electric◌

3.1 Analog 1. Power / Ohms Law

a) Power(Watts) = Current(I-Amps) * Voltage(V-Volts) b) Ohms Law:

• . /\ Picturing the diagram; Cover the Letter for the item you want to find. (V=Volts, I=Amps, R=Ohms)• . / V \ Find V (cover V whats left?) V = I * R• . /-----\ Find I (cover I whats left?) I = V / R• . / I | R \ R = V / I• . ^^^^^^^ Power = V * I; So we can replace any item in the power equation for derived equations• . Ex. Power = (I*R) * I = I^2 * R

2. OpAmp = Signal amplifier that implements a differential amplifier circuit. 3. Transformer = A group of inductors (ie: Coils) that transforms the level of AC Voltage and Current (ie: step-up or step-down voltage level)

3.1.1 Analysishttp://coen.boisestate.edu/bobhay/ece210/

Chapter 1 – Current, Voltage, and ResistanceCharge – Quantity of electricity 1 C (Coulomb) = 6.24 x 1018 electronsCurrent [I or i] – rate of charge flow Charge to Current equation I[A] = dq/dt [coulombs/second] Current to Charge equation Q[C] = ʃ I[A] dt + q(0)[C] Q(0) is charge at t=0

Voltage – The energy(work) required to move electricity V = dw/dq = (w)energy[Joules]/(q)charge[Coulombs]

Power – rate of energy absorption/expension P[W] = VI = dw/dq * dq/dt ->then = dw/dt (Watts) Or w[J] = ʃ p dt + w(0)[J] 1 Joule = 1Watt/Sec 1 KJ = 1 KW/s 1 KWH = 3600KJ

Chapter 2 – Circuit Elements

Superposition – states the voltage increments linear with current incrementsHomogeneity – doubling input causes output to double

Linear element – Elements that satisfies both superposition and homogeneityResistance in a wire (R)=pL/A, L=length, A=Area, p=Resistivity of elementOhms Law – V=iRIndependent Sources – Battery or current source with definite value of V or IDependant Sources – The source value (right-diamond) depends on the Control Value (ie: Vc or Ic, Rectangle Element) where g = gain or multiplier..Note: You can’t use KVL on current sources or KCL on voltages sources →

Prefix Symbol 10n

yotta Y 1024

zetta Z 1021

exa E 1018

peta P 1015

tera T 1012

giga G 109

mega M 106

kilo k 103

hecto h 102

deca da 101

100

deci d 10−1

centi c 10−2

milli m 10−3

micro µ 10−6

nano n 10−9

pico p 10−12

femto f 10−15

atto a 10−18

zepto z 10−21

yocto y 10−24

Page 18: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

Nodal analysisCurrent out of node (+)Node V – far side V ThevinensRth = Voc/Isc

3.1.2 Transistors a) NMOS b) PMOS

Page 19: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

A. CE Amp (DC Analysis)

DC analysis - Dual Stage Bi-Polar NPN PNP Common Emitter Amplifier

Circuit AnalysisFist step is to find the DC voltage Ratings.

From here we can find Ve because of the 0.7V drop from base to emitter of the NPN Transistor

Now we can find the current through the emitter by ohms law on the emitter resitor

Because of a very small base current we can assume that the collector current through Q1 is approximately the same as the emitter current in Q1, therefore we can find the voltage drop across the collector resistor by using ohms law.

Then we can find the collector voltage on Q1 by subtracting Vr9 from Vcc

Then we can find voltage from collector to emitter by subtraction.(For normal operation should be ½ Vcc)We then do the same process for the second part of the dual stage amplifier to get:

B. Dual Stage NPN PNP Amplifier (AC Analysis)From Transistor Spec (B=100)The only DC value we need for AC analysis is Ic or Ie, we then find the r’e value of the last amplifier. r’e is the AC resistance the transistor adds tothe circuit from Vb to Ve.(Where 25mV is a general constant)We can then find the Gain Av of the second amplifier stage by the equation Av=rc/re. As we can see that by the fact that AC will flow directly through the capacitor C3, the AC resistance of the collector will be R5||RL (or in parallel with), were the AC resistance of the emitter is r’e+R6 because capacitor C4 allows AC current to bypass R11 and return directly to ground through Vcc. This design of amplifier where one capacitor bypasses one emitter resistor but leaves a smaller resistor at the emitter for some resistance is know as a Swamped Amplifier.

Then we can find the input impedance of the second amplifier stage. (Input Resistance)

Notice that the resistance at the base of the transistor Q2 is the emitter resistance times Beta. Once we know the resistance at the base of transistor we can see it is in parallel with R7 and R8.Now we can find the values of the first stage the same as the second stage and we get:

We must be careful when calculating Gain of first stage to include the Input resistance of stage 2 in the collector AC resistance as shown below.

Now that we have both gains in both stages we can find the total amplification by:

Page 20: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

Before we can apply gain we must find the actual input AC voltage though at the base. Notice:We can draw the Thevenin’s equivalent circuit as shown to the left. By this we mean that the source AC goes through R5 but is also dropped to ground through R1||R3||Zin (Zin of the base of Q1). The total Zin was found previously to be 403 Ohms. Therefore, the actual input AC is equal to the value in the center of two series resistors, the first being R2 and the seconds is the resistance from the base to ground of the

transistor.

So the actual AC input voltage is:(The actual input AC voltage)With this input voltage we can then find the approximate output voltage by Total Gain:

Different ApproachA different approach to analyzing the above circuit would to find amplifier stage gains without including the load. For example, instead of including Zin of the next stage, find gain without a load at the output of each amplifier stage. Then one could Thevenize the circuit into three different circuits as shown below:

In the first schematic, we show how we came up with input voltage of 889uV as shown above. The unloaded voltage gain of the first amplifier will be found by:Then 889uV x 9.59 = 8.53mVThe unloaded gain of the second stage is done exactly the same way. Gain=32 unloadedAfter solving the second schematic we find the input voltage into the load with a gain of 32 is 126.4mV.. Finally the output must be divided by the collector resistor ground and the Load resistance to ground giving us a final Vout of 63.2mV which is approximately the same answer as doing things the other way.

4.

Page 21: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

3.1.3 Inductors/Coils

A. Series RL AC Circuits - Low Pass Filtering

Frequency Cutoff(Frequency cut off is when Inductive Reactance (XL) equals Resistance)(Rearranged equation from above when Xl=6.28LF)(This is a slow curved process, cutoff is just a standard)Cutoff with Inductive reactance passes low frequencies and filters high frequencies.

As shown by the oscilloscope, current leads the voltage or voltage lags the current.Inductive Reactance(Where L=Inductor (Henrys) and F=Frequency (Hertz))(Inductive Reactance always 90degrees)Inductive Impedance

On the HP48G+ enter polar mode by right shift (MTH), then enter polar numbers in (xx) with<This can also be found by graphing or Trigonometry as shown below:As shown by the graph, for solving Z one can use the hypotenuse equation:Hypotenuse equation

The angle can be found using Trigonometry functions like:

5. 6. Diode 7. Capacitor 8. Inductor (ie: coil) 9. Resistor

3.2 Digital Combinational Logic Circuits = directly responds to input changeSequential Logic = Remembers present state and combines with input changes to create a new stateSynchronous Sequential = Inputs are only evaluated at master-clock signal changeAsynchronous Sequential = Responds to inputs at speeds determined by the devices themselves rather than a master-clock.

◌ VSS – LOW – '0'◌ VCC – VDD – HIGH = '1'

3.2.1 Sequential Logic (RTL)✔ RTL = Register Transfer Level – Describes how data sequentially moves through the system

◌ NOTICE; In EDA circuit design; the generally accepted meaning of RTL is any HDL code that can be synthesized. (omitting simulation/debug)

✔ System level digital circuits are categorized by how they handle timing.◌ RTL design determines Timing-Sequence & Synchronization of data movement (Transfer-Spec) within digital systems.◌ RTL is Sequential Behavior because data transferred without a sequence is a direct connection◌ RTL design typically implements algorithmic Boolean equations to move data through the system.◌ Gate Delay = Time required for valid input-levels to be reflected on the output pin (ie: Also known as Propagation Delay)

Page 22: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

◌ TIME handling makes sure logic-element-1 has completely evaluated BEFORE its output is fed into logic-element-2.

✔ Sequential logic components have output registers (ie: latches) to hold output-level until the next clock cycle (ie: Evaluation point-in-time)◌ Register outputs re-route to register inputs after a fashion

A.1 Synchronous (In-Sync)

1. Output state of all logic only changes at the master clock signal (Output register is activated by clock) a) All evaluation states are synchronized or stepped which allows the required time for logic-transistors/gates to evaluate the inputs. b) master clock signal - It takes X-clock cycles for output to reflect active inputs.

A.2 Asynchronous (Transparent)

1. Asynchronous circuits are commonly referred to as Transparent 2. Elements in an asynchronous circuit are out-of-sync from each other. 3. State changes with changes on the input pins

a) Asynchronous = Output can change at any time (No Master Sync-Clock) b) Typically use 'complete' signals known as 'data transfer protocols'

• logic-element-1 signals 'complete' on a special pin to instruct logic-element-2 to "go"◦ 'Req' uest◦ 'Ack' nowledge

c) Asynchronous sequential circuits may be regarded as Combinational circuits with feedback d) State changes with changes on the input pins

A.3 Implementation

A.3.1 Finite State Machine (FSM)

1. FSM is a finite (ie: Pre-Defined ) list of “states” (ie: think to-do list but uses nouns) that iterates from one state to the “next state”. a) Moore FSM – Typically is just a counter that steps from one state to the next w/o regard to any other inputs besides the "stored"

present state. b) Mealy FSM – A state machine that is not a Moore FSM(ie: Non Just A-Counter). Next state depends on both current inputs and

present state.• [ASM] Algorithmic State Machine• Sequential logic is used heavily in Finite State Machines (FSM)

A.3.2 Pipe-Lining

✔ Pipe-Lining is a speed enhancement for sequential logical circuits▪ Synchronous Pipe-lining = breaking down complex circuits to small blocks so each can have their own synchronous clock

▫ Pipe-lining in RISC Processor architecture is popular▪ Asynchronous Pipe-lining = output registers are clocked asynchronous

▫ Typically use the REQ(request) / ACK(acknowledge) data transfer protocol

✔ References▪ http://en.wikipedia.org/wiki/Finite_state_machine▪ http://en.wikipedia.org/wiki/Pipeline_%28computing%29▪ http://en.wikipedia.org/wiki/Asynchronous_logic▪ http://en.wikipedia.org/wiki/Sequential_logic▪ http://en.wikipedia.org/wiki/Register-transfer_level▪ http://en.wikipedia.org/wiki/Propagation_delay

3.2.2 Combinational Logic✔ Combinational Logic - (ie: 'Transparent') Discrete non-clocked blocks - No memory

◌ NOT identified by Synchronous or Asynchronous but fits into the Asynchronous group.◌ Said as 'output' is a 'pure function' of the PRESENT input.◌ Boolean algebra, half/full adders, half/full subtractors, multiplexer, demultiplexer, encoders

and decoders.◌ Combinational = Output is a pure function only representing the present input (ALU is

Combinational) { http://en.wikipedia.org/wiki/Combinational_logic }

A. Algorithmic Circuits✔ Algorithmic

◌ Sub-Level Blocks / Sub-Circuits For Logic / Math / Memory◌ Functionality defined by operation (No hardware implementation details), ALU, RAM, CU◌ Algorithm level; much like c-code with if, case, loop statements Example;

'Z=X+Y' for 32-bit adder

B. Arithmetic Circuits✔ Arithmetic Circuits (for numeric functions) are Combinational Circuits

◌ Number representation (Encoders/Decoders)◌ BCD - Binary-coded Decimal; 4-bit groups determine each decimal digit.◌ Gray-Code - Obsolete; Only changes 1-bit per increment (in past used with shaft position

sensors)

Page 23: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

B.1 Negative numbers (0x7F)

✔ Negative Numbers are represented by 2s-Compliment▪ With Negative numbers the range of numbers represented by binary are cut in half for + and -.

▫ 4-Bits (Nibble) Any value over 0x7 is a negative number▫ 8-Bits (1-Bytes) Any value over 0x7F is a negative number▫ 16-Bits (2-Bytes) Any value over 0x7FFF is a negative number▫ 32-Bits (4-Bytes) Any value over 0x7FFFFFFF is a negative number

▪ Left-Most bit can be used as a negative bit-flag (1=negative)✔ 1s Compliment; has a sign bit-flag also but inverts every bit in the number (ie: Subtracting it's positive equivalent)

▪ 2s Compliment; 2^n - PosNum; (-5 = 10000 - 0101 = 1011)▪ Easier method; copy all bits that are 0 and first-bit; then compliment all other bits.▪ Radix-Complement Scheme

B.2 Adder

✔ Math Circuits ( Subtraction is done by changing negative number to 2s Compliment and then adding )▪ Half-Adder(HA) - 2-binary bit (b1, b2) addition circuit with 'carry' and 'sum' bits.▪ Full-Adder(FA) - 2-binary bit (b1, b2) addition circuit with a 'carry-in' bit for extra bit addition (Created from 2 Half-Adder

circuits and an OR gate).▫ Ripple Carry Adder (RCA)▫ http://en.wikipedia.org/wiki/Adder_%28electronics%29

B.3 Boolean Algebra

✔ Mathematics sector used to represent Logical-Circuits and reduce them to simplest terms. 1. Gate Representation (In precedence order of operations)

a) ' (!~) - NOT - L(x,y) = x' + y'; NOT(X) OR NOT(Y) also line above; cant make on PC b) * (^) - AND - L(x,y) = xy; X AND Y; Intersection of X & Y "product" c) + (v) - OR - L(x,y) = x + y; X OR Y; Union of X & Y "sum"

2. Axioms a) AND OR b) 0*0=0 1+1=1 c) 1*1=1 0+0=0 d) 0*1=1*0=0 1+0=0+1=1 e) If x=0 {x'=1} If x=1 {x'=0}

3. Theorems a) AND OR b) x*0=0 x+1=1 // Huntington's Basic Postulate c) x*1=x x+0=x d) xx=x x+x=x e) x!x=0 x+x'=1 // Huntington's Basic Postulate f) !!x=x

4. Principle of Duality - An equations dual is obtained by replacing all + with * and 0s with 1s or visa versa. (as shown above) a) If x,y,z are variables in B(equation) then the following properties hold true. b) AND OR c) x*y = y*x x+y=y+x // Commutative // Huntington's Basic Postulate d) x*(y*z)=(x*y)*z x+(y+z)=(x+y)+z // Associative e) x*(y+z)=x*y+x*z x+y*z=(x+y)*(x+z) // Distributive // Huntington's Basic Postulate f) x+x*y=x x*(x+y)=x // Absorption g) xy + xy! = x (x+y)(x+y!)=x // Combining h) !(xy)=!x+!y !(x+Y)=!x!y // DeMorgan's theorem i) x+!xy=x+y x(!x+y)=xy j) xy+yz+!xz=xy+!xz (x+y)(y+z)(!x+z)=(x+y)(!x+z)// Consensus

• All other theorems and properties can be derived from the 'Huntingtons Basic Postulates'• These are fundamental concepts of the Synthesis process in CAD::EDA design tools

k) Venn diagram - A pictorial representation in which "sets" are represented by circles or other shapes.

3.2.3 Logic Gates✔ Logic Gates = standard / common switch-circuit designs created specifically for handling basic digital logic.

◌ switch = transistors used for digital purposes – Only “on=1 / off=0” states are relevant✔

◌ Buffers – Separate Drive from Pin▪ Tri-State (ie: Transmission Gate) buffers allow pins to be either output-driven or 'Z' dis-connected; thus tri-state 1,0,Z▪ Short-Circuit Prevention when two device outputs share a common wire (One drives while the other in 'Z' – high impedance /

disconnected )▪

◌ Register = Collection of Asynchronous Flip-Flops (ie: Latch)▪ 16-bit register ~ 16 latches

◌ Flip-Flops(FF) – flip-flops are a common logic-gate circuit design that can retain logic levels through time (memory)

Page 24: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

✔ Flip-Flop

Q = Output Description

D D = Q D sets Q @ rising edge of CLKT &

SR Set / Reset |JK J=Set,

K=Reset~&

Latch D = Q D sets Q @ Enable High (Technically nota FF)

◌ Logic Gates – are a common transistor level circuit design. LogicGates

Verilog-Symbol

Description (Input→ Output)

NOT Inverse ~ 1 → 0 / 0 → 1AND All-Input-

AND& 1,1,1(all) → 1 ELSE

→ 0OR All-Input-

OR| 0,0,0(all) → 0 ELSE

→ 1NAND NOT AND ~& → NOT(AND)NOR NOT OR ~| → NOT(OR)XOR Exclusive

OR^ 0,1,0(1-1) → 1 ELSE

→ 0XNOR Exlusive

NOT OR~^ → NOT(XOR)

✔ Propagation delay (ie: Gate Delay) = The time it takes for a digital logic gate to register a result◌ 7400 IC Gates typically have a gate delay of around 10 – 2 nanoseconds; thus can only operate at 100 – 500MHz frequency correctly◌ Inside modern CPU's with speeds of up to 3.5GHz requires gates that respond with a delay of around 280pS (picoseconds)

3.2.4 Discrete Logic

A. 7400-Series ICs✔ Labeling Notations

▪ 'L' = TTL (74LS00)▪ 'H' = CMOS (74HC00)

✔ Notes▪ 7400-Series buffers are about the only 7400 chips still in use today (74244); ▪ 7400-Series SSI-Small Scale Integration technology to make the ICs.

✔ 162244 (SOIC-Package, much smaller & more devices)http://en.wikipedia.org/wiki/7400_series

3.3 Mixed-Signal ( Analog & Digital ) ✔ More @ http://en.wikipedia.org/wiki/Electronic_circuits

✔ ADC = Analog to Digital Circuit – Converts an Analog Input to a Digital Number ( Voltage level → Digital Number )✔ DAC = Digital to Analog Circuit – Converts a Digital Number to an Analog Output ( Digital Number → Voltage Level )✔ http://en.wikipedia.org/wiki/Finite_impulse_response FIR Filter

4. CIRCUIT DESIGN STEPS

1. Plan - Containing IP-Blocks/ System Buses / IO (Peripheral Buses) 2. Entry - Enter the circuit design into EDA software ( Schematics and/or HDL entry ) 3. Synthesis – (ie: Compile) the circuit design to a lower-level NetList 4. Validate – Through simulation that the design meets planned specification and operation 5. Layout – Prepare design for Target Hardware (ie: Floor Planning )

✔ Entry Categories◌ Behavioral - How the circuit behaves (e.g. What a house does)◌ Structural - How the circuit is connected (e.g. House blue-prints)

✔ Entry Abstraction Layers ( Most abstract to least abstract )◌ Architectural - Design in terms of functional blocks (IP-Cores)◌ Algorithmic - Design in terms of math function (behavioral)◌ Register Transfer Level (RTL)- Design in terms of logic and storage devices◌ Gate level - Design in terms of logic comparison gate components◌ Switch level - Design in terms of transistor switches or discrete devices

Drawing 2: Gates of a D-Flip-Flop

Drawing 1: Logic Gate Schematic Symbols

Page 25: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

✔ Circuit design tool chain◌ Each step in an EDA design flow typically has independent software-tools◌ Companies tend to package a set of tools into an integrated design suite◌ Integrated Design Suites are often referred to as EDA Software Packages

✔ Best-practices◌ little code → test → little more code → test (not write a bunch and run)◌ Concept → Partition(Divide & Conquer) → Block1, Block2, etc...

✔ See Also◌ Wiki Design Flow - http://en.wikipedia.org/wiki/Design_flow_%28EDA%29

4.1 Planning ✔ Create detailed design purpose and specifications for the system / circuit

◌ Document the system circuits purpose / goal◌ Document the specification the system must meet.◌ Draw a block diagram of the designs function blocks◌ Specify Input and Output (I/O) Interfaces and standards that might be implemented◌ Specify any internal interconnect architecture (ie: Standard Bus's)◌ Financial Feasibility and Market

4.1.1 System Buses✔ System Buses are common interconnect standards between various components of a system circuit.

◌ AMBA – by ARM; Advanced Microcontroller Bus Architecture (AMBA)◌ Wishbone bus – by OpenCores; Free and open bus architecture (formerly from Silicore) ◌ CoreConnect – by IBM; bus technology from PowerPC Architecture and Xilinx MicroBlaze◌ IDT IPBus ◌ Avalon – by Altera; Proprietary bus system for Altera's Nios II SoCs

Illustration 1: Example Planning Block Diagram for an IC.

Page 26: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

◌ OCP = Open Core Protocol ◌ Hyper Transport – by AMD◌ Quick Path – by Intel

✔ Determine Clock Domains✔ Decide How the “team” will divide responsibilities.

✔ See Also◌ AMBA - http://en.wikipedia.org/wiki/Advanced_Microcontroller_Bus_Architecture ◌ Altera Nios-II SOPC System Bus Standard Avalon Switch Fabric - http://en.wikipedia.org/wiki/Nios_II#Avalon_switch_fabric_interface

4.1.2 IP-Cores (Re-Use)

✔ IP-Core - Intellectual Property Core = A common-use circuit design containing ownership rights (ie: Copyrighted)◌ Other Common Names for IP-Core

▪ IP-Block - Intellectual Property Circuit Block▪ SIP - Semiconductor Intellectual Property

✔ IP-Cores typically have Interconnection Standards (ie: System Buses) that need to be considered.

✔ List of places to get IP-Cores◌ http://www.opencores.org/◌ http://www.geocities.com/SiliconValley/Pines/6639/ip/memory_cores.html - Free Memory Cores ◌ http://www.estec.esa.nl/wsmwww/erc32/ - An ERC32 (radiation-tolerant SPARC V7) processor developed for space applications.◌ http://www.cmosexod.com/freeip.htm - 12bit DSP core / peripherals, 8bit CISC processor, frequency counter, SDRAM Controller◌ http://young-engineering.com/intellectual_property.html ◌ http://www.freerangefactory.org/cores/

✔ Companies that sell IP-Cores◌ http://www.smart-dv.com/ ◌ http://www.wipro.com/ ◌ http://www.hcl.com/

4.1.3 Design For Testability (DFT)✔ Detail how the design will be tested and what functionality needs to be tested.

◌ Basic Input Self Test (BIST) = logic circuit that tests the circuit internally◌ JTAG Boundary Scan

4.2 Schematic Entry ✔ Schematic entry is usually only used at the top-level of a system design to interconnect sub-circuits / cores / blocks.

Page 27: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

4.3 HDL Entry

✔ HDL (Hardware Description Languages)

◌ Standard▪ VHDL – (.vhd) file extension = VHSIC(Very High Speed Integrated Circuit) HDL▪ Verilog – (.v) file extension = Rights Recently purchased by Cadence▪ SystemVerilog - (.sv) file extension = Newer version of Verilog by Cadence to cover its system level shortcomings.

◌ Variations / Extensions▪ Actel HDL (AHDL)▪ Altera HDL (AHDL)▪ SystemC = Is a C++ library (TLM - Transaction Level Modeling) much higher-level than RTL▪ Verilog-A = Analog design extension for Verilog▪ BlueSpec Verilog = Atom System Verilog (Guarded atomic actions); Is a Verilog Simulation extension package.

◌ Historical▪ ABEL – From 1981 see http://en.wikipedia.org/wiki/Advanced_Boolean_Expression_Language▪ PALASM – PAL HDL from 1980s see http://en.wikipedia.org/wiki/PALASM

✔ HDL Modeling (HDL is a Mixed-level circuit description language)◌ Synthesis - circuit behavior = Process of; Abstract desired circuit behavior (RTL) → Circuit design

◌ Synthesizable Code – Code that is synthesized for circuit implementation; Commonly referred to as RTL▪ Behavioral - Verb Emphasis ( Sequential / Procedural ) = describes IO responses; what it does or how it behaves.

▫ Algorithm level code– much like c-code with if, case, loop statements Example; 'Z=X+Y' for 32-bit adder▫ Register Transfer level(RTL) code – Registers connected by Boolean equations that determine how data moves / progresses

through the system.▪ Structural - Noun Emphasis (Concurrent) = Tying together gate/transistor level components (verbal wiring

w/o storage)▫ Gate level code (Alias 'Dataflow') – Boolean expression interconnects AND, NOR, and etc.. Example; 'Z <= X AND Y'▫ Switch level code – ie: transistor level; the MOS transistors inside the gates

◌ Simulation Code – HDL code that is used only for simulation and verification purposes

✔ HDL Terms◌ Sub-Circuits are sometimes called macro-functions, mega-functions or IP-Cores

▪ Technology Dependent Macro-function – circuit design for a specific type of chip▪ Technology Independent Macro-function – circuit design that can be implemented in any type of chip.

▫ LPM = Library of Parameterized Modules – Circuit Library that is technology independent. 'lpm_add_sub'

✔ Coding Practices ( Typically Job specific – no real standard )Use For Postfix For Use For

addr Address _n Active Low

clk Clock _r Register

rst Reset _#r Pipeline #

arst Async Reset _i Internal signal

rw read-write

◌ Physical IO maybe should be all-caps (Aptina)◌ in / out port labeling is discouraged

✔ See Also◌ HDL examples including I/O Hardware Interfaces and descriptions http://www.fpga4fun.com/◌ HDL Coding Styles http://www.maia-eda.net/index.php?option=com_content&task=view&id=121&Itemid=258◌ VHDL Primer http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061348◌ MIT-Press “Circuit Design with VHDL” http://profs.basu.ac.ir/abdoli/upload_file/722.file_ref.1121.1422.pdf◌ Online HDL Simulator http://www.edaplayground.com

4.3.1 Verilog✔ See Also

◌ http://www.doe.carleton.ca/~jknight/97.478/97.478_02F/PetervrlQ.pdf

// synthesis VERILOG_INPUT_VERSION SYSTEMVERILOG_2005

Page 28: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

/**<HDL-Basics> Hardware Description Language - a textual representation of an electronic circuit. 1. HDL Abstraction Levels -

Switch Level - Transistor switching (MOS) Gate Level - Logic gate level (Either Combinational or Combinational/Register) Register Level - Algorithm Level

3. Verilog is case-sensitive (commands are typically lower-case)*******************************************************************************************************************************************/ //</Basics>

A. Module// Module = A named sub-circuit with an external interfacemodule learnbasic(input wire ClkIn, RstIn, ReqIn, // Port = External connection. (type is optional and 'wire' by default) input [7:0] AddTo7, HalfIn, ShifLft, // - 'input' (type wire only) An input for a module or task inout [7:0] DataLine, Trans1, Trans2, // - 'inout' (type wire only) Tr i-State (input and output) output wire ClkLight, RstLight, ReqLight, // - 'output' (any net type) Output - driven signal output reg BcdOut1, BcdOut2, BcdOut3, OddIn7, output [7:0] Sum7, HalfOut, Shift, output [15:0] HWord1, HWord2, HWord3, output [31:0] Word1, Word2, Word3); // [msb:lsb] bundle/bus

// ** Verilog93 - separated port naming and port declarations **// STRUCTURAL - Combinational Logic Circuit design ( Concurrent Operation )

B. Parameter parameter WIDTH = 5; // assign/drive net-connectors only once ELSE U-get "Error 10028 Can't resolve multiple constant drivers for net "?"."

C. Connectors //--Internal connectors--// //// 4-Assignable states ('0','1','X','Z'); Can be assigned an initial value. wire [7:0]Sum,DivOut = 0; // - wire (basic connector) General purpose wire wand [7:0]Active; // - wand (Wired AND) 0-Dominates; All connections to the wire are AND'ed together wor a; // - wor (Wired OR) 1-Dominates; All connections to the wire are OR'ed together tri b; // - tri (Wired tri-state) Single-Driver; triand, trior, tri0, tri1; all must be z except one driverline supply0 Gnd; // - supply0 (Wired Ground) Tied directly to power-level(0) supply1 Vcc; // - supply1 (Wired Power) Tied directly to power-level(1) reg [7:0]OperReg = 0; // - reg (Wired-Register) Reflects a variable value. wire Enable,EnableN; // Multiple items seperated by ','

D. Bit-Literals //--[ Drive-Line ]--// //// Bit-literal assignments (%bit-size'%base%%value%) assign Word2 = 123; // (default) 32-bit decimal assign Word3 = 32'd123; // 'd' = decimal Exactly the same as above reg [7:0]Div2 = 8'b0000_0010; // 'b' = binary '_' are ignored reg [7:0]Seven = 8'h7; // 'h' = hexidicamal assign W8C = 8'o377; // 'o' = octal

E. Logic Gates //--[ Logic Gates ]--// //// Primitives +--------------------------------------------------------------- not(Active[0],RstIn); // Gate-Syntax | not(o,i) = '~' notif(o,i) notif0() notif1() buf U1(DataLine,A8); // Named 'U1' | buf(o,i) bufif(o,i,e) bufif0() bufif1() assign EnableN = ~Enable; // BitWise-Syntax | and(o,i..) = '&' or() = '|' xor() = '^' assign Enable = ClkIn & RstIn; // | nand(o,i..) = '~&' nor() = '~|' xnor() = '~^' notif0(Trans1,DataIn1,EnableN); // Not-gate with a Tri-state output and an active-low('if0') enable. bufif1(Trans2,DataIn2,Enable); // Buffer with a Tri-state output and an active-high('if1') enable.

F. Algorithmic //--[ Algorithmic ]--// //// Operator Components assign Sum7 = AddTo7 + Seven; // '+' Addition '-' Subtraction/Negative '*' multiplica assign HalfOut = HalfIn / Div2; // '/' divide '%' modulus '**' exponent assign Shift = HalfOut << 1; // '>>' shift right '>>>' arithmetic right shift // And opposite for left-shift assign HWord1 = {1'b0,Sum7[6:0],Shift}; // '{}' concatenate - Combine "0,Sum7[6:0],Shift" to make 'HWord1' assign Word1 = {2{HWord1}}; // Replicate 'HWord1' twice to produce a twice as large connector bus 'Word1' Sum7 <= Sum7 << 1; // Left bit shift by 1

G. Abstraction (Generate, Sub, etc)

//--[ Generate ]--// //// Pre-compiler auto-line generator generate //// Example produces the equivalent of 4-stand lines: genvar i; // not Auto[0](HWord2[0],Seven[0]); for( i = 0; i <= 3; i = i + 1) // not Auto[1](HWord2[1],Seven[1]); begin:Auto // not Auto[2](HWord2[2],Seven[2]); not(HWord2[i],Seven[i]); // not Auto[3](HWord2[3],Seven[3]); end endgenerate //--[ Function ]--// function MyFunc( input n ); assign MyFunc = 1; endfunction //--[ Sub-Circuit Initialization ]--// //// Use a Sub-Circuit within this circuit SubCircuit Sub (.one(a), .two(b)); // IN[0] connects to macro IN (.a) and etc..

Page 29: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

H. Compiler Directives'timescale 1 ns/ 1 ps'define name code;'include “filename.v”; // Include the contents of a file at this point in the current file

I. Behavioral (Always@)// BEHAVIORAL - Sequential/Procedural logic (RTL-Modelling) ( Cannot assign net-connectors; only registers and variables )

always @(posedge ClkIn) begin // Triggers - @(posedge, %net), @(negedge %net), or @(%net) //both edges

reg m; // local //--[ Comparitors ] - Plexers – Coders

I.1 If Else BcdOut1 = (RstIn == 1) ? 0: 1; // '?:' IF...THEN Active[1] = (Comparison) ? TrueValue : FalseValue; if(ClkIn == 1 && RstIn != 1) BcdOut2 = 1; // '==' EQUALS '>=' Greater/Equal '&<=' Less/Equal '!=' Not Equal else if (RstIn == !ReqIn || ClkIn == 0) BcdOut3 = 1; // '!' NOT '&&' AND '||' OR

I.2 Case if(ClkIn == 1) begin case(AddTo7) // casex() to allow 'X', casez() to allow 'Z' and wild-card '?' but not 'X' 8'b0 : OddIn7 <= 1; // '<=' is for Synchronous logic where RHS is evaluated but only assigned on next trigger. 8'b1 : OddIn7 <= 1; 8'd3 : OddIn7 <= 1; default : OddIn7 <= 0; endcase end end

// SIMULATION - Testbench

initial begin // Executed once at very beginning of simulation end

J. Task task DoSomething; $display("Hi"); endtask time z; // Record current Sim time

//{SO} initial Initialize simulation execution block (Executes once at start of simulation)//{SO} wait(%condition) delay execution till condition is true.//{SO} #5 a = 20 a = 20 after 5 time units. Evaluate statement only after the delay in time units. //{SO} c = #5 a; c = a after 5 time units. 'a' is evaluated immediately then after delay it is assigned to 'c'.//{SO} fork...join Concurrent execute statements within

endmodule

module SubCircuit#(parameter PassedParam = 5)(input one, output two);assign two = ~one;

endmodule

4.3.2 VHDL Syntax

A. Include (LIBRARY / USE)--====================================================================================================================-- INCLUDE LIBRARIES (ie: Directories) to find Re-usable code--====================================================================================================================library work; -- Examples; 'ieee', 'textio', 'standard', ['std' & 'work' are always included by default]library std; -- Include "\altera\13.0sp1\quartus\libraries\vhdl\std"library ieee; -- Include "\altera\13.0sp1\quartus\libraries\vhdl\ieee"

-- Import Library.Package.Partsuse std.standard.all; -- Include the 'std.standard' package //Types 'BIT' 'BOOLEAN' 'INTEGER' 'REAL' data-types.use ieee.std_logic_1164.all; -- Include the 'std_logic_1164' package //Values 'Z'=Disconnect 'L'=Weak0 'H'=Weak1 'X'=Unknown '-'=DontCare 'W'=WeakUnknownuse ieee.numeric_std.all; -- Include the 'numeric_std' package //Allows arithmetic(+,-,/,*) on 'std_logic_1164' values.

B. External I/O (ENTITY...GENERIC/PORT)✔ GENERIC default class is CONSTANT – CONSTANT ADD_BITS: ….. is the same as just ADD_BITS: ….✔ PORT default class is SIGNAL – SIGNAL mux_out: OUT ….. is the same as just mux_out: OUT ….✔ FUNCTIONS & PROCEDURE can also be declared at the end of an ENTITY but not the COMPONENT declaration.

--====================================================================================================================ENTITY EntityName IS -- External I/O--====================================================================================================================

GENERIC ( -- Constructor / Instance Arguments --ADD_BITS : INTEGER := 4; -- Bit count for 'add'CLK_DIV : INTEGER := 15); -- Clock Divider by

PORT ( -- External Connectors ---- ID : Mode DataType :=Initial Valuedebounce_on : IN STD_LOGIC := '0';debounce_off : IN STD_LOGIC := '0'; -- SR Latch debounce requires double-throw switches (on/off)debounce_out : BUFFER STD_LOGIC := '0'; -- Buffers allow output to be wired to other internal circuitsdebounce_out_n : OUT STD_LOGIC := '0'; -- Inverted 'debounce_out'

Page 30: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

mux_in1 : IN STD_LOGIC := '0';mux_in2 : IN STD_LOGIC := '0';mux_sel : IN STD_LOGIC := '0';mux_out : OUT STD_LOGIC := '0';

dmux_in : IN STD_LOGIC := '0';dmux_sel : IN STD_LOGIC := '0';dmux_out : OUT STD_LOGIC_VECTOR ( 1 DOWNTO 0) := "00"; -- Initial Value on both wires is '0'

add_in1 : IN STD_LOGIC_VECTOR ((ADD_BITS - 1) DOWNTO 0) := "0000";add_in2 : IN STD_LOGIC_VECTOR ((ADD_BITS - 1) DOWNTO 0) := "0000";add_sum : OUT STD_LOGIC_VECTOR ((ADD_BITS - 1) DOWNTO 0) := "0000";add_carry : OUT STD_LOGIC);

clk_in : IN STD_LOGIC := '0';clk_out : BUFFER STD_LOGIC := '0';

SegDisplay : OUT STD_LOGIC_VECTOR (6 DOWNTO 0)); -- 7 Segment DisplayEND EntityName;

C. ARCHITECTURE (Declarations)✔ SIGNAL / CONSTANTS / TYPE / SUBTYPE definition area local to the Architecture✔ FUNCTION / PROCEDURE / COMPONENT declarations are generally declared here.

--====================================================================================================================ARCHITECTURE ArchitectureName OF EntityName IS--====================================================================================================================

--[ Inter-Architecture ]-----------------------------------------------------------------------SIGNAL ABitIs1 : BIT;SIGNAL Bit1 : BIT; -- BIT is a basic data typeSIGNAL Bit2 : BIT;SIGNAL Bits : BIT_VECTOR(1 DOWNTO 0);SIGNAL Bits_n : BIT_VECTOR(1 DOWNTO 0);SIGNAL Bits_0 : BIT_VECTOR(3 DOWNTO 0);SIGNAL Bits_1 : BIT_VECTOR(3 DOWNTO 0);

SIGNAL add_sum_full : STD_LOGIC_VECTOR (ADD_BITS DOWNTO 0);-- +1 bit for full add sum of other 2.SIGNAL debounce_tmp : STD_LOGIC;

SIGNAL StateClk : STD_LOGIC; -- Clock that increments the state machineSUBTYPE TwoBits : STD_LOGIC_VECTOR(1 DOWNTO 0); -- Parse out any STD_LOGIC_VECTOR to only 2-bits.TYPE States IS ( Display1, Display2, Display3, Display4 ); -- Each State is enumerated (User-Defined-Type)TYPE SegMem IS ARRAY ( 1 TO 4 ) OF STD_LOGIC_VECTOR(6 DOWNTO 0); -- Build ROM for Segment Display of each number.

CONSTANT SegROM : SegMem := (x"F", -- index(1); Bits on 7 Segment display to show a '1'x"FF", -- index(2); Bits on 7 Segment display to show a '2'x"FF", -- index(3); Bits on 7 Segment display to show a '3'x"A"); -- index(4); Bits on 7 Segment display to show a '4'

C.1 COMPONENT--[ Declare ]---( Re-Use )-------------------------------------------------------------------------COMPONENT mitDFF

GENERIC( RisingEdge : BOOLEAN := TRUE );PORT(

d: IN STD_LOGIC;clk: IN STD_LOGIC;rst: IN STD_LOGIC;q: OUT STD_LOGIC);

END COMPONENT;

C.2 CONFIGURATION

When VHDL comes across a COMPONENT declaration how does it know the COMPONENT class is associated to the ENTITY? Answer: They both have the same name.

Actually every COMPONENT declaration has a configuration and the configuration that says use the same-named ENTITY is the VHDL “default” configuration.

The CONFIGURATION block allows the designer to specifically assign a COMPONENT Instance to an associated ENTITY.

-- Select a given architecture for your component instanceCONFIGURATION AnyConfigName OF

--(The Entity ----> Architecture ----> Instance : OfComponent) will point to (Library.Entity(Architecture))MyEntity IS FOR MyArchitecture FOR MyInstance : OfComponentName USE ENTITY LibraryName.EntityName(ArchitectureName);

end for; end for;END CONFIGURATION;

Typically the CONFIGURATION block will be in a Tree structure which will allow multiple assignments to parent level “FOR”

-- Why are two 'for' statements are nested? All 'for Instance'(s) under the main 'for Architecture' apply within the parent 'for acrchitecture' designated.CONFIGURATION ForMyEntity OF MyEntity IS

FOR MyArchitectureFOR MyFirstInstance : OfComponentName use entity work.ComponentOne(Synchronous_Arch); END FOR;FOR MySecondInstance : OfComponentName use entity work.ComponentOne(Asynchronous_Arch); END FOR;FOR OTHERS : OfComponentName use entity work.ComponentOne(MixedSignal_Arch); END FOR;

END FOR;END CONFIGURATION;

Page 31: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

CONFIGURATION blocks are typically defined at the end of the VHDL code which uses the COMPONENT definition.

D. BEGIN (Structural Design)----------------------------------------------------------------------------------------------------------------------BEGIN -- Circuit design----------------------------------------------------------------------------------------------------------------------

D.1 <= and => (SIGNAL Assignment)--[ '<=' & '=>' (Structrual) ]------------------------------------------------------------------

ABitIs1 <= '1'; -- '<=' assign; 'ABitIs1' = '1'Bits_n <= ( 0 => NOT Bit1, 1 => NOT Bit2 ); -- '=>' Named connection; connect Bits_n(0) to 'NOT Bit1' etc...Bits <= ( Bit1, Bit2 ); -- Positional connection; connect Bits(0) to 'Bit1' etc...Bits_0 <= ( OTHERS => '0' ); -- 'OTHERS' keyword; connect all other un-assigned bits to '0'

D.2 Logic Gates--[ Gates (Structural) ]-------------------------------------------------------------------------

debounce_tmp <= debounce_off NAND debounce_out; -- Support-for: NOT AND OR NAND NOR XOR XNORdebounce_out <= debounce_on NAND debounce_tmp; -- Cross wired NAND gates (order doesn't matter in structural)debounce_out_n <= NOT debounce_out; -- Inverted output

D.3 GENERATE--[ GENERATE (Structural) ]---------------------------------------------------------------------

G1: FOR i IN Bits_1'RANGE GENERATE -- Auto Generate assignment statements (must have a 'label:' pre-fix)Bits_1(i) <= '1';

END GENERATE;

D.4 WHEN...ELSE--[ WHEN...ELSE (Structural) ]------------------------------------------------------------------

dmux_out <= '0' & dmux_in WHEN (mux_sel = '0') ELSE -- When 'mux_sel' = 0; 'dmux_out' = Concatenate '0' & 'dmux_in'dmux_in & '0' WHEN (mux_sel = '1') ELSE -- When 'mux_sel' = 1; 'dmux_out' = Concatenate 'dmux_in' & '0'"ZZ" WHEN (mux_sel = 'U' OR mux_sel = 'Z') ELSE -- When 'mux_sel' = 'Z' or 'U'; 'dmux_out' = "ZZ" (disconnect)"--"; -- ELSE; 'dmux_out' = "--"(don't care)

D.5 WITH...SELECT--[ WITH...SELECT (Structural) ]-----------------------------------------------------------------

WITH (mux_sel) SELECTmux_out <= mux_in1 WHEN '0', -- Connect 'mux_out' to 'mux_in1' when 'mux_sel' = 0

mux_in2 WHEN '1', -- Connect 'mux_out' to 'mux_in2' when 'mux_sel' = 1UNAFFECTED WHEN OTHERS; -- ELSE; Don't change anything

D.6 Arithmetic & Casting--[ '+' & Casting (Structural) ]------------------------------------------------------------------

add_sum_full <= std_logic_vector(unsigned('0' & add_in1) + unsigned('0' & add_in2));add_sum <= add_sum_full((ADD_BITS - 1) DOWNTO 0); -- sumadd_carry <= add_sum_full(ADD_BITS); -- +1 bit carry-- STD_LOGIC_VECTOR doesn't support math functions because signed/unsigned binary isn't defined by it.-- Therefore; cast STD_LOGIC_VECTOR 'add_in1' & add_in2' to data type 'unsigned' for the '+' operation.

------------------------------------------------------------------------------------------------------------------------ BEHAVIORAL----------------------------------------------------------------------------------------------------------------------

E. PROCESS (Sequential Design)PROCESSes are Sequential blocks of code that begin execution only when activated by nodes that change state in it's sensitivity list.

✔ Sequential Code Blocks▪ PROCESS▪ FUNCTION▪ PROCEDURE

E.1 VARIABLE

✔ A VARIABLE is assigned using “:=”✔ A SIGNAL assignment uses “<=”✔ An Equals Comparison uses “=”

E.2 IF...THEN– IF <condition> THEN <assign>; ELSIF <condition> THEN <assign>; ELSE <assign>; END IF;

--vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvPROCESS(rising_edge(clk_in))

VARIABLE clkcnt : INTEGER := 0;

BEGIN – SYNCHRONOUS

--[ IF...THEN (Sequential) ]-------------IF clkcnt = CLK_DIV THEN

clkcnt := 0; -- Reset 'clkcnt'clk_out <= NOT clk_out; -- Toggle 'clk_out'

ELSIF clkcnt < 0 THENclkcnt := 0;

ELSEclkcnt := clkcnt + 1;

Page 32: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

END IF;

END PROCESS;

E.3 WAIT

WAIT Command is typically used only for Testbench Code; See Simulation✔ WAIT FOR <signal condition>;✔ WAIT ON <signals>;✔ WAIT UNTIL <time>;

E.4 CASE...WHEN--[ CASE...WHEN (Sequential) ]-------------CASE State IS

WHEN Display1 =>StateAsInt := 1;NextState := Display2;

WHEN Display2 =>StateAsInt := 2;NextState := Display3;

WHEN Display3 =>StateAsInt := 3;NextState := Display4;

WHEN OTHERS =>NextState := Display1; StateAsInt := 4;

END CASE;

E.5 FOR...LOOP--[ FOR...LOOP (Sequential) ]---------------FOR i IN SegROM'LOW TO SegROM'HIGHLOOP

IF ( i = StateAsInt ) THEN -- Find the 'SegROM(index)' for the State.SegDisplay <= SegROM(i); -- Drive the 'SegROM(i)' to the display to show the 'State' number.EXIT; -- Break out-of-loop

ELSENEXT; -- Example of continuing loop w/o finish.

END IF; END LOOP;

E.6 WHILE...LOOP--vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvPROCESS -- No sensitivity list when using 'WAIT'

VARIABLE State : States := Display1; -- Data Type 'States' is User-Defined.VARIABLE NextState : States := Display1;VARIABLE StateAsInt : INTEGER := 0;

BEGIN -- SYNCHRONOUSWAIT ON StateClk; -- 'WAIT ON' is same as 'PROCESS (StateClk)' must be first line after BEGIN

--[ CASE...WHEN (Sequential) ]-------------CASE State IS

WHEN Display1 =>StateAsInt := 1;NextState := Display2;

WHEN Display2 =>StateAsInt := 2;NextState := Display3;

WHEN Display3 =>StateAsInt := 3;NextState := Display4;

WHEN OTHERS =>NextState := Display1; StateAsInt := 4;

END CASE;

--[ FOR...LOOP (Sequential) ]---------------FOR i IN SegROM'LOW TO SegROM'HIGHLOOP

IF ( i = StateAsInt ) THEN -- Find the 'SegROM(index)' for the State.SegDisplay <= SegROM(i); -- Drive the 'SegROM(i)' to the display to show the 'State' number.EXIT; -- Break out-of-loop

ELSENEXT; -- Example of continuing loop w/o finish.

END IF; END LOOP;

-- --[ WHILE...LOOP (Sequential) ]--------------- WHILE (count = '1')-- LOOP---- END LOOP;

END PROCESS;END ArchitectureName;

Page 33: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

F. PACKAGE--===================================================================================================================================================-- PACKAGING ( Creating Custom Libraries )--===================================================================================================================================================--[ PACKAGE ]-- -- packages COMPONENTS, FUNCTIONS, and PROCEDURES into a "library" -- Abstraction in a Package has a declaration (.header) and architecture (PACKAGE BODY). -- (.header) can exist by itself when only TYPE/CONSTANTS are being declared. PACKAGE BasicTraining IS

-- Define an ENTITY as a COMPONENT for Re-Use (Definition is a copy of the ENTITY w/o the ARCHITECTURE)COMPONENT EntityName IS

GENERIC ( -- Constructor / Instance Arguments --ADD_BITS : INTEGER := 4; -- Bit count for 'add'CLK_DIV : INTEGER := 15); -- Clock Divider by

PORT ( -- External Connectors ---- ID : Mode DataType :=Initial Valuedebounce_on : IN STD_LOGIC := '0';debounce_off : IN STD_LOGIC := '0'; -- SR Latch debounce requires double-throw switches (on/off)debounce_out : BUFFER STD_LOGIC := '0'; -- Buffers allow output to be wired to other internal circuitsdebounce_out_n : OUT STD_LOGIC := '0'; -- Inverted 'debounce_out'

mux_in1 : IN STD_LOGIC := '0';mux_in2 : IN STD_LOGIC := '0';mux_sel : IN STD_LOGIC := '0';mux_out : OUT STD_LOGIC := '0';

dmux_in : IN STD_LOGIC := '0';dmux_sel : IN STD_LOGIC := '0';dmux_out : OUT STD_LOGIC_VECTOR ( 1 DOWNTO 0) := "00"; -- Initial Value on both wires is '0'

add_in1 : IN STD_LOGIC_VECTOR ((ADD_BITS - 1) DOWNTO 0) := "0000";add_in2 : IN STD_LOGIC_VECTOR ((ADD_BITS - 1) DOWNTO 0) := "0000";add_sum : OUT STD_LOGIC_VECTOR ((ADD_BITS - 1) DOWNTO 0) := "0000";add_carry : OUT STD_LOGIC := '0';

clk_in : IN STD_LOGIC := '0';clk_out : BUFFER STD_LOGIC := '0';

SegDisplay : OUT STD_LOGIC_VECTOR (6 DOWNTO 0)); -- 7 Segment DisplayEND COMPONENT;

FUNCTION DoSomething (VARIABLE a, b : INTEGER) RETURN boolean;-- PROCEDURE-- TYPE-- CONSTANTEND PACKAGE BasicTraining;---------------------------------------------------------------------------------------------------------------------------------------------------PACKAGE BODY BasicTraining IS -- A Package body is only necessary when a FUNCTION or PROCEDURE needs defined.

FUNCTION DoSomething (VARIABLE a, b : INTEGER) RETURN boolean;BEGIN

-- PACKAGE COMPONENT EXAMPLES--vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv--[ WAIT...UNTIL (Sequential)]PROCESS -- No sense list when using 'WAIT'BEGIN

WAIT UNTIL rising_edge(clk); -- Must be first statement after BEGINWAIT FOR 500 ns;

END PROCESS;--^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

--vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv--[ WAIT...ON (Sequential)]PROCESS -- No sense list when using 'WAIT'BEGIN

WAIT ON clk, rst; -- Must be first statement after BEGIN

END PROCESS;--^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

END FUNCTION DoSomething;

END PACKAGE BODY BasicTraining;

4.3.3 VHDL Usage

A. Simulation (TestBench)--===================================================================================================================================================-- SIMULATION ( VHDL Features that are NOT-Synthesizable are used for circuit simulation purposes )--===================================================================================================================================================ARCHITECTURE TestBench OF EntityName ISBEGIN

-- WAIT UNTIL clk'EVENT; -- PROCESS cannot have sensitivity list when using WAIT; Not part of sensitivity list

Page 34: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

-- WAIT ON clk; -- WAIT must be first statement in a No %sensitivy_list PROCESSS; WAIT ON clk is same as PROCESS(clk);-- WAIT FOR 30 ns; -- (Simulation Only)

-- ASSERT("Hi"); -- Manually display compiling errors and stuff.END TestBench;

entity test_counter is PORT ( count : BUFFER bit_vector(8 downto 1));end;

architecture only of test_counter is

COMPONENT counter PORT ( count : BUFFER bit_vector(8 downto 1); clk : IN bit; reset : IN bit);END COMPONENT ;

SIGNAL clk : bit := '0';SIGNAL reset : bit := '0';

begin

dut : counter PORT MAP ( count => count, clk => clk, reset => reset );

clock : PROCESS begin wait for 10 ns; clk <= not clk;end PROCESS clock;

stimulus : PROCESS begin wait for 5 ns; reset <= '1'; wait for 4 ns; reset <= '0'; wait;end PROCESS stimulus;

end only;

B. ClockDiv Circuit-------------------------------------------------------------------------------------------------------------------------------------------------- ClockDiv Circuit Design------------------------------------------------------------------------------------------------------------------------------------------------library ieee;use ieee.std_logic_1164.all;

entity ClockDiv isgeneric ( div: integer :=15 );port ( clkin: in std_logic; clkout: out std_logic);

end ClockDiv;

architecture ClockDiv of ClockDiv isbegin

process(clkin)variable output : std_logic;variable clkcnt : integer := 0;

beginif rising_edge(clkin) THEN

clkcnt := clkcnt + 1;if clkcnt = div then

clkcnt := 0;output := NOT output;

elseNULL;

end if;else

NULL;end if;clkout <= output;

end process;end ClockDiv;

C. Package Example------------------------------------------------- work.AnEntity with multiple architectures-----------------------------------------------LIBRARY ieee;USE ieee.std_logic_1164.all;ENTITY AnEntity IS

GENERIC (PropTime : TIME := 5 ns);PORT (OutPin : OUT STD_LOGIC);

END AnEntity;ARCHITECTURE FirstArch OF AnEntity IS BEGIN

OutPin <= '1' after PropTime;END FirstArch;ARCHITECTURE SecondArch OF AnEntity IS BEGIN

OutPin <= '0' after PropTime;

Page 35: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

END SecondArch;ARCHITECTURE AnyOthers OF AnEntity IS BEGIN

OutPin <= 'Z' after PropTime;END AnyOthers;--^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

------------------------------------------------- MyEntity that will configure various -- architectures of component 'AnEntity'.LIBRARY ieee;USE ieee.std_logic_1164.all;-----------------------------------------------ENTITY MyEntity IS GENERIC (EntityArg : TIME := 5 ns); PORT (PINS : OUT STD_LOGIC_VECTOR(2 DOWNTO 0) );END MyEntity;

-----------------------------------------------ARCHITECTURE MyEntity OF MyEntity IS

COMPONENT UseConfiguration ISGENERIC (TimeNS : TIME);PORT (Output : OUT STD_LOGIC);

END COMPONENT;BEGIN

MyFirstInstance : UseConfiguration GENERIC MAP (10 ns) PORT MAP (PINS(0));MySecondInstance : UseConfiguration GENERIC MAP (5 ns) PORT MAP (PINS(1));SomeOtherInstance : UseConfiguration GENERIC MAP (1 ns) PORT MAP (PINS(2));

END MyEntity;-----------------------------------------------CONFIGURATION OfMyEntity OF MyEntity IS

FOR MyEntityFOR MyFirstInstance : UseConfiguration use entity work.AnEntity(FirstArch)

-- Resolve pin mismatches between 'AnEntity' => 'UseConfiguration' COMPONENT-- GENERIC MAP and PORT MAP are NOT-NEEDED if the Pin Names in COMPONENT declare-- are the same as the 'AnEntity' ENTITY.GENERIC MAP (PropTime => TimeNS) PORT MAP (OutPin => Output);END FOR;

FOR MySecondInstance : UseConfiguration use entity work.AnEntity(SecondArch)GENERIC MAP (PropTime => TimeNS) PORT MAP (OutPin => Output);END FOR;

FOR OTHERS : UseConfiguration use entity work.AnEntity(AnyOthers)GENERIC MAP (PropTime => TimeNS) PORT MAP (OutPin => Output);END FOR;

END FOR;END CONFIGURATION;-----------------------------------------------

LIBRARY ieee;USE ieee.std_logic_1164.all;ENTITY TestBench IS END TestBench;ARCHITECTURE TestBench OF TestBench IS

SIGNAL CheckPins : STD_LOGIC_VECTOR(2 DOWNTO 0);COMPONENT MyEntity IS GENERIC (EntityArg : TIME := 5 ns); PORT (PINS : OUT STD_LOGIC_VECTOR(2 DOWNTO 0) );END COMPONENT;

BEGINU1 : MyEntity PORT MAP (PINS => CheckPins);

END TestBench;

D. Common Errors✔ VHDL Common Error Messages and Fixes

◌ signal does not hold value after clock edge - Usually only one item can be defined either at rising edge or falling edge but not both.◌ Multiply driven - Same as above◌ clock not locally stable - clk'EVENT cannot determine if rising/falling edge; no clk='1'◌ ignored unnecessary pin clk - means PROCESS(clk) is ignored because 'clk' wasn't used in the code

4.4 Synthesis ( Decoding / Compiling ) ✔ Synthesis tools read HDL (ie: RTL) code and generates lower-level Synthesized Net-list files to describe the circuit.✔ Synthesis = the process of transforming and optimizing (ie: Compiling) design entry into lower-level / simplest terms or elements (ie: NetList)✔ NetList = Text list of component networks – Details all the connections of blocks I/O lines and component specification.

◌ Net-list standards▪ EDIF = Electronic design interchange format – Input files (.edf)

◌ Net-lists can be used to ▪ Produce Layout for a photo-mask used in ASIC Wafer Fabrication (ie: IC Fabrication)▪ FPGA / PLD circuit programming (ie: Laying-out/Fitting/Place N Route) circuit into the FPGA.▪ Silicon Virtual Prototype Simulators (SVP) that simulate circuits as they would be on a silicon wafer.▪ Validate and Simulate Circuit Behavior

◌ Synthesis tools can be configured to▪ Optimization for speed▪ Optimization for size▪ Simulation Only outputting a simulation model

✔ Flat Compilation = All design is compiled and analyzed together into one “flat” net-list. (slow compilation times – turn on “Rapid Recompile”

Page 36: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

to only compile changes and speed up.)✔ Incremental Compilation = Partitioning large designs (even allow UN-finished partitions) by way of separate net-list files that get put together by incremental

compilation.

✔ VHDL keywords / constructs that can be Ignored by most Synthesis Tools (For Simulation only)◌ – after, (transportand inertial)◌ – wait forxx ns◌ – Fileoperations◌ – generic parameters must have default values◌ – All dynamically elaborated data structures◌ – Floating point data types, e.g. Real◌ – Initial values of signals and variables◌ – Multiple drivers for a signal (unless tri‐stated)◌ – The process sensitivity list is ignored◌ – Configurations◌ – Division (/) is only supported if the right operand is a constant power of ◌ Assert

▪ Report▪ Severity

✔ References◌ http://en.wikipedia.org/wiki/EDIF

◌ http://en.wikipedia.org/wiki/Netlist

4.5 Verification

✔ Terms / Acronyms◌ PVT = Process, Voltage and Temperature Analysis – How operation varies with varying PVT conditions.◌ MTBF = mean time before failures – How long before design failures appear (Higher is better); see Metastability and

synchronization registers

◌ IBIS = Input Output Buffer Information Specifications◌ VCD = Value Change Dump (Waveform standard) – A VCD viewer plots a wave form based on VCD-Values.◌ PLI = Programming Language Interface – Invoking C functions from Verilog (ie: System Call) Ex. Getting HEX images form file,

printing text in debug window.◌ HVL = Hardware Verification Langauge – Language specifically designed for HDL verification / testbench (Ex. E-Language, VERA,

TestBuilder C++)◌ PSL = Property Specification Language – (by Accellera) http://www.eda.org/vfv/docs/PSL-v1.1.pdf ( Sounds like it's a verification language )◌ VIP = Verification IP

▪ URM = Universal Reuse Methodology - https://verificationacademy.com/topics/verification-methodology

▪ UVM = Universal Verification Methodology - Standard used to verify designs written in SystemVerilog (http://www.accellera.org/community/uvm/ )

▪ OVM = Open Verification Methodology - Documented methodology with a building block library for verification

4.5.1 Simulation ( SPICE / NetList )

✔ HDL Simulation Levels◌ Functional / RTL Simulation – No Timing considerations◌ Gate-level Simulation – Includes Timing Analysis (Requires Post-Synthesis NetList)

✔ HDL Simulation Applications◌ ModelSim http://www.mentor.com/products/fv/modelsim/ ◌ Maia Simulation http://www.maia-eda.net/index.php?option=com_content&task=view&id=13&Itemid=47

◌ Wiki List of HDL Simulators http://en.wikipedia.org/wiki/List_of_HDL_simulators

✔ Simulation Implementation◌ Forced Input◌ WaveForm◌ TestBench◌ Test Vectors

✔ SPICE Simulation = Simulation Program with Integrated Circuit Emphasis ( SPICE Simulation often uses Schematic Entry to simulate circuitdesigns. )

◌ Common SPICE Applications▪ NI MultiSim by National Instruments (Previously ElectronicWorkbench)▪ Altium CircuitMaker▪ LTSpice is for transistor level model-ling.▪ Matlab

Page 37: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

◌ Details of SPICE▪ Synopsis owns HSPICE▪ Cadence owns PSPICE – OrCad contains PSPICE simulation.▪ ADICE – Analog Devices▪ LTSPICE – Linear Technology – ▪ Mica – Freescale Semiconductor▪ TISPICE – Texas Instruments

✔ Reference◌ http://en.wikipedia.org/wiki/SPICE◌ http://en.wikipedia.org/wiki/Category:Electronic_circuit_simulators◌ http://en.wikipedia.org/wiki/List_of_free_electronics_circuit_simulators◌ http://techdocs.altium.com/display/ALEG/Legacy+Downloads (Get CircuitMaker Free; EOL product)◌ http://en.wikipedia.org/wiki/LTspice ◌ https://verificationacademy.com/topics/verification-methodology - UVM/OVM

4.6 Target Hardware ( Fitting / Layout )

Circuit Designs can be implemented in various target hardware

✔ IC - Integrated Circuit - Single electronic chip package containing an electronic circuit✔ PCA - Printed Circuit Assembly - Physically interconnected electronic components on a Printed Circuit Board (PCB)✔ Programmable IC(s) - IC(s) with programmable interconnects that allow a circuit design to be programmed into the IC.

✔ See Also◌ http://en.wikipedia.org/wiki/Integrated_circuit - Contains full details about categories, scale integration, fabricating & packaging,

and families◌ http://en.wikipedia.org/wiki/Application-specific_integrated_circuit - ASIC is used to describe custom Integrated Circuits (IC)◌ http://en.wikipedia.org/wiki/Printed_circuit_board - A PCB with attached components is called a PCA

4.6.1 Integrated Circuits (IC) ✔ ASIC- Application Specific Integrated Circuit

◌ Integrated Circuit(s) designed to preform a specific task.◌ Widely used generic electronic circuits are often packaged in an IC.

✔ Categories◌ MSI - Medium-scale Integration = Chips with 10 to 100 gates◌ LSI - Large-scale Integration = More than 100 gates up to 1980s◌ VLSI - Very Large-scale Integration = After 1980s all complex chips were considered VLSI

✔ Manufacturing Steps◌ Circuit Design - Circuit is designed on computers using EDA software which typically stores circuit designs in a database◌ Data-Base Release (DBR) - Design is released (ie: committed) for IC/ASIC manufacturing◌ Wafer Fabrication - Circuit design is implemented on a silicon wafers at the “FAB” using photo-lithography technology. (Many IC(S) per wafer)◌ Wafer Sort - Automatic Test Equipment (ATE) tests each Integrated Circuit(IC) on the wafer using “wafer probe” technology.◌ Packaging - Wafers are cut (ie: Diced), put on a substrate where nodes are wire-bonded for external pins and then put into Chip-Packages

✔ See Also◌ http://en.wikipedia.org/wiki/Semiconductor_device_fabrication

A. Data-Base Release (DBR)✔ Data-Base Release is the process step at which the circuit design is frozen for IC manufacturing.

✔ Tape-Out - Process of creating Photo-masks from circuit design files used in IC Fabrication.◌ [ Circuit Design Files ] → [ Chip-Layout / place-n-route / fitting artwork files ] → [ Mask Shop ]→ [ Photo-Masks ]

✔ Reticle - A single IC-mask on a multi-part Photo-Mask

✔ See Also◌ http://en.wikipedia.org/wiki/Photomask ◌ http://en.wikipedia.org/wiki/Tape-out ◌ http://en.wikipedia.org/wiki/Photolithography

B. Wafer Fabrication (FAB) 1. Silicon Wafer (ie: Slice / substrate ) - Blank silicon plate on which many Integrated Circuit (IC) chips are created

a) Sea-of-Gates Template Wafers - Specially created wafers with an array of gates already fabricated in them; Further fab-ing in the interconnects will produce the IC.

Page 38: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

2. Fabrication a) Photo-Masks are used to implant/etch/grow the N and P semiconductor regions into the Silicon

Wafer b) DIE = One IC (ie: Chip) on a wafer c) LOT = Case of 25-Wafers for transport

d) Wafer Traveler = A list of process-steps at the fabrication facility (ie: “FAB”) required to create the circuitry of the design

e) Process Integration (PI) = Handles the fab processing of wafers ( ie: Traveler Steps )

✔ See Also◌ http://en.wikipedia.org/wiki/Wafer_%28electronics%29

C. Wafer Sort (Probe)✔ Probe Test ( ie: Wafer-Level Testing )

◌ 1st Silicon = A common term used when a new design reaches probe test for the first time (ie: The 1st wafer of the design)◌ ATE = Automated Test Equipment

▪ Wafer Cleaning – wafers are often cleaned with machines (see: Semi-tool)▪ Probe Testers – the chips on a wafer are tested by probing contact points ( see manufacturers such as Teradyne )▪ Laser(ESI-9820) – Often laser tools burn in Permanent IC settings and/or memory ( Otherwise One-Time Programmable

Memory (OTPM) is used )✔ Items like part number, origin factory, programmable repairs and default settings (TRIMS) are marked/set inside the chip itself. Repairs

offer the capability to fix/adjust some of the defects after the sensor has been fabricated.

✔ See Also◌ http://en.wikipedia.org/wiki/Wafer_testing

Page 39: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

D. Dice & Packaging✔ Dicing = The process of cutting each DIE from a wafer✔ Each DIE is then packaged into casings

◌ SIP single in line package◌ DIP dual in line package 2-Side through hole pins◌ PLCC plastic lead chip carrier 4-Side wrap around chip pins to fit in square socket◌ QFP quad flat pack 4-Side surface-mount pins◌ PGA pin grid array Bottom-side pins (ie: like plug-in CPUs)◌ BGA ball grid array PGA without pins just solder balls

✔ See Also◌ http://en.wikipedia.org/wiki/Integrated_circuit_packaging ◌ http://en.wikipedia.org/wiki/List_of_integrated_circuit_packaging_types

E. Final / Back-End TestAfter the IC is packaged; a final test or functional test is preformed to guarantee a working IC for the customer.

4.6.2 Programmable IC(s)

✔ FPGA - Field Programmable Gate Array – Design is loaded into SRAM blocks (volatile) creating needed interconnects and logic.✔ FPAA - Field Programmable Analog Array – An FPGA that allows for Mixed-Signal (Analog/Digital) programmable circuit design✔ PLD - Programmable Logic Device✔ PLA - Programmable Logic Array✔ PAL - Programmable Array Logic✔ GAL - Generic Array

✔ See Also◌ http://en.wikipedia.org/wiki/FPGA◌ http://en.wikipedia.org/wiki/FPGA_prototyping

◌ http://en.wikipedia.org/wiki/Programmable_logic

A. Field Programmable Gate Array (FPGA)✔ FPGA = A “Blank” Integrated Circuit (IC) Chip in which circuit designs can be programmed into them.✔ FPGA Architecture varies by vendor/model; below is example architectures of Altera and Xilinx

5. FPGA Vendors a) http://www.xilinx.com/ Virtex, Spartan, Kintex, Artix, Zynq(ARM) CPLD: CoolRunner, 9500Series b) http://www.altera.com/ Stratix, Arria, Cyclone(ARM) c) http://www.latticesemi.com/ ECP5 d) http://www.microsemi.com/ Previously ACTEL e) http://www.achronix.com/ Hand-held niche; Not general use FPGA(s) f) http://www.tabula.com/ 3-D High Speed FPGA(s) g) www.microsemi.com/products/fpga-soc MicroSemi h) Purchasing

• Xilinx Dev Boards - http://www.digilentinc.com/index.cfm

6. FPGA Development Boards ( Design Prototyping ) a) Altera

• List of Altera Dev-Boards @ http://www.altera.com/products/devkits/kit-dev_platforms.jsp• Popular provider (Terasic) @ http://www.terasic.com.tw/en/

b) Xilinx

Page 40: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

• Xilinx sells Dev-Boards directly @ http://www.xilinx.com/products/boards-and-kits/ • Popular provider (AVNET) @ http://www.avnet.com/en-us/Pages/default.aspx• XTEX FPGA Boards @ http://www.ztex.de/• Mojo (Open-Hardware) @ http://embeddedmicro.com/• Papilio (Open-Hardware) @ http://papilio.cc/

7. Altera Architecture a) FPGA = Field Programmable Gate Array – Depending on model contain 'x' number of LABs b) LAB = Logic Array Block – Each LAB contains (16)LEs. c) LE = Logic Element – Each LE contains (4)LUTs. d) LUT = Look Up Table – An electronic truth table to implement a variety of logical gates.

8. Xilinx Architecture a) FPGA = Field Programmable Gate Array – Depending on model contains 'x' number of CLBs b) CLB = Configurable Logic Block – Each CLB contains (4)Slices c) Slice = No Accrymn – Each Slice contains (2)LCs d) LC = Logic Cell - Each logic cell contains (2)3-input LUT a Full-Adder(FA) and an output register (DFF – D

Flip Flop) e) LUT = Look Up Table – An electronic truth table to implement a variety of logical gates.

9. FPGA Architecture (In General) a) [LUT/ALM] - Each LE/LC typically includes a 4-input "Look-Up Table" instead of gates; like a truth-table.

• ALM(adaptive logic module) - is a type of LUT that includes a [FA]full adder and [FF]flip-flop.• The 4-Input LUT standard is maintained in ALM for compatibility.• Typically there are 4 or 5 LUTs per LE making 16 or 32 possible row truth table (old was 3-LUT or 8-bit)

b) [Macro-Cell/Resource-Blocks] LE; High-Level functionality blocks - Some LE's are hard-wired functions; IP(Intellectual Property Cores)• PLL phase-lock loop; DLL delay lock loops (Dynamically phase-shift strobes for memory interfaces / temperature change

adaptability)• IO Bank; pad slew rate and drive strength (programmable)• SRAM memory• HS-Transceivers• FPGAs has IO control (IO elements) slew control, LVDS, pull-up, clamps, and etc.. Bi-directional has OE (output-enable)

• [IOB]Input/Output Block• Also have dedicated resource blocks (memory blocks, FIFO, MLABs memory labs, math operations)

• SRAM cells ( stores how the LABs logic and PLL clocks will work ) gates input come form the SRAM cell.• Because of SRAM cells the FPGA must be programmed on power-up (SRAM is volatile)

c) // Register packing - refers to the use of the LUT and FF in a logic element(LE)

d) PI - Matrix of "Programmable interconnects" in a Row/Column layout• Clock signals and other high-fan-out signals(ie: global buffers) are routed independently of logic interconnects.• PI's can contain both local-networks for adjacent LE's or Row/Col for entire grid.

Page 41: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

• FPGAs have dedicated clock pins and clock control blocks e) Terms

• “Device Atoms” – A LUT of DFF or FA within the FPGA architecture is called a device atom.

10. Programming a FPGA/PLD✔ IC-Programming-Unit – Older PLD's with PROM, EPROM or Fuse-Memory required a physical tool to program the chip.✔ In-System-Programming (ISP) – Circuit board has a JTAG header plug-in for programming chips within the circuit.

B. Programmable Logic Devices (PLD)

✔ PLD / GAL are the root/parent technology that led into FPGA technology

1. SPLD = Simple Programmable Logic Devices a) PLA - Programmable Logic Array = Programmable interconnects on AND & OR gates b) PAL - Programmable Array Logic = Device (AND programmable / OR hard-wired

2. CPLD = Combinational / Complex Logic Device a) Architecture

• Contain multiple PLD/PAL logic arrays in one• Macro-cell = Term used to signify the logic capability count

• Equivalent-Gates = term used to describe the count of NAND gates required to implement a design• Each Macro-cell uses 20-gates so an 8-macrocell PLD can have 160-gates and a CPLD with 500-macrocells supports 10,000 gates.

4.6.3 Printed Circuit Assemblies (PCA)

✔ Printed Circuit Assembly (PCA) = Printed Circuit Board (PCB) with components attached

1. PCB Etching - Copper Traces/Routes are created on fiberglass boards typically using a photo-plotter and copper etchant chemical.

2. Part Placement

a) Through-hole Technology (THT) - Component leads are inserted through holes in the PCB board.• CNC Milling Machine - Holes in the PCB board are created using automated drilling machines• Wave Soldering machine - Component leads are soldered to the PCB board using a machine that creates waves of molten solder

b) Surface Mount Technology (SMT) - Components are placed on pads on the PCB board.• SMT metal stencil - A metal template/stensil used to apply solder paste to component pin locations on a PCB board.• Re-flow Oven - A programmable oven used to melt the solder paste on a PCB.

c) Pick N Place - Components for the circuit design are picked and placed onto the circuit board typically by “Pick N Place” automatic equipment• Tape Reel - Spool of electronic components used by Pick N Place machines.

3. PCA Testing a) ICT = In-Circuit-Test is a test instrument that has a bed of nails (ie: Connectors) that measure and test the completed circuit board. b) Flying-Probe = Flying-Probes can also be used for a cheaper and not as thorough In-Circuit-Test measure and device testing.

4. Functional Testing = Finally the circuit board is powered up under normal operating circumstances and tested for sale-quality functionality.

✔ See Also◌ http://en.wikipedia.org/wiki/SMT_placement_equipment - SMT

◌ http://en.wikipedia.org/wiki/In-circuit_test - ICT◌ http://en.wikipedia.org/wiki/Flying_probe - Flying Probe

5. CIRCUIT DESIGN SOFTWARE (EDA / ECAD)

✔ EDA - Electronic Design Automation = Category of PC-Software specifically for System Circuit Designing (ie: Electronic Engineering )✔ ECAD - Electronic Computer Aided Drafting = Another term for EDA; Software tools are considered a sector of the Computer Aided Design (CAD) category✔ CAE - Computer Aided Engineering = Yet another term for Computer Aided Design (CAD)

✔ Wiki list of EDA Vendor Software packages http://en.wikipedia.org/wiki/Category:Electronic_design_automation_companies✔ Wiki comparison list of EDA Software packages http://en.wikipedia.org/wiki/Comparison_of_EDA_Software

✔ EDA Tools were originally created on Linux OS Shells.◌ EDA Tools typically contain a slew of “<command>.exe” files inside the tools sub-directory◌ EDA Tool commands typically can be invoked entirely from the OS command line

▪ Graphical User Interfaces (GUI) s are usually just helper tools that auto-launch commands)

◌ Tcl = Tool command language – Tcl is a Linux scripting language / shell (windows ported); It is used heavily in EDA tool automation (ie: Tool Integration).✔ SDL = Specification and Description Language

---[ Sample List of EDA Vendors and tools (based on assumed popularity)]---✔ Synopsis

◌ Synplify – FPGA design solution by Synplicity (Acquired by Synopsis in 2008)

Page 42: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

✔ Mentor Graphics◌ Leonardo Spectrum = CPLD, FPGA or ASIC Synthesis◌ Precision RTL◌ ModelSim

✔ Cadence◌ Virtuoso = Schematic editor

http://www.cadence.com/products/rf/schematic_editor/pages/default.aspx◌ Allegro SPB = Design Tool Suite◌ Spectre = Mixed signal (chip level) Simulation◌ OrCad = PCB design Free size limited download http://www.orcad.com/◌ Allegro Design Entry CIS = Component Information System – also known as OrCAD Capture CIS◌ SimVision = Unified graphical debugging environment (Waveform simulation)

✔ Xilinx (FPGA/CPLD)◌ Vivado

✔ Altera (FPGA/CPLD)◌ Quartus-II◌ Qsys = Previously “SOPC-Builder”

✔ Reference◌ http://en.wikipedia.org/wiki/Synopsys – http://www.synopsys.com/home.aspx Commercial◌ http://en.wikipedia.org/wiki/Mentor_Graphics – http://www.mentor.com/products/fpga/synthesis/ Commercial◌ http://en.wikipedia.org/wiki/Cadence_Design_Systems – http://www.cadence.com/en/default.aspx Commercial◌ http://en.wikipedia.org/wiki/Altium – http://www.altium.com/ Commercial◌ http://en.wikipedia.org/wiki/GEDA – http://www.geda-project.org/ OpenSource◌ http://en.wikipedia.org/wiki/KiCAD – http://www.kicad-pcb.org/display/KICAD/KiCad+EDA+Software+Suite OpenSource◌ http://en.wikipedia.org/wiki/Electronic_design_automation EDA Software

5.1 Altera Quartus-II 1. File extensions

• bdf - block design file (schematic)• bsf - block symbol file (symbol)• edf - EDIF; Vendor neutral schematic &amp;amp design file format (Electronic design interchange format)• lmf – ASCII files used to map EDIF(.edf) and Verilog Quartus mapping files (.vqm) (Other Vendor HDL → Quartus Logic)• mif - memory initialization file• ncf - Altera Monitor Program [NiosII] Project File• pof - "Programmer object file" compiled project file to upload to FPGA's FLASH for Active-Serial mode (see also .sof)• ppf - Pin Planner• qar – Archived (like zipped) quartus project – Quartus → Project → “Archive Project” / “Restore archived project”• qip - Quartus IP-Core project file• qpf - Quartus project file• qsf - Quartus settings file; Can add PIN-Assignments here - set_location_assignment PIN_N25 -to x1 (File is in Tcl syntax)• qsys - Hardware contents of a Qsys System• sdc - Synopsys Design Constraints; Component Simulation parameters text file (Created manually or with the TimeQuest)• smf - State machine file• sof - "SRAM object file" compiled file to upload to FPGA• sopcinfo - Description details of the associated 'Qsys' file in XML (Used to generate the BSP for software design - the build tools)• sym - Symbol file• tdf - "text design file" written in AHDL Altera hardware description language (AHDL)• vho – Simulation structural NetList• vht – ModelSim generated VHDL test-bench files• vqm – Verilog Quartus mapping files – node-level or atom net-list text file• vwf - Simulation waveform to set node levels at simulation time.

2. Projects a) Project File = <ProjectName>(.qpf); a “revisions” text file that points to <ProjectNameRevision>(.qsf) b) Project Settings = (.qsf) projects contents and settings text file stores settings made in Quartus → Assignments menu c) Set Default Projects Folder = Menu → Tools → Options → General → “Default File Location” (@Bottom) d) Import/Export Pin Assignments = Menu → Assignments → Import (Retrieve Pin Assignments) or Export (Save Pin Assignments) e) Pin Driving (Including UN-Used) = Menu → Assignments → Device → “Device and Pin Options” (max I/O @ 240mA) f) Auto-settings by specification = Menu → Tools → “Laungh Design Space Explorer” (Uses SDC timing constraints file with

TimeQuest to meet goals) g) Project Revisions (Diff settings) = Menu → Project → Revisions (ie: Compilation Settings Revisions not Source File Revisions ::

Creates new .qsf file)• Compare Revisions = Menu → Projects → Revisions → Compare

Page 43: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

• Select Revision for Synthesis = Project Navigator → Revisions → Right-Click and select “Set Current Revision” h) Copy Project = Menu → Projects → “Copy Project” – Ideal way to create a new project based on existing one i) Specify timing constraints (SDC) = Menu → Tools → TimeQuest Timing Analyzer – Analyzes timing constraints on compiled design j) Quartus Database for teams = Menu → Projects → “Import/Export Database” and “Clean Project”

3. Quartus Folders a) Error Message Details = Menu → Help → Message List – Points to <Install-

Path>/quartus/common/help/webhelp/) b) Altera Device List = Menu → Help → Devices and Adapters – Points to <Install-

Path>/quartus/common/help/webhelp/) c) EDA Interfaces (Other EDA Tools) = Menu → Help → EDA Interfaces – Points to <Install-

Path>/quartus/common/help/webhelp/) d) Getting Started Tutorial = Menu → Help → Getting Started Tutorial – Points to <Install-

Path>/quartus/common/help/tutorial/qtutorial.htm) e) Altera supplied IP-Cores = Menu → Tools → IP Catalog (MegaWizard) – <Install-Path>/ip/altera/<IP-Core> f) Generate Tcl Project Script = Menu → Projects → “Generate Tcl file for project”

** Add <Install-Path>/quartus/bin64 to Command Line PATH to use 'quartus_sh -qhelp'

4. Validation Tools a) Auto device selected by Fitter = feature that will pick a suitable Altera FPGA upon design compilation. b) Device Migration = tools that allow designs to move between different FGPA IC-Chips c) PowerPlay Power Analyzer = Estimates power usage for the Circuit implemented on a PCB board. d) Early Pin planning = PCB layout is determined before hand where pin locations must be verified by FPGA fitter software to

avoid board changes.• The pin planner interfaces with the IP-Core parameter editor and pin-outs created in top-level design file then “Start I/O assignment

analysis”• Then to a board-aware analysis = “Enable Advanced I/O Timing Options”

e) Simultaneous Switching Noise (SSN) = Analyzes / checks for noise /distortion voltage across I/O traces. f) Design Assistant = Checks design for adherence to Altera guidelines (Can also use a “lint” tool for coding style checks) g) TimeQuest Analyzer = Thorough circuit timing analysis tool

• tsu = Input setup time• th = Input hold time• tco = clock to out delays• tpd = Propagation delay – pin to pin delays• Fmax = Maximum clocking frequency

Clock Period = tco + data delay + setup time – clock skew= tco + B + tsu – (E -C)

Fmax = 1/Clock Period

Page 44: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

5.1.1 Qsys Designer (SOPC)✔ Qsys = Embedded System Design Tool (Previously SOPC-Builder)

◌ Systems are constructed by adding (ie: picking N choosing) Qsys Components (ie: IP-Blocks / Cores with common system bus)

◌ Qsys auto-generates▪ HDL files - Circuit design files▪ Boot-loader - HEX-Code for the system start-up▪ “_hw.tcl” - Hardware Components Description File▪ SOPCinfo - Specification file for the Board Support Package (BSP)

◌ Implementation▪ Component names - (ie: IP-Block Names) in Qsys are used by firmware to access the hardware▪ System is synthesized - [SOF] → [FPGA] → [HAL] → [BSP](system.h) → Applicaion(?.elf)

▪ FIFO(s) are used to connect FPGA IO-Pins to the processor.▫ IN-FIFO & OUT-FIFO both connected to the data bus▫ ( In exports In-Bus / Out exports out bus )

▪ HAL Hardware abstraction layer (library) FPGA

✔ HAL✔ Altera SBT (The NiosII SBT (System Build Tools) Generates → HAL Board Support Package (BSP))

◌ SBT for Eclipse takes the sopcinfo data and generates HAL(Hardware abstraction layer) -> Component Drivers▪ system.h – Defines symbols for referencing hardware in the system (BSP) part of the board support

package▪ boot-loader (Intel HEX) – Initialization information for on-chip memories (initializes contents)▪ .a = Single user library project ( doesn't contain main() )

◌ HAL = Hardware Abstraction Layer▪ newlib▪ Device drivers

◌ Eclipse (C/C++) with the NiosII build chain▪ Compiles to ?.elf file – the executable for embedded processor▪ elf = Executable and Linking File – format is result of compiled C/C++ application▪ ELF - Executable and Likable Format = Binary File Format (Flexible file format for binary code)

◌ NiosII SBT Command Line◌ Optional Libraries

▪ NicheStack TCP/IP Stack▪ Read-only ZIP file system

Page 45: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

▪ Host File System (Refer to HAL) ✔ Software Development for the NiosII system - "Getting started with the Graphical User Interface" @ NiosII Software Developers Handbook

▪ http://www.altera.com/literature/hb/nios2/n2sw_nii52017.pdf✔ Reference

◌ Altera Tutorial “Nios II Hardware Development Tutorial”◌ Altera http://www.altera.com/support/examples/design-entry-tools/qsys/qsys.html ◌ University Courses w/Qsys http://myweb.wit.edu/johnsont/

5.1.2 Soft Core Processors✔ NiosII ( Master of Avalon Interconnect Fabric )

◌ /e◌ /s – Standard Edition◌ /f◌ NiosII w/MMU = NiosII for Linux; no System Build Tools (SBT) support

✔ Registers ( Memory Mapping I/O )◌ Register offsets are assigned within Qsys◌ Avalon-MM ( Master / Slave type architecture )◌ Control Registers◌ Status Registers◌ Qsys sets up separate command / response networks to IP-Block

▪ 2x-throughput

✔ Instruction Cache Memory

✔ Ports◌ data_master = The processors data bus

▪ Avalon-ST = Streaming interconnect fabric◌ instruction_master = retrieves instructions

▪ instruction_master → jtag_debug_module ( connection to processor for debug/firmware download)✔ Interconnect Fabric

◌ Connection Fabric = A "Standard" that allows internal connections between Processor and peripherals (A Standard Control, Data, and Address Bus connectors)

◌ Connection fabric also named NoC(Network-on-chip) Architecture; The arbiter for IP Packet transform to various IP components◌ The Nios II HAL(Hardware abstraction layer) interprets low IRQ values as higher priority.◌ HAL - Hardware abstraction layer and peripheral drivers (Software that generates C headers for Custom Nios)◌ Examples;

✔ ALTERA; Avalon Fabric including Avalon-MM(Memory-Mapped I/O) and Avalon-ST(Streaming) as well as ARM Structure and AIX4✔ Configure

◌ Reset Vector Offset = 1st Address (boot-loader / image / custom )◌ Exception Vector = Act of responding to an exception and then returning to pre-exception state.

▪ NiosII.Processor.Reference page 3-31▪ http://www.johnloomis.org/NiosII/interrupts/exception2.html

◌ Pipe-lining Support for up to 4-pipelines◌ Base Address - Nios II processor cores can address a 31-bit address span.

▪ You must assign base address between 0x00000000 and 0x7FFFFFFF (Over is a negative number)

✔ SOPC-Peripherals◌ SysID to match firmware with processor core◌ Generating Systems with Qsys◌ Simulation◌ DMA direct memory access controller◌ DMA - Direct memory access "controller"; DMA is nothing more than a way to bypass the CPU to get to system memory and/or I/O.

Page 46: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

▪ http://www.ganssle.com/articles/adma.htm◌ “Bus Request" (AKA "Hold" on Intel CPUs) is an input that, when asserted by some external device, causes the CPU to tri-state it's pins

at the completion of the next instruction.◌ “Bus Grant" (AKA "Bus Acknowledge" or "Hold Acknowledge") signals that the processor is indeed tri-stated. This means any other

device can put addresses, data, and control signals on the bus. The idea is that a DMA controller can cause the CPU to yield control, at which point the controller takes over the bus and initiates bus cycles. Obviously, the DMA controller must be pretty intelligent to properly handle the timing and to drive external devices through the bus

◌ What peripherals will Nios connect to (add/remove PIO, VGA, etc..)

✔ Digital circuit logic can be 'positive logic' where high-voltage = 1 or 'negative logic' where low-voltage = 1✔ . Vdd - is Maximum voltage (~5 to 1Vdc)✔ . V1,min --- * Between V0,max and V1,min is 'undefined'✔ . V0,max--- * No assumed value except in transitional phase.✔ . Vss - is Minimum Voltage (GND)

5.1.3 IP-Cores✔ Mega-Functions = Altera Quartus installs off-the-shelf configurable IP cores optimized for Altera devices (OpenCore Plus IP)✔ Quartus → Tools → IP Catalog (Previously “MegaWizard Plug-In Manager”)

◌ Basic Function IP◌ DSP Function IP◌ Interface Protocol IP◌ Memory Interfaces and Controller IP◌ Processor and Peripherals IP ( Covered in Qsys Section – Above )

▪ Licensed IP's can be used locally as▫ Untethered = run for a limited time▫ Tethered = indefinite usage but only when connected to host PC

◌ (.qip) and (.qsys) files can be added directly to a project – Project Navigator → Files → Right-Click Add/Remove files.✔ IP-Cores

◌ Include Design Libraries = Quartus → Assignments → Settings → Libraries ▪ Project library setup in (.qsf)▪ Global library setup (quartus2.ini) – Via SEARCH_PATH setting

◌ When searching for IP-Cores the project directory takes precedence over all others.✔ See

◌ DSP Solution Center http://www.altera.com/technology/dsp/dsp-index.jsp◌ Altera IP literature http://www.altera.com/literature/lit-ip.jsp

✔ IP-Cores can be instantiated in HDL code◌ By Name with parameters (In VHDL you must “include” the associated libraries)

▪ Verilog Altera IP-Core Instancealtfp_mult inst1 (.dataa(wire_dataa), .datab(datab), .clock(clock), .result(result));defparam

inst1.pipeline = 11,inst1.width_exp = 8,inst1.width_man = 23,inst1.exception_handling = "no";

▪ VHDL Alter IP-Core Instancelibrary altera_mf;use altera_mf.altera_mf_components.all; …inst1 : altfp_mult generic map (

pipeline => 11,width_exp => 8,width_man => 23, exception_handling => "no")

port map (dataa => wire_dataa,datab => datab,clock => clock,result => result);

5.1.4 Schematic & HDL Editors 1. Alteras University Program Training Resources at ftp://ftp.altera.com/up/pub/Altera_Material/13.0/Tutorials/ or

{ ftp://ftp.altera.com/ } a) Steps of the flow can be set just below the project browser b) Chip Planner draws the FPGA/LAB/LE used on the chip c) RTL simulation?

2. Simulating a Circuit

Page 47: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

a) File > New > VWF; Edit > Insert > Node or Bus > Node Finder > List > Select and Add > OK > Drag area and click to apply levels b) Click "Run a Functional Simulation Button" c) Click "Run a Timing Simulation" (Full Compilation required)

3. Programming the FPGA a) JTAG - when switch position is in "Run" during programming b) AS (Active Serial) - Design is loaded into on-board flash; switch in "Prog" during programming

4. Backup DE2 FPGA Flash a) Open Programmer b) Set Mode to "Active Serial" and set board switch to "Prog" c) "Add Device" and choose "EPCS16" (the flash unit) d) Select "Examine" then "Start" to load the flash contents e) Click "Save" to save the contents to a .pof file.

5. Templates – Quartus → Edit → Insert Template (Drops template code in the open HDL file.)

5.1.5 Design Simulation ( Debug / Performance )

A. Simulation 1. Altera comes with 2-Simulation Tools that can do either RTL or Gate Simulation

a) Qsim – By Altera b) ModelSim – By Mentor Graphics

2. Simplest way to do this is File > new (University Program VWF; add nodes adjust wave-forms; save) 3. Reference

a) Wiki List of Simulators http://en.wikipedia.org/wiki/List_of_HDL_simulators

B. TimeQuest Timing Analyzer✔ Executable is 'quartus_sta.exe'

◌ Auto generate SDC Template = Quartus → TimeQuest Analyzer → Constraints → “Write SDC File”

C. ELA – Embedded Logic Analyzer ELA - Embedded logic analyzer HPS - hard processor system (ie: SOC); FPGA is much slower than HPS. NI Labview - National Instruments Labview is a high-level system design tool that converts graphical block diagrams into digital hardwarecircuits NetList - is a circuit connection text file (typically fed into a SPICE simulator to generate XY-plot analysis using Differential non-linear and calculus/engineering equations. * IBIS (Input/Output Buffer Information Specification) - Hides SPICE model by assigning IO specifications of the device for board level simulation - Companies involved in FPGA design - Aldec Active HDL Simulator - Synopsys Design Analyzer - Synopsys Design compiler

5.1.6 Bugs / Gotchas✔ Below error occurs when using Eclipse Nios

0 [main] bash 312 find_fast_cwd: WARNING: Couldn't compute FAST_CWD pointer. Please report this problem tothe public mailing list [email protected]

{ http://www.alteraforum.com/forum/showthread.php?t=44672&s=1dc3d4440ab489c8969dbfcca15baffe&p=189487#post189487 }{ http://www.alteraforum.com/forum/showthread.php?t=43526&GSA_pos=2&WT.oss_r=1&WT.oss=Couldn%27t%20compute%20FAST_CWD%20pointer }Download / Install most recent Cygwin w/Perl for both x86 and x86_64.

I Renamed original folders C:\altera\13.0sp1\quartus\bin\cygwin to \cygwin_originalC:\altera\13.0sp1\quartus\bin64\cygwin to \cygwin_original

Created new empty ....\cygwin foldersCopy paste recent Cygwin into their respective directories C:\altera\13.0sp1\quartus\bin\cygwin (x86) and C:\altera\13.0sp1\quartus\bin64\cygwin (x86_64) directories respectively.

✔ ModelSim won't simulate the NiosII/s soft-coreNiosII/s proprietary = Remove ModelSim-Altera setting on project start-up

✔ Qsys - "Failed to query available BSP types"Have to take a different route

Page 48: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

error dialog shown below ("Failed to query available BSP typesI filed a service request and received the following reply:

"There is a bug in the GUI for the bsp creation page for Nios II Software Build Tools for Eclipse in ACDS 13.0. The bug is currently planned to be fixed in 13.1. We are sorry for any inconvenience caused due to this bug.As a workaround for this issue, instead of choosing New->Nios II Board Support Package, choose the option New -> Nios II Application and BSP from Template. Select the template Hello World if you would like to have Altera HAL as the Operation System, else select Hello MicroC/OS-II if you would like to include the MicroC/OS-II RTOS. Please note that you should not click "Next", so that you won't be directed to the bsp page which has bug. Click finish after you have filled in the required information. The bsp project created will be automatically named as %application project name you specify%_bsp. You may delete the application project later if it is not needed."

✔ Using command line options in Windows• Add <Install-Path>/quartus/bin64 to environment variable PATH to use 'quartus_sh -qhelp'

**LEAVE OpenCore Plus Status Pop-Up box open else ELF will fail to download. (This message notifies that one of the IP-Cores used requires licensing for in-production use)

5.2 Xilinx ISE / Vivado

A. System-Level Tools 1. Xilinx Soft-Core Processors

a) MicroBlaze b) PicoBlaze

B. Circuit-Level Tools 2. IP-Integrator (Previously ISE)

Page 49: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

5.3 ModelSim

✔ Features◌ Altera Quartus-II Installer includes ModelSim-Altera Starter edition◌ ModelSim has a “Transcript” command prompt which is actually a TCL shell prompt with necessary imports.◌ GUI providing tools to create and/or simulate design projects

▪ Menu → File → New → Project▫ Altera Quartus builds a ModelSim include file at C:\altera\13.0sp1\modelsim_ase\modelsim.ini

▫ Includes Libraries such as: C:\altera\13.0sp1\modelsim_ase\altera\vhdl\altera_mf▫ Folder $MODELSIM_TECH = C:\altera\13.0sp1\modelsim_ase\win32aloem\

✔ Paths◌ Program File = C:\altera\13.0sp1\modelsim_ase\win32aloem\modelsim.exe◌ Working Directory = C:\altera\13.0sp1\modelsim_ase

▪ .\altera\ = Altera Mega-function simulation files. ▪ .\docs\ = Documents and tutorial guides (as well as a Tcl help guide)▪ .\examples\ = ModelSim Help/Tutorial example files▪ .\modelsim.ini = Text file that will include all the locations of Altera Mega-function simulation code▪ .\ieee\ = simulation code for the 'IEEE' library▪ .\win32aloem\ = The ModelSim Executable directory

✔ File Associations◌ (.mpf) – ModelSim project file = Text file containing all files and settings for a simulation project (App; ModelSim.exe)◌ (.wlf) – Simulated Waveform = Mentor graphics proprietary waveform (App; ModelSim.exe)

▪ See Also http://en.wikipedia.org/wiki/Waveform_viewer

✔ Usage◌ Work Directory - Choosing the directory that ModelSim will work out of

▪ 1) Menu → File → Change Directory▪ 2) The Directory chosen will need a “work” sub-folder (ie: Library) and can only be properly created by using

▫ ModelSim> vlib work▫ Right-Click in the Library browser and select 'new' → 'library' → 'a new library' and give the new sub-folder / library a name.

◌ Compiling - The Design Files (Verilog / VHDL) or Testbench files▪ ModelSim> vcom -reportprogress 300 -work work D:/Electronics/CAD/_Projects/MyDFF2/MyDFF2.vhd▪ Menu → Compile → Compile and choose File▪ Once Compiled the output files will be stored in the 'work' library / folder. (Files .dat, .dbs, .prw, .psm )

◌ Simulate - Load / launch the simulator▪ ModelSim> vsim -gui work.mydff2▪ Menu → Simulate → 'Start Simulation' and pick the Verilog / VHDL file to simulate

Page 50: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

6. SYSTEM SOFTWARE

✔ Common System Software◌ Bootloaders = Bare-Metal programs loaded sequentially to initiate basic usage◌ BSP - Board Support Package = Collection of Device Drivers to expand hardware control◌ OS - Operating System = A set of software libraries used to manage hardware & isolate software from hardware.

✔ System Software Configurations◌ Simple Structure (ie: No Operating System) = An Operating System is optional in Embedded Systems◌ OS [Contains Middleware & Device Drivers] → Hardware = OS Manages device drivers through system level calls (e.g. Windows/Linux)◌ OS → Device Drivers → Hardware = An OS developed on-top of static device drivers (Platform specific OS)◌ OS → BSP w/Drivers → Hardware = An OS developed on-top of a BSP which contains device drivers.

✔ See Also◌ Abstraction Layers http://en.wikipedia.org/wiki/Abstraction_layer◌ Hardware Abstractions http://en.wikipedia.org/wiki/Hardware_abstraction

6.1 Bootloaders

✔ Types◌ Bootstrap Loader = Initial Boot loader◌ Boot Loader = Any other Boot loaders

✔ System Start-Up Sequence 1. Assert Reset = On power-up the reset circuit asserts the reset signal 2. De-Assert Reset = Reset is de-asserted when clocks reach running speeds and voltages stabilize 3. Set Instruction Pointer = The processors instruction pointer is set to the 'Reset Vector' for 1st instruction 4. Initialize Registers = Interrupts are disabled; Clears and sets register values such as the stack pointer and flags 5. Start Interrupt Service Routines (ISR) = Launch boot-loaders (ie: device drivers) in the form of Interrupt Service Routines

◌ Boot-loaders can jump to main() functions of C-Code for libraries that matches interface of routines and data structures

✔ Chain-loading = Process of LOADING multistage boot-loaders one after the other with increasing complexity and functionality 1. Bootstrap Loader = Initial instructions that starts the loading of the boot-loaders; Execution begins at the 'reset vector' in ROM 2. BIOS - Basic Input/Output System = A boot-loader for basic I/O functionality (e.g. keyboard/mouse/display) 3. MBR - Master Boot Record = A boot-loader at the very beginning (boot sector) of a secondary memory device 4. 2nd Stage Bootloaders - Generic Bootloaders = Further booting device drivers used to expand functionality of the system 5. Kernel - Runtime Engine of the OS =

✔ Common Bootloaders◌ BIOS - Basic Input/Output System = By Intel [1975]◌ EFI - Extensible Firmware Interface = By Intel; deprecated in 2005 to UEFI

Page 51: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

◌ UEFI - Unified Embedded Firmware Interface = By Unified EFI Forum http://www.uefi.org/

◌ GNU◌ GRUB - Grand Unified Boot-loader = A common Linux boot-loader system◌ BOOTMGR - Boot Manager = A MS-Windows Boot-loader◌ Syslinux◌ NTLDR◌ BootX◌ LILO - Linux Loader = A common Linux boot-loader system◌ CFE - Common Firmware Environment = A boot-loader system and console by Broadcom◌ U-Boot = An open source BIOS boot-loader

✔ Reference◌ Wikipedia Booting (boot-loader loading) http://en.wikipedia.org/wiki/Booting ◌ Wikipedia List of Boot-loaders http://en.wikipedia.org/wiki/Comparison_of_boot_loaders ◌ Wikipedia UEFI http://en.wikipedia.org/wiki/Unified_EFI_Forum◌ How computers boot up http://duartes.org/gustavo/blog/post/how-computers-boot-up/ ◌ http://en.wikipedia.org/wiki/Firmware Links to ROM imaging and boot-loaders◌ Wiki ELF File http://en.wikipedia.org/wiki/Executable_and_Linkable_Format◌ http://www.bottomupcs.com/elf.html

6.2 Board Support Package (BSP/HAL)

✔ BIOS - Basic Input/Output System = BSP that manages basic peripheral device I/O✔ ASP - Architecture Support Package = Another term for BSP device driver package collection✔ FSP - Firmware Support Package = Another term for BSP device driver package collection

✔ Notes◌ The reality is that hobbyist embedded programming doesn't allow time for implementing all the ISRs and the boot-loader code. ◌ Many people use standard software frameworks available for specific processors.◌ EDA System Design Software typically contains applications that automatically create all the required boot-loaders and device drivers

✔ Terms◌ HAL - Hardware Abstraction Layer = The program layer that joins the hardware → software◌ BSP - Board Support Package = Library of boot-loaders and device drivers for hardware → software support◌ ESD - Embedded Software Development = http://www.altera.com/devices/processor/nios2/tools/ni2-development_tools.html ◌ SBT - Software Building Tools = A library for system-specific support code. (Run-time environment for NiosII)◌ EDS - Embedded Design Suite◌ HID - Human Interface Device

✔ How firmware connects to the metal (static tables)** List of Common HAL/BIOS Specifications **

✔ HAL = Isolates platform-specific hardware from Operating System (allows any motherboard)◌ New platform only requires new driver compilation; because drivers rely on the HAL code.◌ ACPI = Advanced Configuration and Power Interface (Introduced in 1996; http://www.acpi.info/ )◌ APM = Advanced Power Management and Application Programming Interfaces (BIOS code)◌ PNP-BIOS = Plug & Play Application Programming Interfaces (BIOS code)◌ MPS = Multiprocessor Specification (BIOS code)◌ See Also

▪ HAL options after XP or Server 2003 @ http://support2.microsoft.com/kb/309283 ▪ UEFI = Unified Extensible Firmware Interface [ HAL ↔ OS ] interface specification @ http://www.uefi.org/

Page 52: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

6.3 Operating Systems (OS)

✔ Provides a Common (ie: Standard) Operation and Organization (ie: Management) of Hardware & Software Resources.◌ Manages

▪ Processor = Provides basic means of multitasking by dividing and splitting instructions / duties.▪ Memory = Controls Virtual Memory tables; dividing memory into two distinct access levels

▫ Kernel Mode = Full Access to all resources (ie: Supervisor Mode)▫ User Mode = Limited Access to resources (e.g. Applications cannot corrupt kernel-level code)

◌ Provides▪ SCI - System Call Interface = For Hardware ↔ Software Isolation Layer (ie: Abstraction)

✔ Common Components◌ Subsystems - Standard SCI/API = Provides standard-sets of System Call Interfaces (SCI)◌ IPC - Inter-process Communication = Facilities/Mechanisms for component communications◌ HAL - Hardware Abstraction Layer = Base hardware abstraction (e.g. Motherboard Isolation)◌ Memory Management = Operates and Organizes Random-Access Memory (RAM)◌ Process Management = Operates and Organizes Program Processes & Threads◌ I/O Management - Input/Output = Operates and Organizes I/O Devices (e.g. Drivers & File Systems)

✔ Kernel Architectures◌ Monolithic = Entire OS is working in Kernel Mode / Space / Memory. Providing a high-level virtual interface over hardware.◌ Micro = Only fundamental parts of the OS are working in Kernel Mode.◌ Hybrid = OS Operation is divided between Kernel and User Mode.

✔ See Also◌ Wiki Abstraction http://en.wikipedia.org/wiki/Abstraction_%28computer_science%29◌ Wiki Abstraction Layer http://en.wikipedia.org/wiki/Abstraction_layer◌ How to write an OS in Assembly Language http://wiki.osdev.org/Main_Page◌ Hobby OS Development http://en.wikipedia.org/wiki/Hobbyist_operating_system_development◌ Wiki Operating Systems http://en.wikipedia.org/wiki/Operating_system◌ OS Tutorial K-State http://faculty.salina.k-state.edu/tim/ossg/index.html◌ Deeper into Windows Architecture http://blogs.msdn.com/b/hanybarakat/archive/2007/02/25/deeper-into-windows-architecture.aspx◌ Wiki

▪ Kernel http://en.wikipedia.org/wiki/Kernel_%28operating_system%29▪ Monolithic-Kernel http://en.wikipedia.org/wiki/Monolithic_kernel▪ Micro-Kernel http://en.wikipedia.org/wiki/Microkernel▪ Protection Ring http://en.wikipedia.org/wiki/Protection_ring

6.3.1 Market

✔ OS Types◌ Generic◌ RTOS - Real Time OS = An OS for embedded systems typically with an Real-Time Clock (RTC)

▪ RTOS for Altera NiosII Soft-Core processors▫ Micrium (MicroC/OS) – http://micrium.com/ http://en.wikipedia.org/wiki/MicroC/OS-II▫ VxWorks

▪ Embedded Systems▫ Windows CE▫ Minix 3

Page 53: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

✔ Characteristics◌ Tasking (Single or Multi)◌ User ( Single or Multi )◌ Distributed◌ Templated◌ Embedded◌ Real-Time (RTOS)

✔ Microsoft◌ DOSDOS - Disk Operating System = OS Shell/Disk Operating System(DOS) Invokes OS commands◌ Windows Client Editions

▪ Windows 7 Home Basic▪ Windows 7 Home Premium▪ Windows 7 Professional▪ Windows 7 Ultimate▪ Windows 7 Enterprise▪ Windows 7 Starter

◌ Windows Server Editions▪ Windows Server 2008 R2 Foundation▪ Windows Server 2008 R2 Standard = Hyper-V▪ Windows Server 2008 R2 Enterprise = Hyper-V▪ Windows Server 2008 R2 Datacenter = Hyper-V▪ Windows Web Server 2008 R2▪ Windows HPC Server 2008 R2▪ Windows Server 2008 R2 for Itanium-Based Systems

✔ Linux/Unix◌ BSD◌ OS-X◌ Google Chromium

✔ See Also◌ List of RTOS http://en.wikipedia.org/wiki/List_of_real-time_operating_systems◌ Popular RTOS http://en.wikipedia.org/wiki/RTOS#Examples◌ Sun Micro-Systems Software http://en.wikipedia.org/wiki/Category:Sun_Microsystems_software

6.3.2 Windows

✔ User-Mode Processes◌ User Applications = See List of types◌ Fixed/Hardwired System Support = (ie: Hardwired) Logon process, Session Manager; No started by the service control manager)◌ Service = Task Scheduler, Print Spooler. Run independent of user log-on◌ Environment subsystems = All User-Mode applications work through subsystem personality & programmer interfaces.

✔ Kernel-Mode Processes◌ Windows Executive and Kernel◌ Device Drivers = Hardware (translates user I/O functions calls into specific hardware I/O requests) and non-I/O such as File

system and network drivers◌ HAL = Layer of code that isolates the kernel & device drivers & executive from platform-specific hardware differences◌ Windowing and Graphics System = Implements Windows GUI functions (ie: Windows USER & GDI functions) such as dealing with

windows and user interface controls and drawing.

Page 54: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

C:\Windows\System32\ Mode Description

Hal.dll Kernel Hardware Abstraction Layer (Hardware Specific)

Ntoskrnl.exe Kernel Windows Executive and Kernel

Ntkrnlpa.exe Kernel (32-bit) Executive and Kernel w/Physical Address Extension (PAE). Allows 64GB RAM Access.

Architecture Specific is isolated in HAL & KERNEL above (e.g. Motherboard)

Ntdll.dll System Support System service dispatch stubs to executive functions

Win32k.sys Kernel Windows Subsystem

Kernel32.dll Kernel Windows32 Subsystem

Advapi32.dll Kernel API Subsystem

User32.dll Kernel User Subsystem

Gdi32.dll Kernel Graphics Device Interface (GDI) Subsystem

A. Executive and Kernel (Ntoskrnl.exe)

✔ Executive (Upper-Layer of Ntoskrnl.exe)

◌ Major Components▪ Configuration Manager▪ Process Manager▪ Security Reference Monitor▪ I/O Manager▪ Plug and Play (PnP) Manager▪ Power Manager▪ Windows Driver Model Windows Management Instrumentation routines▪ Cache Manager▪ Memory Manager▪ Logical Prefetcher and Superfetch

◌ Support Functions (Used by the Executive Components)▪ Object Manager▪ ALPC - Advanced Local Procedure Call▪ Run-Time library Functions▪ Executive Support routines = System Memory allocation (paged & nonpaged pool), interlock access, synchronization objects

resources, fast mutexes, and pushlocks

◌ Base OS Services▪ Memory▪ Process and thread management

Page 55: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

▪ Security▪ I/O▪ Networking▪ IPC

◌ Functions▪ ALPC▪ NtQueryInformationProcess, NtCreatePagingFile – Undocumented System Services (not part of ntdll.dll exports)▪ Supplies a general interface (Calls between user → Kernel Mode for device drivers not associated with read/write)▪ WDK Kernel Functions▪ Hidden

▫ WDK Undocumented Kernel Functions – Starts with Inbv)▫ Iop = Internal I/O manager support functions▫ Mi = Internal memory management support functions

✔ Kernel (Lower-Layer of Ntoskrnl.exe)◌ Low-Level OS Support

▪ Thread scheduling = Kernel Dispatcher objects; sync capabilities▪ Interrupt and exception dispatching▪ Multiprocessor synchronization▪ Provides API to the Windows Executive for higher-level constructs

◌ Functions▪ WDK provides some documentation of the kernel functions; they start with 'Ke'

✔ Device Drivers = Hardware (translates user I/O functions calls into specific hardware I/O requests) and non-I/O such as File system and network drivers

✔ HAL = Layer of code that isolates the kernel & device drivers & executive from platform-specific hardware differences✔ Windowing and Graphics System = Implements Windows GUI functions (ie: Windows USER & GDI functions) such as dealing with windows

and user interface controls and drawing.

B. Inter-process Communications (IPC – Ntdll.dll)✔ Windows

◌ Ntdll▪ Ldr - Image Loader▪ Csr - Heap Manager / Windows subsystem process communications▪ Rtl - General run-time library routines▪ DbgUi - User Mode debug functions▪ Etw - Event Tracing functions▪ APC - Asynchronous Procedure Call = Dispatcher and exception dispatcher▪ CRT - C Run-Time routines = Contains only a small sub-set of functions▪ Exports “system services” from the Executive (Ntoskrnl.exe)

▪ Contains the 'Image Loader' for loading and communicating DLL files.

C. Environmental Subsystems✔ MS-Windows Subsystems

▪ Windows Subsystem - C:\Windows\System32\Win32k.sys = Kernel-mode part of the Windows Subsystem▪ POSIX - Last shipped with Windows 2000▪ OS/2 - Last shipped with Windows 2000▪ SUA - Subsystem for Unix-based Applications = An Enhanced POSIX subsystem

◌ Windows Subsystem - Files; Kernel32.dll, Advapi32.dll, User32.dll and Gdi32.dll = Windows API◌ SUA Subsystem - Files; Psxdll.dll = SUA API Functions

▪ Allows running UNIX-based applications; Supported on Windows Server / Enterprise / Ultimate editions.

C.1 Windows API (SCI)

✔ Categories◌ Base Services

▪ Windows API Functions - Documented (e.g. Create Process, CreateFile, GetMessage)▪ System Calls - (ie: Native System Services) Undocumented, underlying user-mode callable (e.g. NtCreateUserProcess)▪ Routines - (ie: Kernel Support Functions) = Only callable from Kernel-mode (e.g. ExAllocatePoolWithTag for drivers)▪ Windows Services - User Level services like the Task Scheduler

Page 56: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

▪ DLL - Dynamic-link Libraries = ▪ Terminology

▫ Fibers▫ User-Mode Scheduling (UMS)

◌ Component Services◌ User Interface Services◌ Graphics and Multimedia Services◌ Messaging and Collaboration◌ Networking◌ Web Services

✔ Details◌ SMSS - Session Manager Subsystem = Launches Environmental Subsystems(HKLM\SYSTEM\CurrentControlSet\Control\Session

Manager\SubSystems

◌ CSRSS - Client/Server Run-Time Subsystem◌ GDI - Graphics Device Interface = Library for graphics output devices (ie: drawing)◌ USER32 [Window Manager] (Windows / Buttons) → GDI → Graphics device driver / Video miniport driver → Hardware

6.3.3 Memory Management

✔ Memory Management = Component that associates [ virtual address spaces ↔ physical memory ]◌ Memory Addresses are routed from virtual address to physical addresses by memory manager.

▪ Paged Pool = Memory that can be paged out to the hard drive▪ Non-paged Pool = Always resident in memory

◌ 1-Memory Page = 4kilobytes◌ Memory Manager takes care of pushing over-loads to disk “Pool” memory space.◌ See http://msdn.microsoft.com/en-us/Library/Windows/Hardware/hh439648%28v=vs.85%29.aspx

✔ Virtual Memory = Memory split or allocated between

◌ Systems usually handle addresses through a Memory Management Unit (MMU)◌ This allows Virtual Address ↔ Physical Address management◌ In Windows – User-Mode Processes are assigned their own virtual address space to operate in

✔ Virtual Memory Spaces◌ Kernel - (ie: Supervisor) Kernel Architecture of the OS determines software in the “Kernel Space”◌ User - Kernel Architecture of the OS determines software in the “User Space”

✔ See Also◌ Wiki User Space http://en.wikipedia.org/wiki/User_space

6.3.4 Process Management

A. Multiprocessor Platforms

✔ Hardware Types◌ Multicore = Multiple physical processor cores on one IC Package◌ Hyper-Threading = Two logical processors for each physical core (see; thread scheduling)◌ NUMA = Each “Node” contains a processor and memory. Nodes are interconnected by a cache-coherent bus.

✔ Support Mechanisms◌ SMP - Symmetric MultiProcessing = Threads split between processors (there is no “master” processor)◌ ASMP - Asymmetric MultiProcessing = A “master” processor runs the kernel; other processors run user code.

✔ MS-Windows Features◌ SMP Multiprocessor support◌ Multicore, Hyper-Threading, and NUMA Platform support

✔ Windows Architecture knowledge for device drivers◌ spin locks◌ wait locks◌ Threads and Processes – fully re-entrant, MP safe

Page 57: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

◌ Processor modes – Ring0 and Ring3 in x86◌ Memory Management – User vs Kernel Mode and “demand paged virtual memory”◌ Multiple nested interrupt levels◌ Difference between IO port and memory space◌ Device registers and why/when devices interrupt◌ DMA and basic difference between DMA and programmed IO relevant to a driver

◌ Race / Deadlock control▪ Synchronization= Using synchronization objects to protect shared data▪ Serialization = Stack / queue requests for one at a time access to shared data

✔ Need to look-up and document◌ Semaphores◌ Mutex◌ Heap

B. Scheduling

✔ Windows Implementations◌ Kernel Scheduler

▪ Fibers = (ie: Light-weight threads) Manual Scheduling; Use ConvertThreadToFiber()▪ UMS - User-mode Scheduling = 64-bit Windows support; See “Direct Context Switch”

✔ See Also◌ Wiki Scheduling http://en.wikipedia.org/wiki/Scheduling_%28computing%29◌

6.3.5 Inter-Process Communication (IPC)

✔ Types◌ File◌ Signal◌ Messaging◌ Pipe◌ Semaphore◌ Shared Memory◌ Memory-Mapped

✔ Interface Categories◌ ABI - Application Binary Interface = Interface between program components at the machine code level (e.g. OS level)◌ API - Application Programming Interface = Interfaces between program components at the source code level

✔ See Also◌ Wiki

▪ Inter-process Communication http://en.wikipedia.org/wiki/Inter-process_communication▪ Inter-process Communication Categories http://en.wikipedia.org/wiki/Category:Inter-process_communication▪ Local Procedure Call http://en.wikipedia.org/wiki/Local_Procedure_Call▪ Windows communication and services http://en.wikipedia.org/wiki/Category:Windows_communication_and_services▪ Unix Doors http://en.wikipedia.org/wiki/Doors_%28computing%29

A. General IPC (CORBA/ORB)✔ OS Libary

◌ Windows is part of Ntdll.dll library✔ Technologies

◌ Dynamic Linker◌ Dynamically Loaded Library◌ DLL - Dynamic Link Library = Microsoft's implementation of “Shared Libraries” through shared memory space.◌ IPC - Inter-Process Communication = Using communication protocols to message

Page 58: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

✔ Component Re-Use◌ Late / Dynamic binding = Method being called on an object is looked up by “name” at runtime.◌ Early / Static binding = Compilation fixes data-types in the virtual method table (“v-table”)◌ Dynamic Loading / Binding◌ Static Linking - (ie: Static Dispatch / ◌ Dynamic Linking

✔ See Also◌ Wiki Dynamic Loading http://en.wikipedia.org/wiki/Dynamic_loading◌ Wiki Static Linking http://en.wikipedia.org/wiki/Static_library◌ Wiki Dynamic Linker http://en.wikipedia.org/wiki/Dynamic_linker◌ Wiki Dynamic Dispatch http://en.wikipedia.org/wiki/Dynamic_dispatch◌ Wiki vtable http://en.wikipedia.org/wiki/Virtual_method_table◌ Wiki Application Virtualization Software http://en.wikipedia.org/wiki/Comparison_of_application_virtualization_software◌ Wiki Foreign Function Interface http://en.wikipedia.org/wiki/Foreign_function_interface◌ Wiki Language Binding http://en.wikipedia.org/wiki/Language_binding

✔ Dynamic✔ Static✔ Methods of Library Loading

◌ Path◌ Name - OS finds the library via Registry - Dependency Hell ( DLL Hell ) - UID Unique ID were invented to prevent DLL hell◌ Windows checks the registry to determine the place of dynamic libraries that implement the COM objects.

✔ See Also◌ Wiki Library http://en.wikipedia.org/wiki/Library_%28computing%29◌ Wiki Dynamic Link Library http://en.wikipedia.org/wiki/Dynamic-link_library◌ Wiki Dynamic Loading http://en.wikipedia.org/wiki/Dynamic_loading◌ ◌ ◌

✔ Dynamic Linker - Late Binding = The “part” of an OS that loads and links shared libraries at run-time.◌ This is done by copying the library contents to RAM and filling jump tables and pointers◌ Late Linking◌ http://en.wikipedia.org/wiki/Late_binding

✔ Dynamic Dispatch✔ Name Binding http://en.wikipedia.org/wiki/Name_binding✔ Dynamic Loading http://en.wikipedia.org/wiki/Dynamic_loading

◌ 3-mechanisms by which a program can use other software▪ dynamic loading▪ static linking▪ dynamic linking▪

✔ Market◌ CORBA - Common Object Request Broker Architecture◌ ACE - Adaptive Communication Environment◌ TAO - The ACE ORB (Object Request Broker)◌ http://en.wikipedia.org/wiki/Adaptive_Communication_Environment

▪ LPC▪ ALPC

RPC✔ See Also

◌ Wiki▪ Inter-Process Communication http://en.wikipedia.org/wiki/Inter-process_communication▪ Inter-Process Communication Categories http://en.wikipedia.org/wiki/Category:Inter-process_communication▪ Windows Communication and Services http://en.wikipedia.org/wiki/Category:Windows_communication_and_services

◌ CBSE - Component-Based Software Engineering http://en.wikipedia.org/wiki/Component-based_software_engineering◌ CBD - Component-Based Development◌ TI IPC Users Guide http://processors.wiki.ti.com/index.php/IPC_Users_Guide/Use_Cases_for_IPC◌ Wiki IPC Categories http://en.wikipedia.org/wiki/Category:Inter-process_communication◌ Wiki Synchronization http://en.wikipedia.org/wiki/Synchronization_%28computer_science%29◌ OS MicroKernel http://en.wikipedia.org/wiki/Microkernel◌ Software Layers http://accu.org/index.php/journals/460

Page 59: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

◌ OS Technology▪ http://en.wikipedia.org/wiki/Category:Operating_system_technology▪ http://en.wikipedia.org/wiki/Loader_%28computing%29▪

B. Microsoft IPC (LPC/COM/IDL)

✔ LPC - Local Procedure Call = Requires the 'Image Loader'✔ DDE - Dynamic Data Exchange = [1987] MS-Windows or OS/2 protocol for inter-process communications.✔ NetDDE - Windows for Workgroups DDE = An expanded DDE protocol to work between networked systems.

✔ COM - Component Object Model = [1993] Base Standard ABI Component enabling inter-process communication.✔ COM - Common Object Model = A specification & various API(s) with system-level run-time libraries for marshaling✔ DCOM - Distributed COM = COM ABI with features for network communicating components / calls.✔ MTS - Microsoft Transaction Server✔ COM+ - = MTS Implemented DCOM✔ OLE - Object Linking and Embedding = IOleObject interface; Creating a control extension (OCX)✔ OLE Automation - = IDispatch interface;✔ Active X = [1996] Expanded COM technology to support ActiveX objects for WWW.

✔ C++ COM Models◌ ATL - Active Template Library = Set of template-based C++ classes to assist in COM objects.◌ MFC - Microsoft Foundation Classes

✔ DLL - Dynamic Link Library = A collection (ie: Library) of program components with a dynamic interface specification.◌ MS-Windows registry “picks” the DLL file to use (See steps below)

▪ Reference to 'C:\Lib.DLL'▪ Windows will read the GUID on 'C:\Lib.DLL'▪ Looks up the GUID in the windows registry▪ Registry GUID path → DLL is used (ie: If a new DLL with the same GUID has been registered then windows will use the \new\ one

even if directly referenced to C:\Lib.DLL

✔ IDL= Interface Definition Language

✔ Terminology◌ DCE - Distributed Computing Environment– Originally by Open Software Foundations origins of COM/OLE/ActiveX◌ Marshalling = Calling external methods (e.g. External methods is called Marshalling an external method calls arguments.)

◌ COM Type Libraries – Are components that can describe themselves to the COM engine▪ Registry records a UID for each COM component known as HKEY_CLASSES_ROOT hive▪ Registry REVERSE look-up to UID is stored in HKEY_CLASSES_ROOT\CLSID sub-folder

◌ Standardizes the instantiation (ie: Creation) process of COM objects by requiring the use of 'Class Factories'◌ Standard requires two items to exist

▪ Type Library Contains▫ CLSID of a component▫ IID(s) of the interfaces the component implements▫ Descriptions of each of the methods of those interfaces.▫ Type Libraries are typically used by Rapid Application Development (RAD) environments such as Delphi, VB, VS to assist

developers of client applications.

◌ RegFree COM - Registration-Free COM = A technology introduced with Windows-XP that allows COM compo▪ Allows COM components to store activation “metadata” and “Class ID” (CLSID) for the component w/o using the registry.▪ Metadata - Instead, Metadata and CLSID(s) of the classes are implmented in the compontent and declared in an assmebly

manifest (described using XML), sotred either as a resource in the executable OR as a seperate file installed with the component.This allows multiple versions of the same component to be installed in different directories; described by their own manifests as well as XCOPY deployment. This technology has limited support for EXE and COM servers and cannot be used for system-wide components such as MDAC, MSXML, DirectX or Internet Explorer.

◌ Composed of▪ IDL - Interface definition language (Has Interfaces and Type Libraries) each having a GUID (Global Unique Identifier)

▫ Enums and Data-Types can e defined in IDL▪ IID - Interface ID(s) another common term for GUID(s)▪ LIBID(s) - Type Library ID(s) a more specific term▪ CLSID - Class ID(s)

✔ COM Components contain:◌ Interface = Does NOT carry any implementations of the methods (JUST method declarations)

▪ Interface is the only way a client can access the services of the COM component

Page 60: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

▪ Two Types of Interfaces▫ Standard - Interfaces provided by the COM library. (e.g. Iunknown, Idispatch, IclassFactory, Iole, IdataObject, Istream,

IStorage)▫ Custom - Programmer interfaces

◌ CoClass - Component Class = COM Class Definition (The 'class' identifier in IDL)◌ Types

▪ In-Process DLL Libraries that run in the same memory space as the client application using it. If DLL crashes App does too.▪ Out-Process EXE Runs in separate memory space as the client App calling it. If EXE crashes App remains active and EXE is

reloaded.▪ Remote Just like any other component but runs from a seperate location via network; Implemented with DCOM

(Distributed COM) technology.◌ .NET has its own COM run-time tool known as WinRT

✔ Windows Loader◌ #1 – Application loads◌ #2 – Windows searches for the manifest; If preset, the loader adds information from it to the activation context◌ #3 – When the COM class factory tries to instantiate a class The activation context is first checked to see if an emplementation for the

CLSID can be found – ONLY IF THE LOOKUP FAILS – is the registry scanned.

✔ Windows DNA - Windows Distributed interNet Applications Architecture = Collection of MS Techonology for Windows / Internet◌ ActiveX◌ DHTML◌ COM

Component Object Model (COM) is a binary-interface standard for software componentry introduced by Microsoft in 1993. It is used to enable interprocess communication and dynamic object creation in a large range of programming languages. The term COM is often used in the Microsoftsoftware development industry as an umbrella term that encompasses the OLE, OLE Automation, ActiveX, COM+ and DCOM technologies.

Different component types are identified by class IDs (CLSIDs), which are Globally Unique Ident i fiers (GUIDs). Each COM component exposes its functionality through one or more interfaces. The different interfaces supported by a component are distinguished from each other using interfaceIDs (IIDs), which are GUIDs too.

COM interfaces have bindings in several languages, such as C, C++, Visual Basic, Delphi, and several of the scripting languages implemented on the Windows platform. All access to components is done through the methods of the interfaces. This allows techniques such as inter-process, or even inter-computer programming (the latter using the support of DCOM).Interfaces

All COM components must (at the very least) implement the standard IUnknown interface, and thus all COM interfaces are derived from IUnknown. The IUnknown interface consists of three methods: AddRef() and Release() (which implement reference counting and control the lifetime of interfaces) and QueryInterface(), which by specifying an IID allows a caller to retrieve references to the different interfaces the component implements. The effect of QueryInterface() is similar to dynamic_cast<> in C++ or casts in Java and C#.

Notes from : http://www.youtube.com/watch?v=3ciT2uOz1kMNIC – Network interface cardGrids – Computers across the internet CORBA over IPCluster – Server rack or multiple racks all in one room

Theme – Has one Dispatcher and a lot of WorkersSETI@Home, BOINC, Render farms, Google clusters

✔ Reference◌ http://en.wikipedia.org/wiki/Component_Object_Model ◌ C++ and the COM Interface http://na.support.keysight.com/pna/help/latest/Programming/Learning_about_COM/c+

+_and_the_com_interface.htm ◌ C++ as an IDL http://g.oswego.edu/dl/mood/C++AsIDL.html◌ Wiki Windows DNA http://en.wikipedia.org/wiki/Windows_DNA◌ MSDN Inter-process Communications https://msdn.microsoft.com/en-us/library/aa365574%28VS.85%29.aspx◌ Wiki Windows Registry http://en.wikipedia.org/wiki/Windows_Registry

C. Remote Procedure Call (RPC)✔ RPC - Remote Procedure Call = Sun Systems ABI standard for inter-process communications.✔ POSIX✔ See Also

◌ Unix IPC Guide http://beej.us/guide/bgipc/◌ DTrace Monitoring Tool http://en.wikipedia.org/wiki/DTrace◌ ◌ http://www.devarticles.com/c/a/COM/COM-101-A-Quick-Primer/1/#ZmD8mreIzVrKXBbA.99

Page 61: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

◌ Understanding Exported Code (DLLs, IDL, etc..) for VB6 http://whathesaid.ca/what-he-wrote/tame-visual-basic-with-idl/

Visual Basic Data Type IDL Data Type

Boolean VARIANT_BOOL

Byte unsigned char

Collection _Collection*

Currency CURRENCY

Date DATE

Double double

Integer short

Long long

Object IDispatch*

Recordset _Recordset*

Single float

String BSTR

Variant VARIANT

no parameters voidFigure 2: Visual Basic data types and their corresponding data types in IDL

Other than unsigned char (Byte), keep in mind that VB can only implement signed types. Parameters marked as [in] use the IDL representation as in figure 1. These correspond to ByVal parameters in VB. Parameters marked as [in, out] add a single indirection operator (*). These correspond to VB’s ByRef parameters. For example:

HRESULT Method1( // ByVal As Integer [in] short intInParm, // ByVal As Object [in] IDispatch* objInParm, // ByRef As Integer [in, out] short* intInOutParm, // ByRef As Object [in, out] IDispatch** objInOutParm);

6.4 I/O Management

A. Plug and Play Devices (PnP)

✔ PnP Device Tree = The Windows kernel Plug and Play Manager collects all-peripheral devices into a device tree.◌ Device Node = Physical Device, Software component, or Function of a Composite Device in the PnP Device Tree◌ Device Object(DO) = Each Node is represented by an instance of the DEVICE_OBJECT data structure.

Illustration 2: ACPI HAL System Device Tree

Page 62: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

◌ Driver Stack = The path of drivers through the device tree to a specific target device “the device's driver stack”

✔ Driver Types◌ Root = Entry point driver to the device tree (ACPI in the diagram)◌ Software = No hardware just used for Kernel-Mode access and/or User Mode drivers◌ Class = Applies to all devices within a given windows-defined device class

◌ Function (FDO) = Primary bus/device driver that handles read/write/control (ie: Also called Mini-Port driver)▪ FDO - Function Device Object = Parent device object▪ PDO - Physical Device Object = Child device object within a parent FDO▪ CDO - Control Device Object = Non-PnP driver for legacy devices (handles its own create/destroy)

◌ Filter (Filter DO) = Extension (ie: In-between driver) component for specialized protocols or bug-fixes▪ Upper-level filter driver – Processes IRP data before the Function Driver▪ Lower-level filter driver – Processes IRP data after the Function Driver

✔ At start-up ◌ The Windows kernel PnP-Manager requests that each parent driver enumerate all connected child nodes(PDO Child-list).◌ Each Child PDO then has at least 1-FDO or 1+ Filter DO

✔ For Example: Every USB device is a PDO of the USB Host FDO – But each USB device also has a local Function Driver (FDO)

✔ OS Class Drivers= OS's comes pre-packaged with general purpose “standard” device drivers for a particular class of devices✔ Reference

◌ Device Nodes and Stacks @ http://msdn.microsoft.com/en-us/library/windows/hardware/ff554721%28v=vs.85%29.aspx ◌ Windows Device Classes @ http://msdn.microsoft.com/en-us/library/windows/hardware/ff557557%28v=vs.85%29.aspx

6.5 Unix/Linux

7. SOFTWARE DEVELOPMENT

✔ User Applications◌ Windows 32-bit or 64-bit◌ Windows 3.1 (16-bit)◌ MS-DOS (16-bit)◌ POSIX 32-bit or 64-bit

▪ Note: 16-bit applications can only run on 32-bit Windows

7.1 Overview ✔ Programming The process of writing source code that is converted (ie: Compiled/Interpreted) to a target “machine language” (ie:

Processor Instructions)

◌ Way-Ahead-of-Time(WAT) / Ahead-Of-Time (AOT) Compilation Compiler IS system processor specific

▪ Initial Compilation Converts all source code to target Machine Language all at once during the compilation process▪ System Specific The compiler is system hardware/processor specific

◌ Just-In-Time(JIT) Compilation AOT Compiler is NOT system processor specific; JIT Compiler/Interpreter IS processor system specific

Page 63: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

▪ Source Code → AOT Compiler → Intermediate Language Original Source code is converted to an intermediate language code standard

▪ Intermediate Language → JIT Compiler → Machine Language Parts of the code are compiled once and executed multiple times▪ Intermediate Language → Interpreter → Machine Language Other parts must remain interpreted and converted every time

during execution▪ ▪ JIT-Compiler is also sometimes referred to as “translators” or “dynamic adaptive compilation (DAC)”

◌ Interpreters Source Code is NOT system processor specific; The Interpreter Engine IS system processor specific▪ No Compilation Converts source code to machine language on-the-fly line per line every-time the code is executed.

◌ Virtual Machine (VM) Machine-Level converter from one system platform (Itself) to a target system platform.

✔ Language Terminology◌ Late-Binding Allocates data type resolution “on-the-fly” rather than at compile time◌ Scripting Language All scripting languages are interpreted but not all Interpreted languages are scripting languages (e.g.

HTML, JavaScript, Vb-script)

✔ Program Paradigm - Fundamental Style - See http://en.wikipedia.org/wiki/Programming_paradigm

◌ Usually is written so the data is dynamic while the functionality is static◌ Learn to use libraries and code bases that have already been written◌ Organization

▪ Around its code (what is happening) – Structured / Functional (Code acting on data)▪ Around its data (who is being affected) – Object Oriented (Data controlling access to code)(Define the routines allowed to act on

the data type)✔ Structured Programming (Mid-Level) High-Order Languages (HOL); Stand-alone subroutines; Procedural Languages

◌ FORTRAN [1950]◌ COBOL [1959]◌ BASIC [1964]◌ Pascal [1970]◌ ANSI C [1972]

✔ Object Oriented Programming (OOP) Very High Level Languages (VHLL)◌ LISP [1960]◌ Simula [1967]◌ SmallTalk [1972]◌ Java, C++, SQL, Delphi [1990s]◌ ** OOP techniques became widely accepted in all languages except C. **

✔ Natural Languages (AI – Artificial Intelligence) Still in development stages (Programming similar to conversational languages)✔ Mechanism – What capabilities are to be provided (drivers should not entail policy; deal with making the hardware available leaving

“how” to use up to the application)✔ Policy – How those capabilities can be used.✔ Programming

◌ Bare-Metal Programming (Low-Level) Programming without an OS (ie: NOTHING between the program and the processor instructions)▪ Machine Language Processor specific binary (ie: '1s' or '0s') that represent data and/or a processor

commands▪ Assembly Language [1949] Processor specific symbolic text representation of worded binary (ie: Machine Language)

✔ Reference◌ Wiki Operating System http://en.wikipedia.org/wiki/Operating_system ◌ Language comparison http://en.wikipedia.org/wiki/Comparison_of_programming_languages ◌ Functional Language comparison http://en.wikipedia.org/wiki/Comparison_of_functional_programming_languages ◌ Language list http://en.wikipedia.org/wiki/List_of_programming_languages ◌ Keywords Compared in Different Languages http://msdn.microsoft.com/en-us/library/zwkz3536%28v=vs.71%29.aspx ◌ List of Compilers http://en.wikipedia.org/wiki/List_of_compilers ◌ Online ISOCPP(ie: C++) compilers https://isocpp.org/blog/2013/01/online-c-compilers also see https://isocpp.org/get-started

▪ Capable of representing a “kernel” binary as easily as an executable or system library

◌ Cross Compilation (Different Target Systems) http://airs.com/ian/configure/configure_5.html◌ Embedded System Programming http://www.bogotobogo.com/cplusplus/embeddedSystemsProgramming_gnu_toolchain_ARM_cross_compiler.php◌ Cmake Cross Compilation http://www.vtk.org/Wiki/CMake_Cross_Compiling◌ Wiki AOT Compilers http://en.wikipedia.org/wiki/Ahead-of-time_compilation

Page 64: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

◌ Wiki Program Execution http://en.wikipedia.org/wiki/Execution_%28computing%29

7.1.1 Compilers/Interpreters

✔ Compiler Types◌ Assembler Assembly Language compiler – Converts assembly language to machine language; Typically both are system processor

specific◌ Cross-compilers Compilers located on a development PC but compiled for an embedded systems hardware platform

✔ Compiling Tool-chain◌ Pre-processor Adjusts (ie: Adds, Deletes, Substitutes) source code fragments dependent on Pre-processor variables just before

compilation. (e.g. Macro's in C & C++)◌ Compiler Converts all source code → Target language (ie: Machine Code or Byte Code) at one time. Compiler is

processor/virtual machine specific◌ Linker◌ Libraries◌ Executable Final file after “linking” the object file with system libraries – file is ready to be transferred to the embedded systems

memory

7.1.2 Common Notations 1. Naming

◌ Event = 'On' like OnProgramStarted or OnButtonClicked()◌ Boolean = 'Is' like IsOkay or IsPathSet()

7.1.3 File Extensions 1. Object files

◌ (.o) = Compiled source file (If you have several source files in your application, you will also have several object files.)

2. Libraries (Package of object files)◌ (.a ) – Linux / (.lib) – Windows = Static Library – Linked during compilation and become part of the executable◌ (.so) – Linux / (.dll) – Windows = Dynamic Library – Loaded only when program is running and library is called.

7.1.4 Object Oriented Programming (OOP) 1. General Components

◌ Data Storage - Noun• Variable – A named memory spot for holding data (Name → Value)

• Compound – Contains both code and data (e.g. Objects)• Discrete – Only contains data• Static – All objects share one memory location (ie: variable)

• Field – Alias for a public variable within a 'class' in OOP languages.• Property – Wrapper for a field in OOP languages.

◌ Data Manipulation – Verb ( Any data manipulation code generally takes on any of the below names – technicality isn't maintained )• Function = In Data → Process → Out Data• Method = Alias for Function in OOP Languages.• Sub-routine = A function that does not directly return data

◌ Function Types• Delegate = Call Wrapper – Function that receives a pointer to some other function (e.g. DelagateCaller(InData,

PtrToFunction))

2. Encapsulation = Data and function encapsulation within Classes and Structures ('struct')◌ class = A defined and named block of code including variables(ie: Properties) and functions(ie: Methods)

• Classes bind together functions and data• e.g. Class Circle { VARIABLES: 'radius', 'color', FUNCTIONS: getRadius(), getColor(), getArea() }

◌ struct = A class typically used for a data structure (User-defined Data Type (UDT)); where the variables within are public by default• e.g. struct milk { brand, amount, grade }

Page 65: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

• TYPE keyword is used instead of 'struct' in VB6, VHDL and various other languages

◌ object = An isolated “copy” of the class code that maintains it's own variable values (ie: Instance of a class)• C1 = A named copy of 'circle class' code thus 'C1' can have it's own radius and color settings.• C2 = A named copy of 'circle class' code thus 'C2' can have it's own radius and color settings.• C3 = A named copy of 'circle class' code thus 'C3' can have it's own radius and color settings.• NEW keyword typically instantiates the object from a class design

** Above isn't actually how “classes/objects” work; but it represents the effect **** OOP languages use “vtables” behind the scenes to link-in the correct values for each object's variable values **Ex. One can drive “Object1” car without driving “Object2” & “Object3” cars even though they all derive from the same class (ie: design)

◌ Class Types▪ Concrete Classes = Classes defined for object creation▪ Abstract Classes = Classes that never become objects but are strictly used for inheritance

▫ C++ - Abstract classes contain at least one “pure virtual” function (to prevent objectifying it)▫ Example: Dog inherits Animal whereas just a plain 'Animal' object will never exist (Abstract is the common-ground of sub-classes)

▫ Interface = A particular type of abstract class that contains ONLY empty PUBLIC members that must be implemented (ie: Over-ridden)

▫ Interface abstract classes do not contain any information or functionality; just a public interface▫ C++ does not have a keyword 'interface'; Typically, a class with ONLY “pure virtual”(ie: =0) functions is considered an 'Interface'▫ Java does have keyword 'interface'; In Java, classes can inherit multiple interfaces but only one other class

◌ Data Hiding▪ Public – Access allowed anywhere▪ Protected – Access allowed within the inheritance tree; keyword FRIEND is used in VB▪ Friend – In C++ a Friend Function can be defined as part of a class definition which allows that function access to

private/protected class variables.▪ Private – Access allowed within the class

3. Inheritance = Method used to expand class functionality with “finer details” – Models a hierarchical classification◌ e.g. food (base class) → fruit (inherits 'food' class) → apple (inherits 'fruit' class)◌ Classes that inherit a “parent/base” class are called “derived classes”◌ Other Terminology identifying inheritance

▪ base → derived class▪ parent → child class▪ super → sub class

◌ Overloading = Same named functions with more than one implementation/functionality▪ Function Overloading = Two same-named functions with different arguments ( The caller argument count/type will determine which

function implementation is used)▪ Operator Overloading = Overloading operators like <,>,=,+, and etc.. (e.g. iostream overloads '<<' and '>>' operators for 'cin' and 'cout')

◌ Overriding = One function implementation over-rides the previous version (Both having identical call names and arguments)▪ When an interface or abstract class is inherited and function bodies are defined in the derived class they actually override the empty

body.

4. Polymorphism = Using the base class interface to access derived class objects◌ Using class inheritance a pointer to a derived class is compatible with a pointer to its base class◌ Polymorphism is the ability to access an object via it's base class inherited interface as its base class type

▪ Base Class Animal; Func Walk▪ Derived class Dog▪ Derived class Cat▪ Animal DogPointer = &Dog▪ Animal CatPointer = &Cat▪ DogPointer->Walk() We can call a base call using a pointer of base type even though Dog is of the derived dog class.

7.1.5 Toolkits / Libraries

A. Microsoft .NET✔ Visual Studio

◌ VS2012 and VS2013 do not have C++ GUI developers (by default but can still be brought up)◌ VS2010 C++ doesn't have intellisense

✔ Windows Form Types◌ Win32 = DLL or Win32 Applications (Using bare WinAPI)◌ ATL =

Page 66: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

◌ MFC = Microsoft Foundation Classes – Higher-level wrappers for Windows API for form design (unmanaged C++, nativeC++)

◌ CLR/CLI = Common Language Runtime/Interface – Brings .NET framework (multi-language) to C++✔ ATL = Active Template Library (C++ classes to simplify programming COM objects)

✔ Runtime Library = Core functions and engine needed by a programming language compiler◌ Visual Basic Runtime = VBRUN60.DLL – Required for any compiled Visual Basic v6.0 compiled program to execute.

✔ Microsoft .NET Framework [2003] Microsoft combined languages J#, C# and VB to execute on a “Common Language” JIT-Compiler residing at the system software layer

✔ .NET Programming Language Is any language that meets the Microsoft Common Language Specification Standard (e.g. C#, J#, VB-2003+, JavaScript)

✔ .NET Framework Must be installed on the target processor system in order to execute a .NET application✔

◌ .NET Source Code → initial compiler → Microsoft Intermediate Language (MSIL)◌ MSIL → Common Language Runtime (CLR) → Machine Language◌

✔ CLR Runtime contains:◌ MSIL Execution Engine w/JIT-Compiler◌ Class Loader◌ Platform Extension Libraries Platform libraries are withing the Base Class Library (BCL)◌ Garbage Collector (GC)

B. C++◌ Core language (variables, data types, literals)◌ C++ Standard Library (files, strings)'stdlib' – Functions for manipulating files and strings

▪ StdLib is != the STL library; but it is a common mistake to refer to the StdLib as STL; StdLib derived parts of the original STL library◌ Standard Template Library (STL) (std::) – methods for manipulating data structures (2.9+ may contain Boost libraries)◌ Boost – Typically considered the 'StdLib' sandbox; a library of pre-standard libraries◌ Cocoa (Mac)

✔ ✔ GUI Designers (Cross-Platform User Interface Toolkits)

◌ Linux (MinGW) – Qt(KDE default DUI engine) / GTK(GIMP engine) / wxWidgets (MFC copy-cat in Dev-C++) / SDL

◌ Windows – Blend / MFC / CLR✔ ✔ Reference

◌ GUI/Widget Toolkits – http://en.wikipedia.org/wiki/List_of_widget_toolkits (Often contain their own rendering engine)◌ Graphics Rendering Engines

▪ OpenGL▪ OpenVG▪ EGL▪ SDL = Simple DirectMedia Layer

◌ Wiki C++ Standard Library http://en.wikipedia.org/wiki/C%2B%2B_Standard_Library ◌ Wiki Standard Template Library (STL) http://en.wikipedia.org/wiki/Standard_Template_Library

Page 67: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

7.1.6 Language Comparisons✔ Java JVM✔

Keywords

7.1.7 Data Models (Serialization)✔ XML

◌ Frankly, if you aren't having to describe/discover the data's type, XML is overkill.✔ JSON✔ YAML - All JSON is a valid YAML

Page 68: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

✔ See http://en.wikipedia.org/wiki/Serialization✔ The process of serializing (encoding) an object is also called "marshalling" an object.✔ de-coding is "unmarshalling"

Page 69: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

7.2 OS Shells

7.2.1 MS-DOS

A. >path✔ Display Environment PATH >PATH✔ Add to the Environment PATH >PATH=<NewPath>;%PATH%

✔ Edit PATH through windows✔ Computer → Right Click → Properties → Advanced System Settings → Advanced Tab → Environment Variables

✔ Windows 8 DOS commands are located at: C:

7.3 Device Driver Development ✔ Types

◌ Architecture-specific - Manages master processor integrated hardware/components (e.g. MMU Drivers, Floating Point Drivers)◌ Generic - Manages board devices

✔ Hardware Driver Functions Interface to OS - Each function has code to interact directly with hardware◌ Start-up - Initialize hardware upon power-on/reset◌ Shutdown - Configures hardware into its power-off state◌ Disable - Allows other software to disable hardware “on-the-fly”◌ Enable - Allows other software to enable hardware “on-the-fly”◌ Acquire - Allows other software to gain LOCK access to the hardware◌ Release - Allows other software to FREE/UNLOCK the hardware◌ Read - Allows other software to READ data from the hardware◌ Write - Allows other software to WRITE data to the hardware◌ Install - Allows other software to “install” new hardware “on-the-fly”◌ Uninstall - Allows other software to “remove” installed hardware “on-the-fly”

✔ Generic Hardware States◌ Inactive - Disconnected; needs installed w/Power OR Disabled; needs enabled◌ Busy - Actively being used◌ Finished (IDLE) - Allows acquisition READ/WRITE requests

✔ Communications◌ Application → OS – Applications calls OS-API functions that send/receive hardware I/O requests◌ OS → Drivers – OS generates I/O Request Packet (IRP) objects and notifies the driver by calling driver Call-back functions◌ Drivers → HAL – Drivers (like OS-Plug-ins) work with OS-Architecture to communicate with the Hardware Abstraction Layer (HAL)◌ HAL → Device – HAL (Abstracting OS from hardware) takes standard calls and converts them to electrical signals

✔ Communication Terms◌ IRP - I/O Request Packet = OS Kernel data structure used to transfer data packets at the driver level◌ WMI - Windows Management Instrumentation = Microsoft's IT Distributed Management infrastructure◌ Port-IO = OS Initiated communication (MS-Windows uses 'IN' and 'OUT' Port access instead of Address Mapped I/O)◌ DMA - Direct Memory Access = Address space to hardware (Typically for high data devices like disks, networks or displays)◌ IRQ - Interrupt ReQuest = Hardware initiated communication requiring reception by software/driver◌ ISR - Interrupt service routine = Function to handle a device interrupts (Each event = 1 interrupt)◌ DPC - Deferred Procedure Call = Handles software interrupts and/or time-consuming interrupts◌ IRQL - Interrupt ReQuest Level = Interrupts contain priority levels DIRQL, DISPATCH, PASSIVE

▪ DIRQL - Most critical = ISR(s) use interrupt spin lock (non-paged memory)▪ DISPATCH - Highest software = Spin lock process synchronization (non-paged memory)▪ PASSIVE - Application level = Fast mutex / resource objects (built from dispatcher object-events)

✔ Reference◌ Wiki IRQ @ http://en.wikipedia.org/wiki/Interrupt_request

7.3.1 Driver Development Kits (DDK)

✔ Windows Driver Kits (WDK) – Microsoft's different driver kits through time

◌ TSR - Terminate and Stay Resident [MS-DOS] Real-Mode drivers (written in Assembly)◌ VDD - Virtual Device Drivers [Windows 3.x, 95, 98, Me drivers] Managed resource drivers (written in Assembly)◌ WDM - Windows Driver Model [Windows NT/XP/2000 till 2005] Full managed drivers (calls OS-system service routines )◌ WDF - Windows Driver Foundation Windows Vista, 7, 8 (2005+) Helpful Abstraction layer framework to the WDM

Page 70: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

✔ File Extensions◌ SYS = Driver based on the Kernel-Mode device Driver Framework (KMDF)◌ DLL = Driver based on the User-Mode device Driver Framework (UMDF)◌ INF = Driver Installer file – Used by Add/Remove hardware to record in the windows registry which files are

function/filter drivers for a device drivers package

✔ WDF Terms◌ DDI - Device Driver Interface = Abstract OS-kernel supplied driver interfaces that drivers need to implement (ie: “Driver Model”)◌ SDV - Static Driver Verifier = Debugging / Verifying tool packaged in the WDK

◌ PREfast = Debugging / Verifying tool packaged in the WDK◌ Checked Build OS = MS-Windows OS distribution that contains debug-related code/symbols specifically for driver debugging◌ Free Build OS = Normal/Released MS-Windows OS distribution◌ WDF Versioning = Drivers are compiled with WDF framework version # so OS can choose correct framework for a driver◌ Permanent Object = Programming object that remains present through the life of a plugged-in device◌ Transient Object = Programming object created and destroyed per-event

✔ See Also◌ MSDN

▪ WDF Reference @ http://msdn.microsoft.com/en-us/library/windows/hardware/dn265590%28v=vs.85%29.aspx ▪ WDF Reference as a CHM File

▫ @ http://download.microsoft.com/download/3/3/C/33CFEF4D-21DA-4229-BC17-3EAC7A7EABE1/WDKDocs_12112009.chm ▪ Windows Driver Development Kit Solutions (DDK) @ http://support2.microsoft.com/ph/7229▪ Windows WDK @ http://msdn.microsoft.com/en-us/windows/hardware/default.aspx ▪ Windows API @ http://msdn.microsoft.com/en-US/windows/desktop/aa904962.aspx ▪ Bus and Port Drivers @ http://msdn.microsoft.com/en-us/library/windows/hardware/ff557547%28v=vs.85%29.aspx ▪ Windows Checked Builds @ http://msdn.microsoft.com/en-us/library/windows/hardware/ff543457%28v=vs.85%29.aspx

◌ Wiki▪ TSR http://en.wikipedia.org/wiki/Terminate_and_stay_resident_program ▪ Device Drivers http://en.wikipedia.org/wiki/Device_driver ▪ WDF http://en.wikipedia.org/wiki/Windows_Driver_Foundation

◌ OSR Online ▪ What exactly is a Driver @ http://www.osronline.com/article.cfm?article=233

7.3.2 Kernel-Mode Driver Framework (KMDF)✔ Overview

◌ Written in 'C' using libraries 'ntoskrnl.exe' and 'hal.dll' for native API and executive services that support DMA and handle IRQ(s)◌ Interacts through “handles” (ie: Pointers to framework objects) and “registered-callback” functions (e.g. framework calls a custom

driver function when an event occurs)◌ IOCTRL(s) = I/O Requests(IRP) that are for controlling the device instead of data transfer

Page 71: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

✔ KMDF Object Attributes◌ ContextSizeOverride◌ ContextTypeInfo - Pointer to type information for the object context area◌ EvtCleanupCallback - Pointer to Callback routine invoked to cleanup the object before its deleted (before all references destroyed)◌ EvtDestroyCallback - Pointer to callback routine invoked when reference count is zero during an object destroy (later than cleanup)◌ ExecutionLevel - Sets the IRQL for KMDF callbacks◌ ParentObject - Handle to the parent object◌ Size - Objects size◌ SynchronizationScope - How callbacks are synchronized (applies to driver, device and file-object)

✔ KMDF Objects (defined in \inc\wdf\Wdfstatus.h or Ntstatus.h)◌ Child-List WdfChildList - List of child devices for a bus-driver◌ Collection WdfCollection - Similar objects container◌ Device WdfDevice - Driver contains one device object for each device it controls

◌ DMA▪ Buffer WdfCommonBuffer - Buffer that connects device and driver▪ Enabler WdfDMAEnabler - Enables a DMA channel with a device▪ Transactions WdfDMATransaction - One DMA Transaction (like an IRP for DMA)

◌ DPC WdfDPC - Deferred Procedure Call◌ Driver WdfDriver - Top-level Driver Object◌ File WdfFileObject - File object for application and external driver access to the driver [ Device ↔ DMA ↔

Driver ↔ File ↔ Application ]

▪ The native File Object represents a single, specific, open instance of a device (or a file on a device) ▪ File object for application and external driver access to the driver [ Device ↔ DMA ↔ Driver ↔ File ↔ Application ]▪ Unique open instance of a WDF Device Object ▪ Note that we are provided a WDF Device Object handle, which represents the WDF File Object’s target device. We are also provided

a WDF Request Object handle, which is the WDF abstraction of the native I/O operation representing the creation of the File Object.

▪ WDF Device Object handle, which represents the WDF File Object’s target device ▪ As an aside that we will revisit later, this WDF Request Object is unique in KMDF in that it is not queue presented, meaning that it

has no parent WDF Queue Object. ▪ Register via FileObject for Create, Close, and Cleanup Callbacks of IRP(s)

◌ General WdfObject – Driver Context object or object for any driver usage requirements◌ I/O

▪ Queue WdfQueue - Any I/O Queue▪ Request (IRP) WdfRequest - ▪ Target WdfIoTarget - Stack to which the driver is forwarding IRP(s)

◌ Interrupt WdfInterrupt - One device Interrupt Request(IRQ) -or- message-signaled interrupt(MSI)◌ Look-Aside List WdfLookAside - Dynamically sized list of identical buffers allocated from paged -or- nonpaged pool

(Component memory buffers)◌ Memory WdfMemory - I/O memory buffer for the driver to store an IRP◌ Registry-Keys WdfKey - Represents one windows registry key◌ Resources

▪ List WdfCmResList - Devices list of resources▪ Range-List WdfIoResList - Configuration for a device▪ Requirements WdfIoResReqList - Set of I/O resources list and their configurations (Each element is a WdfIoResList)

◌ String WdfString - Unicode string◌ Synchronization

▪ SpinLock WdfSpinLock - Spin lock synchronization for DISPATCH_LEVEL data▪ WaitLock WdfWaitLock - Wait lock synchronization for PASSIVE_LEVEL data

◌ Timer WdfTimer - Object for timed callback routine execution◌ USB

▪ Device WdfUsbDevice - One USB device▪ Interface WdfUsbInterface - Interface for a USB device▪ Pipe WdfUsbPipe - Pipe for a USB device

◌ WMI WdfWMIInstance - Windows Management Instrumentation◌ Work-Items WdfWorkItem - PASSIVE_LEVEL system thread item

Page 72: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

✔ KMDF Standard Syntax◌ WdfObjectOperation – KMDF Method naming notation◌ WdfObject{Set/Get}Data – KMDF No-Status Property naming notation◌ WdfObject{Assign/Retrieve}Data – KMDF Status Property naming notation (ie: Return is NTSTATUS)

✔ Getting Started

◌ All Drivers contain▪ (1) DriverEntry() – Gets called when driver gets loaded and creates the Top-Level (ie: “Root”) Driver Object▪ (1+)EvtDriverDeviceAdd() – Gets called when device gets connected and creates Device Object(s) … (1-FDO and 1+PDO for PnP

Devices)▫ Creates Device Objects

◦ Filter DO = Filter Device Object - Filters / Modifies IRP(s) for a device◦ FDO = Functional Device Object - Primary device driver for a PnP device tree◦ PDO = Physical Device Object - A Bus drivers child device enumerator for the PnP device tree◦ Control DO = Control Device Object - Non-PnP device or control interface ( Operation independent of PnP

Device stack … Queue )▫ Sets Device Attributes▫ Registers Required Callback Functions ( Not related to kernel-dispatcher events )

◦ EvtDeviceEject ◦ EvtIo* – Callback functions that handle specific types of IRP(s) from a particular IRP-Queue

◌ PnP Manager Codes▪ IRP_MN_EJECT – Only drivers for physical devices with an eject require handling the request▪

/***************************************************************************************************************************************************** Kernel Mode Device Driver based on:* Kernel Mode Driver Framework (KMDF) - A sub-division of the Windows Driver Foundation's (WDF) Windows Driver Kit (WDK) written in C* _In_ & _Out_ are Function parameter annotations; see http://msdn.microsoft.com/en-us/library/hh916382.aspx*

* DRIVER_OBJECT see http://msdn.microsoft.com/en-us/library/windows/hardware/ff544174%28v=vs.85%29.aspx** This version shows how to register for PNP and Power events, handle create & close file requests, handle WMI set and query events, fire WMI* notification events.*****************************************************************************************************************************************************/#include <ntddk.h> // #include the Windows-NT Device Driver Kit (DDK)#include <wdf.h> // #include the Windows Driver Foundation (WDF) Framework

A. DriverEntry()✔ Driver Object Reference @ http://msdn.microsoft.com/en-us/library/windows/hardware/dn265636%28v=vs.85%29.aspx

Call-Back Methods Structures/Enums Initialization Functions

EvtDriverDeviceAddEvtDriverUnload

WdfDriverCreateWdfDriverGetRegistryPathWdfDriverIsVersionAvailableWdfDriverMiniportUnloadWdfDriverOpenParametersRegistryKey

WDF_DRIVER_CONFIGWDF_DRIVER_INIT_FLAGSWDF_DRIVER_VERSION_AVAILABLE_PARAMS

WDF_DRIVER_CONFIG_INITWDF_DRIVER_VERSION_ABAILABLE_PARAMS_IN

/*********************************************************************************************************************** DriverEntry()* IN: DriverObject* IN: RegistryPath* DESC:* - First routine called by the OS-PnP Manager when driver gets loaded.* - Creates the Driver Object and Registers 'EvtDriverDeviceAdd' and 'EvtDriverUnload' functions.* - Export standard set of entry points using the OS data-structure DRIVER_OBJECT* - OS looks at the data-structure of function pointers to call when a request is targeted to a device described by DEVICE_OBJECT* Function dispatch table = contains a function pointer for each major function code the OS system supports* 28-functions can be supported but usually only 8 are: IRP_MJ_CREATE, CLOSE, READ, WRITE, PNP, POWER, DEVICE_CONTROL, and SYSTEM_CONTROL* by default all these functions point to a routine which indicates that major function is NOT supported.* Parameters:* DriverObject = represents the instance of the function driver that is loaded* into memory. DriverEntry must initialize members of DriverObject before it* returns to the caller. DriverObject is allocated by the system before the* driver is loaded, and it is released by the system after the system unloads* the function driver from memory.* * RegistryPath = represents the driver specific path in the Registry.* The function driver can use the path to store driver related data between* reboots. The path does not store hardware instance specific data.* Duties:* 1) Create a PDDRIVER_OBJECT Instance by calling WdfDriverCreate()* 2) Configure the DriverObject Instance using WDF_DRIVER_CONFIG_INIT(WDF_DRIVER_CONFIG)/*********************************************************************************************************************/NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath) {

NTSTATUS status = STATUS_SUCCESS; WDF_DRIVER_CONFIG config;

Page 73: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

KdPrint(("WDF DriverEntry() Function Driver Sample - Featured version\n")); KdPrint(("Built %s %s\n", __DATE__, __TIME__));

// Initialize driver config settings structure and register AddDevice() WDF_DRIVER_CONFIG_INIT( &config, MyEvtDeviceAdd );

// Create the Driver Object status = WdfDriverCreate(DriverObject, RegistryPath, WDF_NO_OBJECT_ATTRIBUTES, &config, WDF_NO_HANDLE);

if (!NT_SUCCESS(status)) { KdPrint( ("WdfDriverCreate failed with status 0x%x\n", status));} return status;}

B. EvtDeviceAdd()✔ Device Object Reference @ http://msdn.microsoft.com/en-us/library/windows/hardware/dn265631%28v=vs.85%29.aspx

✔ DevicePrefix Call (Verb) Item (Noun) Structure Structure Initializer

WdfDevice Create WDFDEVICE_INIT Device InitializerWdfDevice CreateDevice Interface Create InterfaceWdfDevice RetrieveDevice InterfaceString Retrieves symbolic link nameWdfDevice SetDevice InterfaceState Enables/Disables InterfaceEvtDevice Process QueryInterfaceRequest WDF_QUERY_INTERFACE_CONFIG WDF_QUERY_INTERFACE_CONFIG_INITWdfDevice Add QueryInterfaceWdfDevice Interface{Der/R}eference

NoOpWdfDeviceWdfDevice SetDevice State WDF_DEVICE_STATEWdfDevice Create SymbolicLinkWdfDevice MiniportCreate Creates device for miniport driverWdfDevice InitAssign

/RetrieveDeviceName WDFDEVICE_INIT

WdfDevice InitAssign SDDLString WDFDEVICE_INIT Security Setting

WdfDevice Init Free De-allocate WDFDEVICE_INITWdfDevice DeviceGet/InitSet/Set CharacteristicsWdfDevice InitSetDevice ClassWdfDevice InitSetDevice TypeWdfDevice InitSet ExclusiveWdfDevice Assign MofResourceNameWdfDevice Set Failed WDF_DEVICE_FAILED_ACTION Notify framework of FailureWdfDevice WdmGet DeviceObject WDM-model device objectWdfDevice WdmGet PhysicalDeviceWdfWdmDevice

GetWdf DeviceHandle Device Object for WDM device

WdfDevice/WdfFdoInit

OpenRegistryKey Access Windows Registry

WdfFdo InitSet DefaultChildListConfigWdfFdo InitSet EventCallbacks WDF_FDO_EVENT_CALLBACKS WDF_FDO_EVENT_CALLBACKS_INITEvtDevice Filter{Add/Remove} ResourceRequirements FDOEvtDevice RemoveAdded Resources FDOWdfFdo InitSet FilterWdfFdo InitWdmGet PhysicalDeviceWdfFdo Add StaticChildWdfFdo Get DefaultChildList WDF_CHILD_LIST_CONFIGWdfFdo {Lock/Unlock} StaticChildListForIterationWdfFdo QueryFor InterfaceWdfFdo Retrieve NextStaticChildWdfPdo Init AddCompatibleIDWdfPdo InitAdd DeviceTextWdfPdo InitAdd HardwareIDWdfPdo Init AllocateWdfPdo InitAllow ForwardingRequestToPare

ntWdfPdo InitAssign ContainerIDWdfPdo InitAssign DeviceIDWdfPdo InitAssign InstanceIDWdfPdo InitAssign RawDeviceWdfPdo InitSet DefaultLocaleWdfPdo InitSet EventCallbacks WDF_PDO_EVENT_CALLBACKS WDF_PDO_EVENT_CALLBACKS_INITEvtChildList CreateDeviceWdfChildList Get DeviceWdfChildList Retrieve AddressDescription WDF_CHILD_ADDRESS_DESCRIPTION

_HEADERWDF_CHILD_ADDRESS_DESCRIPTION_HEADER_INIT

Page 74: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

WdfChildList Retrieve PdoEvtChildList AddressDescription CleanupEvtChildList AddressDescription CopyEvtChildList AddressDescription DuplicateEvtChildListEvtChildList IdentificationDescripti

onCleanup WDF_CHILD_IDENTIFICATION_DESCR

IPTION_HEADERWDF_CHILD_IDENTIFICATION_DESCRIPTION_HEADER_INIT

EvtChildList IdentificationDescription

Compare

EvtChildList IdentificationDescription

Copy

EvtChildList IdentificationDescription

Duplicate

EvtChildList DeviceReenumerated

EvtChildList ScanForChildrenWdfChildList AddOrUpdate/Update

AllChildDescriptionAsPresent

WdfChildList Update ChildDescriptionAsMissingWdfChildList {Begin/End} IterationWdfChildList {Begin/End} ScanWdfChildList Create

WdfChildList Request ChildEjectWdfPdo Add/Remove EjectionRelationsPhysical

DeviceWdfPdo Clear EjectionRelationsDevicesWdfChildList Retrieve NextDeviceWdfChildList

✔ Device DependenciesPreFix Call Item Structure Structure Initializer

WdfDevice

Add/Remove DependentUsageDeviceObject Dependent driver

WdfDevice

Add/Remove RemovalRelationsPhysicalDevice Dependent driver/remove

WdfDevice

Clear RemovalRelationsDevices Remove all-drivers/dependence

WdfDevice

WdmGet AttachedDevice Gets next-lower device

WdfPdo Get ParentWdfPdo MarkMissingWdfPdo Request EjectWdfPdo Retrieve/Update AddressDescriptionWdfPdo Retrieve IdentificationDescription

✔ FilePreFix Call Item Structure Structure Initializer

WdfDevice

InitSet FileObjectConfig WDF_FILEOBJECT_CONFIG WDF_FILEOBJECT_CONFIG_INIT

WdfDevice

Get FileObject

Evt File Cleanup EvtDeviceFileCreate HANDLE Close access to deviceEvt File Close EvtDeviceFileCreate HANDLE Close access to deviceWdfDevice

Set SpecialFileSupport WDF_SPECIAL_FILE_TYPE Enable/Disable support for special files

✔ Access / File (Application I/O)PreFix Call Item Structure Structure Initializer

WdfDevice InitSet IoInCallerContextCallback Register EvtIoInCallerContext functionWdfDevice InitSet IoType Register function for IO buffers for special deviceWdfDevice/WdfFdoInit

AllocAndQueryProperty

WdfDevice/WdfFdoInit

QueryProperty Access device properties

WdfDevice {Set/Get} AlignmentRequirement Devices address for memory transferWdfDevice Get DriverWdfDevice Get IoTarget Pointer to Function that handles I/OWdfDevice Set BusInformationForChildre PNP_BUS_INFORMATION Information about a bus

Page 75: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

nEvtDevice Prepare HardwareEvtDevice SelfManag

edIoCleanup

EvtDevice SelfManaged

IoFlush

EvtDevice SelfManaged

IoInit

EvtDevice SelfManaged

IoRestart

EvtDevice SelfManaged

IoSuspend

EvtDevice UsageNotification WDF_SPECIAL_FILE_TYPE

EvtDeviceWdm

IrpPreprocess IRP – Structure Receives IRP before framework

EvtDeviceWdm

DispatchPreprocessedIrp Returns Preprocessed IRP to the framework

Evt IoInCallerContext Device Object, IRP Object I/O Request before I/O queue

✔ DEVICE_OBJECT◌ Called when a new device is plugged-in◌ Registers the Functions that the Driver will Support http://msdn.microsoft.com/en-

us/library/windows/hardware/dn265631%28v=vs.85%29.aspx

✔ Bus Driver = KMDF drivers indicate a “Bus Driver” by calling PDO initialization methods before creating it s Device Object in EvtAddDevice().

◌ Static Model – For PDO devices that are statically attached (ie: USB Host controller on the Motherboard)◌ Dynamic – For PDO devices that are hot-swappable (Plug n Play)

/*************************************************************************************************** EvtDeviceAdd()* IN: Driver = Handle to a framework driver object created in DriverEntry* IN: DeviceInit = Pointer to a framework-allocated WDFDEVICE_INIT structure.* DESC: Is called by the framework in response to AddDevice call from the PnP manager./*************************************************************************************************/NTSTATUS MyEvtDeviceAdd(IN WDFDRIVER Driver, IN PWDFDEVICE_INIT DeviceInit) {

// Initialize settings structures NTSTATUS status = STATUS_SUCCESS; WDF_PNPPOWER_EVENT_CALLBACKS pnpPowerCallbacks; WDF_OBJECT_ATTRIBUTES fdoAttributes; WDFDEVICE device; WDF_FILEOBJECT_CONFIG fileConfig; WDF_DEVICE_POWER_POLICY_IDLE_SETTINGS idleSettings; WDF_DEVICE_POWER_POLICY_WAKE_SETTINGS wakeSettings; WDF_POWER_POLICY_EVENT_CALLBACKS powerPolicyCallbacks; WDF_IO_QUEUE_CONFIG queueConfig; //PFDO_DATA fdoData; WDFQUEUE queue;

WDF_DEVICE_FAILED_ACTION *one;

UNREFERENCED_PARAMETER(Driver); PAGED_CODE(); KdPrint(("EventDeviceAdd called\n"));

one = new WDF_DEVICE_FAILED_ACTION;one->WdfDeviceFailedUndefined = 1;one.WdfDeviceFailedAttemptRestart;WdfDeviceSetFailed(&device, one);

B.1 Plug and Play (PnP)

✔ WDF Framework handles PnP and Power Management via a “State Machine” (Applies to both KMDF and UMDF)

Page 76: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

✔ Driver can implement particular “states” callback functions that it needs to handle specifically while leaving others for the WDF default implementations

◌ The WDF Default implementation can handle other parts of the framework so proper behavior occurs when a state transition occurs▪ Example: The I/O queue can stop dispatching requests when device is in a low-power state

✔ PnP OperationsPreFix Call Item Structure Structure Initializer

WdfDevice

Set PnpCapabilities WDF_DEVICE_PNP_CAPABILITIES

WDF_DEVICE_PNP_CAPABILITIES_INIT

WdfDevice

InitSet PnpPowerEventCallbacks

WDF_PNPPOWER_EVENT_CALLBACKS

WDF_PNPPOWER_EVENT_CALLBACKS_INIT

WdfDevice

GetDevice PnpState WDF_DEVICE_PNP_STATE

EvtDevice

PnpStateChange WDF_DEVICE_PNP_NOTIFICATION_DATA

WDF_DEVICE_PNP_CAPABILITIES_INIT

EvtDevice

ReleaseHardware When drive is no longer accessible

EvtDevice

SurpriseRemoval When device is hot-removed/failed

EvtDevice

SelfManaged

IoCleanup

EvtDevice

SelfManaged

IoInit

//-- [ PnP Power ] --//// WdfDeviceInitSetPnpPowerEventCallbacks() @ http://msdn.microsoft.com/en-us/library/windows/hardware/ff546135%28v=vs.85%29.aspx

// IN: &WDFDEVICE_INIT// IN: Initialized Structure -- WDF_PNPPOWER_EVENT_CALLBACKS_INIT( WDF_PNPPOWER_EVENT_CALLBACKS )// DESC: Initialize the pnpPowerCallbacks for PNP and Power events// -Or- use framework defaults which depend on DeviceInit being FDO, PDO or Filter DO.

WDF_PNPPOWER_EVENT_CALLBACKS_INIT(&pnpPowerCallbacks); pnpPowerCallbacks.EvtDevicePrepareHardware = EventDevicePrepareHardware; // PnP pnpPowerCallbacks.EvtDeviceReleaseHardware = EventDeviceReleaseHardware; // PnP pnpPowerCallbacks.EvtDeviceSelfManagedIoInit = EventDeviceSelfManagedIoInit; // PnP pnpPowerCallbacks.EvtDeviceD0Entry = EventDeviceD0Entry; // Power - Default/Empty? pnpPowerCallbacks.EvtDeviceD0Exit = EventDeviceD0Exit; // Power WdfDeviceInitSetPnpPowerEventCallbacks(DeviceInit, &pnpPowerCallbacks);

B.2 Power Management

✔ Power States◌ Sx = System Power States (Where 'x' is 0 to 5)

▪ S0 = Working State◌ Dx = Device Power States (Where 'x' is 0 to 3) higher uses less power and longest wake-up latency

▪ D0 = Working State

✔ PowerPreFix Call Item Structure Structure Initializer

WdfDevice

Set PowerCapabilities WDF_DEVICE_POWER_CAPABILITIES WDF_DEVICE_POWER_CAPABILITIES_INIT

WdfDevice

InitSet PowerPolicyEventCallbacks

WDF_POWER_POLICY_EVENT_CALLBACKS

WDF_POWER_POLICY_EVENT_CALLBACKS_INIT

WdfDevice

InitRegister PowerPolicyStateChangeCallback

WdfDevice

InitSet PowerPolicyOwnership

EvtDevice

PowerPolicyStateChange

WDF_DEVICE_POWER_POLICY_NOTIFICATION_DATA

WdfDevice

GetDevice PowerPolicyState

WdfDevice

GetDevice PowerState WDF_DEVICE_POWER_STATE (Returns)

WdfDevice

InitRegister PowerStateChangeCallback

EvtDevice

PowerStateChange WDF_DEVICE_POWER_NOTIFICATION_DATA

WdfDevice

InitSet PowerInrush Device requires inrush current @ start-up

WdfDevice

InitSetPower{Not}

Pageable Driver accepts pageable data during sleep or not

WdfDevice

{Set/Get}Device

State WDF_DEVICE_STATE (Returns) WDF_DEVICE_STATE_INIT

WdfDevice

Get SystemPowerAction Current system power action if any

Page 77: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

WdfDevice

Assign S0IdleSettings WDF_DEVICE_POWER_POLICY_IDLE_SETTINGS

WDF_DEVICE_POWER_POLICY_IDLE_SETTINGS_INIT

WdfDevice

Assign SxWakeSettings WDF_DEVICE_POWER_POLICY_WAKE_SETTINGS

WDF_DEVICE_POWER_POLICY_WAKE_SETTINGS_INIT

WdfDevice

Indicate WakeStatus Device has awoke

WdfDevice

{Stop/Resume}Idle

Not in use; ok for idle state

WdfDevice

Set StaticStopRemove Whether device can be removed

EvtDevice

{Arm/Disarm}

WakeFromS0 WDF_DEVICE_PNP_CAPABILITIES WDF_DEVICE_PNP_CAPABILITIES_INIT

EvtDevice

{Arm/Disarm}

WakeFromSx WDF_PNPPOWER_EVENT_CALLBACKS WDF_PNPPOWER_EVENT_CALLBACKS_INIT

EvtDevice

Arm WakeFromSxWithReason

EvtDevice

WakeFromS0Triggered

EvtDevice

WakeFromSxTriggered

EvtDevice

D0{Entry/Exit}

WDF_POWER_DEVICE_STATE

EvtDevice

D0Entry PostInterruptsEnabled WDF_POWER_DEVICE_STATE

EvtDevice

D0Exit PreInterruptsDisabled

WdfDev

StateIsNP WDF_DEVICE_POWER_STATE Is Non-Pageable

WdfDev

StateNormalize State machine states as index

EvtDevice

Disable/Enable

WakeAtBus PDO

EvtDevice

Eject PDO

EvtDevice

ResourceRequirementsQuery

EvtDevice

ResourcesQuery

EvtDevice

Set Lock

EvtDevice

ShutdownNotification WDF_DEVICE_SHUTDOWN_FLAGS

Wdf ControlDeviceInit

Allocate

Wdf ControlDeviceInitSet

ShutdownNotification

Wdf Control FinishInitializing

Po Register/Unregisted

PowerSettingCallback

//-- [ Power Policy ] --//// WdfDeviceInitSetPowerPolicyEventCallbacks() @ http://msdn.microsoft.com/en-us/library/windows/hardware/ff546774%28v=vs.85%29.aspx// IN: &WDFDEVICE_INIT// IN: Initialized Structure -- WDF_POWER_POLICY_EVENT_CALLBACKS_INIT( WDF_POWER_POLICY_EVENT_CALLBACKS )

// DESC: Register Power-Policy callbacks to handle arm/disarm ing the hardware ( wait-wake when wake event is triggered by device)// WdfDeviceInit | SetPowerPolicy | EventCallbacks() @

WDF_POWER_POLICY_EVENT_CALLBACKS_INIT(&powerPolicyCallbacks); powerPolicyCallbacks.EvtDeviceArmWakeFromS0 = EventDeviceArmWakeFromS0; powerPolicyCallbacks.EvtDeviceDisarmWakeFromS0 = EventDeviceDisarmWakeFromS0; powerPolicyCallbacks.EvtDeviceWakeFromS0Triggered = EventDeviceWakeFromS0Triggered; powerPolicyCallbacks.EvtDeviceArmWakeFromSx = EventDeviceArmWakeFromSx; powerPolicyCallbacks.EvtDeviceDisarmWakeFromSx = EventDeviceDisarmWakeFromSx; powerPolicyCallbacks.EvtDeviceWakeFromSxTriggered = EventDeviceWakeFromSxTriggered; WdfDeviceInitSetPowerPolicyEventCallbacks(DeviceInit, &powerPolicyCallbacks);

// // Register the power policy callbacks. // WdfDeviceInitSetPowerPolicyEventCallbacks(DeviceInit, &powerPolicyCallbacks);

Page 78: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

//-- [ Dx Power ] Callbacks --// // Set the idle power policy to put the device to Dx if the device is not used for the specified IdleTimeout time.

// Since this is a virtual device we tell the framework that we cannot wake ourself if we sleep in S0. // Only way the device can be brought to D0 is if the device recieves an I/O from the system.

WDF_DEVICE_POWER_POLICY_IDLE_SETTINGS_INIT(&idleSettings, IdleCannotWakeFromS0); idleSettings.IdleTimeout = 60000; // 60 secs idle timeout status = WdfDeviceAssignS0IdleSettings(device, &idleSettings); if (!NT_SUCCESS(status)) { KdPrint( ("WdfDeviceAssignS0IdleSettings failed 0x%x\n", status)); return status;}

//-- [ Wait-wake policy ] --// WDF_DEVICE_POWER_POLICY_WAKE_SETTINGS_INIT(&wakeSettings); status = WdfDeviceAssignSxWakeSettings(device, &wakeSettings); if (!NT_SUCCESS(status)) { // We are probably enumerated on a bus that doesn't support Sx-wake. // Let us not fail the device add just because we aren't able to support // wait-wake. I will let the user of this sample decide how important it's // to support wait-wake for their hardware and return appropriate status. KdPrint( ("WdfDeviceAssignSxWakeSettings failed 0x%x\n", status)); status = STATUS_SUCCESS;}

B.3 File / Context//-- [ File Object ] --//

// For Immediate IRP(s) -> Non-Queue // WdfDeviceInitSetFileObjectConfig() @ http://msdn.microsoft.com/en-us/library/windows/hardware/ff546107%28v=vs.85%29.aspx

// IN: Struct to tell the // DESC: Handle Create, Close and Cleanup requests for other IRP(s). WDF_FILEOBJECT_CONFIG_INIT(&fileConfig, EventDeviceFileCreate, EventFileClose, WDF_NO_EVENT_CALLBACK); WdfDeviceInitSetFileObjectConfig(DeviceInit, &fileConfig, WDF_NO_OBJECT_ATTRIBUTES);

//-- [ Register context cleanup ] --// // This cleanup will be called in the context of pnp remove-device when the framework deletes the device object. fdoAttributes.EvtCleanupCallback = EventDeviceContextCleanup;

B.4 Device //-- [ Create Device ] --// // DeviceInit is completely initialized so create the device and attach it to the lower stack status = WdfDeviceCreate(&DeviceInit, &fdoAttributes, &device); if (!NT_SUCCESS(status)) { KdPrint( ("WdfDeviceCreate failed with Status code 0x%x\n", status)); return status;}

B.5 Interface //-- [ Create Interface ] --//

// Tell the Framework that this device will need an interface so that applications can find our device and talk to it. status = WdfDeviceCreateDeviceInterface(device, (LPGUID) &GUID_DEVINTERFACE_TOASTER, NULL); if (!NT_SUCCESS (status)) { KdPrint( ("WdfDeviceCreateDeviceInterface failed 0x%x\n", status)); return status;}

B.6 I/O Handling 1. KMDF packages device I/O into IRP(s) (ie:.. WdfRequest Object) @ the I/O-Request Handler and Queues or Directly transfers I/O. 2. Determines if the driver has a configured a I/O- Queue for the request and queues the request 3. Checks the PnP power state for “D0” operational state and turns-on device if necessary 4. ELSE the request fails

✔ WDF Framework manages the flow of I/O requests by creating a queue object and configuration it◌ Dispatching Type – Queues are configured by the type of dispatching◌ IRP Type – Queues are configured by the type of I/O request

✔ WDF Framework adds requests to the queue and dispatches according to drivers specification◌ Specification Types of IRP queue handling (PnP / Power-Managment handle the three differently)

▪ Parallel - Queue pushes requests to the driver as soon as they arrive▪ Sequential - Queue pushes requests to the driver synchronously▪ Manual - Driver pulls requests from the queue as needed

◌ PnP / Power Management events on the queue▪ Driver specifies what happens on queue during start, stop and resume events▪ Windows I/O is inherently Asynchronous so drivers must cope with race conditions and locks if not using the default cancellation

system in the WDF framwork.▪ Drivers must synchronize access to shared data (Windows is multi-threaded; default WDF is to lock/hold requests and

synchronization scope )▫ UMDF calls this the “locking constraint” and applies only to device objects – default; Device Scope▫ Objects synchronization scope tells WDF if it can invoke multiple callbacks on the object concurrently

◦ Can be specified for drivers, device, and file objects▫ Synchronization Scopes

◦ Device = Don't call certain I/O event callbacks concurrently for a single device object or any file object or queue objects that are its children

◦ Queue = Per Queue basis do not call IRP callbacks concurrently

Page 79: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

◦ None = WDF can call any callbacks concurrently (default setting)

✔ IRP Major Function Codes @ http://msdn.microsoft.com/en-us/library/windows/hardware/ff550710%28v=vs.85%29.aspx ✔ Required Dispatch Routines @ http://msdn.microsoft.com/en-us/library/windows/hardware/ff561060%28v=vs.85%29.aspx ✔ How Requests are dispatched from the queue

◌ IO Target Device (WDF framework object that represents a driver)◌ IO Target is default the next driver in the driver stack

✔ Communications◌ I/O Request Packet (IRP) = All windows I/O requests are carried by an IRP which is a kernel data structure.

▪ Write IRP Packet = Data to be written to the device - WriteFile()▪ Read IRP Packet = Pass buffer to driver to be filled with data from the device - ReadFile()▪ I/O Control Packet = Other than read/write purpose (e.g. Type, Status) - DeviceIoControl()

▫ PnP Manager Packet▫ Power Manager Packet▫ Device Status▫ Device Queries

▪ IoCallDriver() = Sends an IRP to a driver▫ Pointer to a DRIVER_OBJECT▫ Pointer to the IRP instance▫ If the target driver is the next on the driver stack the IRP is called a “local” I/O Target else it is called a “remote” I/O Target

◌ IRP - I/O Transfer Types▪ Buffered = IRP has a pointer to Kernel buffer space (ie: METHOD_BUFFERED)▪ Direct = A Memory Descriptor List (MDL) is passed to the driver (ie: METHOD_DIRECT)▪ Neither = Buffer size and address in client space is passed to the driver (ie: METHOD_NEITHER)

◌ Interrupt Request's (IRQ)▪ EvtIoRead

✔ How Power Management events affect the queue◌ WDF integrates PnP / Power Management with the I/O Queue by canceling the queue requests during power-save states.

◌ Handling IRP(s) @ http://msdn.microsoft.com/en-us/library/windows/hardware/ff546847%28v=vs.85%29.aspx ◌ Writing Dispatch Routines to handle IRP(s) @ http://msdn.microsoft.com/en-

us/library/windows/hardware/ff566407%28v=vs.85%29.aspx

✔ IRPPreFix Call Item Structure Structure Initializer

WdfDevice

InitAssign

WdmIrpPreprocessCallback

IRP Major Code handler

WdfRequest

Allocate

Timer

WdfRequest

Cancel SentRequest

WdfRequest

Change Target

WdfRequest

Complete

WdfRequest

CompleteWithInformation

WdfRequest

CompleteWithPriorityBoost

WdfRequest

Create

WdfRequest

CreateFromIrp

WdfRequest

Format RequestUsingCurrentType

WdfRequest

ForwardToIoQueue

WdfRequest

ForwardToParentDeviceIoQueue

WdfRequest

Get CompletionParams

WdfRequest

Get FileObject

Get InformationGet IoQueueGet ParametersGet RequestorMode

Page 80: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

✔ QueryPreFix Call Structure Structure Initializer

WdfDevice InitSetRequestAttributes Apply to IRP(s) attributes at QueueWdfDevice ConfigureRequestDispatching Assigns IRP to specific queueWdfDevice DeviceEnqueueRequest IRP Type → FrameworkWdfDevice GetDefaultQueue Devices default queue handleEvtDevice QueryRemoveEvtDevice QueryStopEvtDevice RelationsQuery

EvtIo AllocateRequestResourcesEvtIo AllocateResourcesForReservedR

equestEvtIo CanceledOnQueueEvtIo DefaultEvtIo DeviceControlEvtIoWdm IrpForForwardProgress WDF_IO_FORWARD_PROGRESS_AC

TIONWdfIoQueue AssignForwardProgressPolicy WDF_IO_QUEUE_FORWARD_PROGR

ESS_POLICYEvtIo InternalDeviceControlEvtIo QueueStateWdfIoQueue StartEvtIo ReadEvtIo ResumeWdfIoQueue/EvtIo

Stop

WdfIoQueue StopSynchronouslyEvtIo WriteWdfIoQueue Create WDF_IO_QUEUE_CONFIG WDF_IO_QUEUE_CONFIG_INIT

WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE

WdfIoQueue DrainWdfIoQueue DrainSynchronouslyWdfIoQueue FindRequestWdfIoQueue GetDeviceWdfIoQueue GetStateWdfIoQueue PurgeWdfIoQueue PurgeSynchronouslyWdfIoQueue ReadyNotifyWdfIoQueue RetrieveFoundRequestWdfIoQueue RetrieveNextRequestWdfIoQueue RetrieveRequestByFileObject

//-- [ I/O Queue ] --// // Register I/O IRP_MJ_READ, IRP_MJ_WRITE, and IRP_MJ_DEVICE_CONTROL callbacks

// IRP(s) go to: Registered, default EvtIoDefault handler, or fails to STATUS_INVALID_DEVICE_REQUEST. // Create default queue - gets all the requests that are not configure-fowarded using WdfDeviceConfigureRequestDispatching.

// Dispatch Types (WdfIoQueueDispatch)// Sequential = IRP(s) -> EvtIo(Read/Write/{Internal}DeviceControl/Default) request handlers -> WdfRequestComplete (one at a time)// Parallel = Handle I/O request simultaneously (must protect simultaneously accessed data).// Manual =

WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE(&queueConfig, WdfIoQueueDispatchParallel); // EvtIoCancel queueConfig.EvtIoRead = EventIoRead; queueConfig.EvtIoWrite = EventIoWrite; queueConfig.EvtIoDeviceControl = EventIoDeviceControl;

__analysis_assume(queueConfig.EvtIoStop != 0); // EvtIoStop to prevent SDV warning status = WdfIoQueueCreate(device, &queueConfig, WDF_NO_OBJECT_ATTRIBUTES, &queue ); __analysis_assume(queueConfig.EvtIoStop == 0);

if (!NT_SUCCESS (status)) { KdPrint( ("WdfIoQueueCreate failed 0x%x\n", status)); return status;}

//--[ Finally register all our WMI datablocks with WMI subsystem. ]--// status = ToasterWmiRegistration(device); return status;}

Page 81: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

//--[ // Set the idle power policy to put the device to Dx if the device is not used // for the specified IdleTimeout time. Since this is a virtual device we // tell the framework that we cannot wake ourself if we sleep in S0. Only // way the device can be brought to D0 is if the device recieves an I/O from // the system. // WDF_DEVICE_POWER_POLICY_IDLE_SETTINGS_INIT(&idleSettings, IdleCannotWakeFromS0); idleSettings.IdleTimeout = 60000; // 60 secs idle timeout status = WdfDeviceAssignS0IdleSettings(device, &idleSettings); if (!NT_SUCCESS(status)) { KdPrint( ("WdfDeviceAssignS0IdleSettings failed 0x%x\n", status)); return status; }

// // Set the wait-wake policy. //

WDF_DEVICE_POWER_POLICY_WAKE_SETTINGS_INIT(&wakeSettings); status = WdfDeviceAssignSxWakeSettings(device, &wakeSettings); if (!NT_SUCCESS(status)) { // // We are probably enumerated on a bus that doesn't support Sx-wake. // Let us not fail the device add just because we aren't able to support // wait-wake. I will let the user of this sample decide how important it's // to support wait-wake for their hardware and return appropriate status. // KdPrint( ("WdfDeviceAssignSxWakeSettings failed 0x%x\n", status)); status = STATUS_SUCCESS; }

// // Finally register all our WMI datablocks with WMI subsystem. // status = ToasterWmiRegistration(device);

// // Please note that if this event fails or eventually device gets removed // the framework will automatically take care of deregistering with // WMI, detaching and deleting the deviceobject and cleaning up other // resources. Framework does most of the resource cleanup during device // remove and driver unload. //

return status;}

C. Callback Functions/************************************************************************************************************* EventDevicePrepareHardware()* IN: Device - Handle to a framework device object.* IN: ResourcesRaw - Handle to a collection of framework resource objects.* This collection identifies the raw (bus-relative) hardware* resources that have been assigned to the device.* IN: ResourcesTranslated - Handle to a collection of framework resource objects.* This collection identifies the translated (system-physical)* hardware resources that have been assigned to the device.* The resources appear from the CPU's point of view.* Use this list of resources to map I/O space and* device-accessible memory into virtual address space* DESC:* When PnP manager sends IRP_MN_START_DEVICE; EvtDevicePrepareHardware() can:* - map resources* - Get USB device descriptors, config, and select configs.* - Download firmware to the device if firmware is reatained during D0 -> D3 states else use EvtDeviceD0Entry*************************************************************************************************************/NTSTATUS EventDevicePrepareHardware(WDFDEVICE Device, WDFCMRESLIST ResourcesRaw, WDFCMRESLIST ResourcesTranslated) {

//PFDO_DATA fdoData; NTSTATUS status = STATUS_SUCCESS; ULONG i; PCM_PARTIAL_RESOURCE_DESCRIPTOR descriptor;

//fdoData = ToasterFdoGetData(Device); UNREFERENCED_PARAMETER(Device); UNREFERENCED_PARAMETER(ResourcesRaw); KdPrint(("EventDevicePrepareHardware called\n")); PAGED_CODE();

// Get the number of items that are currently in the Resources collection for (i=0; i < WdfCmResourceListGetCount(ResourcesTranslated); i++) {

// iterate thru as many times to get more information about the each items descriptor = WdfCmResourceListGetDescriptor(ResourcesTranslated, i);

switch(descriptor->Type) {

case CmResourceTypePort: KdPrint(("I/O Port: (%x) Length: (%d)\n", descriptor->u.Port.Start.LowPart, descriptor->u.Port.Length)); break;

Page 82: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

case CmResourceTypeMemory: KdPrint(("Memory: (%x) Length: (%d)\n", descriptor->u.Memory.Start.LowPart, descriptor->u.Memory.Length)); break;

case CmResourceTypeInterrupt: KdPrint(("Interrupt level: 0x%0x, Vector: 0x%0x, Affinity: 0x%0Ix\n", descriptor->u.Interrupt.Level, descriptor->u.Interrupt.Vector, descriptor->u.Interrupt.Affinity)); break;

default: break; }

} // Fire device arrival event. ToasterFireArrivalEvent(Device); return status;}

/************************************************************************************************************* EventDeviceReleaseHardware()* IN: Device - Handle to a framework device object.* IN: ResourcesTranslated - Handle to a collection of framework resource objects.* This collection identifies the translated (system-physical)* hardware resources that have been assigned to the device.* The resources appear from the CPU's point of view.* Use this list of resources to map I/O space and* device-accessible memory into virtual address space* DESC:* EvtDeviceReleaseHardware is called by the framework whenever the PnP manager* is revoking ownership of our resources. This may be in response to either* IRP_MN_STOP_DEVICE or IRP_MN_REMOVE_DEVICE. The callback is made before* passing down the IRP to the lower driver.** In this callback, do anything necessary to free those resources.*************************************************************************************************************/NTSTATUS EventDeviceReleaseHardware(IN WDFDEVICE Device, IN WDFCMRESLIST ResourcesTranslated) {

//PFDO_DATA fdoData; UNREFERENCED_PARAMETER(Device); UNREFERENCED_PARAMETER(ResourcesTranslated); KdPrint(("EventDeviceReleaseHardware called\n")); PAGED_CODE();

//fdoData = ToasterFdoGetData(Device); // Unmap any I/O ports, registers that you mapped in PrepareHardware. // Disconnecting from the interrupt will be done automatically by the framework. return STATUS_SUCCESS;}

/************************************************************************************************************* EventDeviceSelfManagedIoInit()* IN: Device - Handle to a framework device object.* DESC:* EvtDeviceSelfManagedIoInit is called it once for each device,* after the framework has called the driver's EvtDeviceD0Entry* callback function for the first time. The framework does not* call the EvtDeviceSelfManagedIoInit callback function again for* that device, unless the device is removed and reconnected, or* the drivers are reloaded.** The EvtDeviceSelfManagedIoInit callback function must initialize* the self-managed I/O operations that the driver will handle* for the device.** This function is not marked pageable because this function is in the* device power up path. When a function is marked pagable and the code* section is paged out, it will generate a page fault which could impact* the fast resume behavior because the client driver will have to wait* until the system drivers can service this page fault.** In this callback, do anything necessary to free those resources.*************************************************************************************************************/NTSTATUS EventDeviceSelfManagedIoInit(IN WDFDEVICE Device) {

NTSTATUS status; PFDO_DATA fdoData;

KdPrint(("EventDeviceSelfManagedIoInit called\n")); fdoData = ToasterFdoGetData(Device);

// We will provide an example on how to get a bus-specific direct // call interface from a bus driver. status = WdfFdoQueryForInterface(Device, &GUID_TOASTER_INTERFACE_STANDARD, (PINTERFACE) &fdoData->BusInterface, sizeof(TOASTER_INTERFACE_STANDARD), 1, NULL);// InterfaceSpecific Data if(NT_SUCCESS(status)) { UCHAR powerlevel;

Page 83: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

// Call the direct callback functions to get the property or // configuration information of the device. (*fdoData->BusInterface.GetCrispinessLevel)(fdoData->BusInterface.InterfaceHeader.Context, &powerlevel); (*fdoData->BusInterface.SetCrispinessLevel)(fdoData->BusInterface.InterfaceHeader.Context, 8); (*fdoData->BusInterface.IsSafetyLockEnabled)(fdoData->BusInterface.InterfaceHeader.Context);

// Provider of this interface may have taken a reference on it. // So we must release the interface as soon as we are done using it. (*fdoData->BusInterface.InterfaceHeader.InterfaceDereference) ((PVOID)fdoData->BusInterface.InterfaceHeader.Context);

} else { // In this sample, we don't want to fail start just because we weren't // able to get the direct-call interface. If this driver is loaded on top // of a bus other than toaster, ToasterGetStandardInterface will return // an error. status = STATUS_SUCCESS; } return status;}

/************************************************************************************************************* EventDeviceContextCleanup()* IN: Device - Handle to a framework device object.* DESC: EvtDeviceContextCleanup event callback must perform any operations that are necessary before the specified device is removed. The framework calls the driver's EvtDeviceContextCleanup callback when the device is deleted in response to IRP_MN_REMOVE_DEVICE request.

In this callback, do anything necessary to free those resources.*************************************************************************************************************/VOID EventDeviceContextCleanup(IN WDFOBJECT Device) {

//PFDO_DATA fdoData; UNREFERENCED_PARAMETER(Device); KdPrint( ("EventDeviceContextCleanup called\n")); PAGED_CODE();

//fdoData = ToasterFdoGetData((WDFDEVICE)Device); return;}

/************************************************************************************************************* EventDeviceFileCreate()* IN: Device - Handle to a framework device object.* IN: FileObject - Pointer to fileobject that represents the open handle.* IN: CreateParams - Parameters for create* DESC: The framework calls a driver's EvtDeviceFileCreate callback when the framework receives an IRP_MJ_CREATE request. The system sends this request when a user application opens the device to perform an I/O operation, such as reading or writing to a device. This callback is called in the context of the thread that created the IRP_MJ_CREATE request.

In this callback, do anything necessary to free those resources.*************************************************************************************************************/VOID EventDeviceFileCreate (IN WDFDEVICE Device, IN WDFREQUEST Request, IN WDFFILEOBJECT FileObject) {

//PFDO_DATA fdoData; UNREFERENCED_PARAMETER(FileObject); UNREFERENCED_PARAMETER(Device); KdPrint( ("EventDeviceFileCreate %p\n", Device)); PAGED_CODE ();

// Get the device context given the device handle. //fdoData = ToasterFdoGetData(Device); WdfRequestComplete(Request, STATUS_SUCCESS); return;}

/************************************************************************************************************* EventFileClose()* IN: FileObject - Pointer to fileobject that represents the open handle.* DESC: EvtFileClose is called when all the handles represented by the FileObject is closed and all the references to FileObject is removed. This callback may get called in an arbitrary thread context instead of the thread that called CloseHandle. If you want to delete any per FileObject context that must be done in the context of the user thread that made the Create call, you should do that in the EvtDeviceCleanp callback.

In this callback, do anything necessary to free those resources.*************************************************************************************************************/VOID EventFileClose (IN WDFFILEOBJECT FileObject) {

//PFDO_DATA fdoData; UNREFERENCED_PARAMETER(FileObject); PAGED_CODE (); //fdoData = ToasterFdoGetData(WdfFileObjectGetDevice(FileObject)); KdPrint( ("EventFileClose\n")); return;}

Page 84: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

/************************************************************************************************************* EventIoRead()* IN: Queue - Handle to the framework queue object that is associated with the I/O request.* IN: Request - Handle to a framework request object.* IN: Lenght - Length of the data buffer associated with the request. The default property of the queue is to not dispatch zero lenght read & write requests to the driver and complete is with status success. So we will never get a zero length request.* DESC: Performs read to the toaster device. This event is called when the framework receives IRP_MJ_READ requests.*************************************************************************************************************/VOID EventIoRead (WDFQUEUE Queue, WDFREQUEST Request, size_t Length) {

NTSTATUS status; ULONG_PTR bytesCopied =0; WDFMEMORY memory;

UNREFERENCED_PARAMETER(Length); UNREFERENCED_PARAMETER(Queue); PAGED_CODE(); KdPrint(("EventIoRead: Request: 0x%p, Queue: 0x%p\n", Request, Queue));

// Get the request memory and perform read operation here status = WdfRequestRetrieveOutputMemory(Request, &memory); if(NT_SUCCESS(status) ) { // Copy data into the memory buffer using WdfMemoryCopyFromBuffer } WdfRequestCompleteWithInformation(Request, status, bytesCopied);}

/************************************************************************************************************* EventIoWrite()* Queue - Handle to the framework queue object that is associated with the I/O request.* Request - Handle to a framework request object.* Lenght - Length of the data buffer associated with the request. (0-lenght buffers aren't passed)* The default property of the queue is to not dispatch* zero lenght read & write requests to the driver and* complete is with status success. So we will never get* a zero length request.* DESC: Performs write to the toaster device. This event is called when the framework receives IRP_MJ_WRITE requests.*************************************************************************************************************/VOID EventIoWrite (WDFQUEUE Queue, WDFREQUEST Request, size_t Length) {

NTSTATUS status; WDFMEMORY memory; UNREFERENCED_PARAMETER(Queue); KdPrint(("EventIoWrite. Request: 0x%p, Queue: 0x%p\n", Request, Queue)); PAGED_CODE();

// Get the request buffer and perform write operation here status = WdfRequestRetrieveInputMemory(Request, &memory); if(NT_SUCCESS(status) ) { // 1) Use WdfMemoryCopyToBuffer to copy data from the request // to driver buffer. // 2) Or get the buffer pointer from the request by calling // WdfRequestRetrieveInputBuffer to transfer data to the hw // 3) Or you can get the buffer pointer from the memory handle // by calling WdfMemoryGetBuffer to transfer data to the hw. } WdfRequestCompleteWithInformation(Request, status, Length);}

/************************************************************************************************************* EventIoDeviceControl()* Queue - Handle to the framework queue object that is associated with the I/O request.* Request - Handle to a framework request object.* OutputBufferLength - length of the request's output buffer, if an output buffer is available.* InputBufferLength - length of the request's input buffer, if an input buffer is available.* IoControlCode - the driver-defined or system-defined I/O control code (IOCTL) that is associated with the request.* DESC: This event is called when the framework receives IRP_MJ_DEVICE_CONTROL requests from the system.*************************************************************************************************************/VOID EventIoDeviceControl(IN WDFQUEUE Queue,IN WDFREQUEST Request,IN size_t OutputBufferLength,

IN size_t InputBufferLength, IN ULONG IoControlCode) {

NTSTATUS status= STATUS_SUCCESS; WDF_DEVICE_STATE deviceState; WDFDEVICE hDevice = WdfIoQueueGetDevice(Queue);

UNREFERENCED_PARAMETER(OutputBufferLength); UNREFERENCED_PARAMETER(InputBufferLength); KdPrint(("EventIoDeviceControl called\n")); PAGED_CODE();

switch (IoControlCode) {

case IOCTL_TOASTER_DONT_DISPLAY_IN_UI_DEVICE: // This is just an example on how to hide your device in the // device manager. Please remove this code when you adapt // this sample for your hardware. WDF_DEVICE_STATE_INIT(&deviceState); deviceState.DontDisplayInUI = WdfTrue; WdfDeviceSetDeviceState( hDevice,

Page 85: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

&deviceState );

break;

default:status = STATUS_INVALID_DEVICE_REQUEST;

} // Complete the Request. WdfRequestCompleteWithInformation(Request, status, (ULONG_PTR) 0);}

/***************************************************************************************************************************************************** Device Driver based on* Kernel Mode Driver Framework (KMDF) - A sub-division of the Windows Driver Foundation's (WDF) Windows Driver Kit (WDK)* _In_ & _Out_ are Function parameter annotations; see http://msdn.microsoft.com/en-us/library/hh916382.aspx* Drivers export a standard set of entry point in its DriverEntry() by filling in a data-structure created by the OS called DRIVER_OBJECT* OS looks at the data-structure of function pointers to call when a request is targeted to a device described by DEVICE_OBJECT* Function dispatch table = contains a function pointer for each major function code the OS system supports* 28-functions can be supported but usually only 8 are: IRP_MJ_CREATE, CLOSE, READ, WRITE, PNP, POWER, DEVICE_CONTROL, and SYSTEM_CONTROL* by default all these functions point to a routine which indicates that major function is NOT supported.****************************************************************************************************************************************************/

DRIVER_INITIALIZE DriverEntry;EVT_WDF_DRIVER_DEVICE_ADD KmdfEvtDeviceAdd;

// All global variables must be defined in 'DeviceEntry' File ; This File

// All Device Drivers START at DriverEntry() which creates the DriverObject when the driver is loadedNTSTATUS DriverEntry(_In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath){ NTSTATUS status; WDF_DRIVER_CONFIG config;

//--- sends a string to the kernel debugger --//KdPrintEx(( DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "KmdfHelloWorld: DriverEntry\n" ));/*ULONG KdPrintEx( ULONG ComponentId,

ULONG Level,PCSTR Format,... arguments);*/

//-- Initializes WDF_DRIVER_CONFIG object; a driver's config structure --//WDF_DRIVER_CONFIG_INIT(&config, KmdfEvtDeviceAdd);/* WDF_DRIVER_CONFIG_INIT( PWDF_DRIVER_CONFIG Config,

PFN_WDF_DRIVER_DEVICE_ADD EvtDriverDeviceAdd );*/

//-- Creates a framework driver object for the calling driver --//status = WdfDriverCreate(DriverObject, RegistryPath, WDF_NO_OBJECT_ATTRIBUTES, &config, WDF_NO_HANDLE);/*NTSTATUS WdfDriverCreate( PDRIVER_OBJECT DriverObject,

PCUNICODE_STRING RegistryPath, PWDF_OBJECT_ATTRIBUTES DriverAttributes, PWDF_DRIVER_CONFIG DriverConfig, WDFDRIVER *Driver);*/

return status;}

//-- Each Device gets added --//NTSTATUS KmdfEvtDeviceAdd(_In_ WDFDRIVER Driver, _Inout_ PWDFDEVICE_INIT DeviceInit){ NTSTATUS status; WDFDEVICE hDevice; UNREFERENCED_PARAMETER(Driver);

KdPrintEx(( DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "KmdfHelloWorld: KmdfHelloWorldEvtDeviceAdd\n" )); status = WdfDeviceCreate(&DeviceInit, WDF_NO_OBJECT_ATTRIBUTES, &hDevice); return status;}

*/

7.3.3 User-Mode Driver Framework (UMDF)✔ UMDF cannot directly access the hardware (ie: DMA, IRQ or WMI)

◌ User-Mode = HRESULT (SUCCEED or FAILED; A type of the COM model)▪ UMDF = User-Mode Driver Framework

▫ Written in C++ (V1 is difficult and being deprecated / V2 is only supported on Windows 8.1 platforms)▫ Each process runs in a specific virtually addressed “user space”▫ Uses Libraries kernel32.dll, user32.dll, wingdi.dll, msvcrt.dll▫ Crash recovery without reboot▫ Debugging on same PC▫ Uses the Active Template Library (ATL); a C++ template library designed for COM objects

Page 86: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

▫ See http://msdn.microsoft.com/en-us/library/windows/hardware/dn265594%28v=vs.85%29.aspx

✔ UMDF Object Interfaces (ie: Abstract base classes) to inherit◌ IWDFObject – Base WDF object type◌ IWDFDriver – Driver object◌ IWDFDevice – Device object◌ IWDFFile – File Object◌ IWDFIoQueue – Queue of I/O requests◌ IWDFIoRequest – Describes and I/O Request Packet◌ IWDFIoTarget – Driver that is the target of an I/O Request Packet◌ IWDFMemory – Access to an area of memory

A. Reference

✔ Reference◌ Wiki-books Device Driver Introduction @ http://en.wikibooks.org/wiki/Windows_Programming/Device_Driver_Introduction◌ Windows driver development

▪ WDK Kit http://msdn.microsoft.com/en-US/windows/hardware/gg454513▪ Differences between WDM and WDF http://msdn.microsoft.com/en-us/library/windows/hardware/gg583838%28v=vs.85%29.aspx ▪ Device Driver Classes/Models http://msdn.microsoft.com/en-us/Library/Windows/Hardware/ff557557%28v=vs.85%29.aspx

◌ Windows WDK kit @ ◌ Windows driver development @ http://msdn.microsoft.com/en-us/windows/hardware/ff960953 ◌ Sample Drivers @ http://code.msdn.microsoft.com/windowshardware

◌ OSR Online – Everything windows driver development @ http://www.osronline.com/◌ OSR Online - Writing Windows Drivers @ http://www.osronline.com/article.cfm?article=20 ◌ CPU Architectures @ http://www.youtube.com/watch?v=H4Z0S9ZbC0g&index=5&list=PLNLBZ0YJh9Y_ShtMzUUaD321ess_idQlR

✔ USB Open Source◌ Install USB drivers - Libwdi @ https://github.com/pbatard/libwdi/wiki

▪ libusbx▪ libusb-win32▪ libusbK

7.3.4 Linux

A. Overview✔ Linux device drivers have 3-sides

◌ Kernel Communications – driver registers functions that will respond to events (open file, page fault, plug and play)▪ talk through initialization function, register_chrdev, hooking into timer interrupt

◌ Hardware Communications◌ User Communications – User → driver interface via device files (character / block device files) e.g. /dev/klife device file

B. Code✔ 'init' is called on driver initialization and 'exit' is called when driver is removed✔ init() will register hooks that will call driver code when an event occurs

◌ Driver registers chardev tied to a given “major number”

Static int __init klife_module_init(void) {int ret;pr_debug(“klife module init called\n”);if (( ret = register_chrdev(KLIFE_MAJOR_NUM, “klife”, &klife_fops) ) < 0 )

printk(KERN_ERR “register_chrdev: %d\n”, ret);return ret;

}

Registering Chardev hooks (ie: Event Calls Function Name)

struct file_operations klife_fops = {.owner = THIS_MODULE,.open = klife_open, // for allocating resources.release = klife_release, // releasing resources.read = klife_read, // generating and reading states of the device.write = klife_write, // start-up settings.mmap = klife_mmap, // faster but more complex direct access to device.ioctl = klife_ioctl // querying device and enabling/disabling timer interrupts

};

User Space access to “major number”# mknod /dev/klife c 250 0 // creates file

Page 87: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

Use Fileif ((kdf = open(“/dev/klife”, O_RDWR)) < 0 ) {

perror(“open /dev/klife”);exit(EXIT_FAILURE);

}

7.4 Assembly Language (ASM) ✔ Wiki http://en.wikipedia.org/wiki/Comparison_of_assemblers✔ Wiki http://en.wikipedia.org/wiki/Assembly_Language

✔ Terms◌ uOps - Micro-operations = (ie: Macro-instructions) Detailed low-level instructions to implement complex instructions

1. Common Processor Registers a) EAX = Function return b) EBX = Base pointer to the data section c) ECX = Counter for string/loop operators d) EDX = IO pointer

e) ESI = Source pointer for string f) EDI = Destination pointer for string

g) ESP = Stack Pointer h) EBP = Stack frame base pointer (here's where the function starts) i) EIP = Pointer to next instruction (instruction pointer) read-only access via 'JUMP' or 'CALL' j) X – Registers

• AH ( High Byte ) AL ( Low – Byte )• AXE, BXE, CXE – For 32-bit storage• AX, BX, CX – For 16-bit storage• Broken into AH(I/P can only be accessed at the 16-bit level

2. Register Conventions (Prevent register access conflicts) a) Caller-Save Registers (EAX, EDX, ECX) Parent is responsible for saving registers to the stack and restoring them before calling another

function that may destroy them. b) Callee-Save Registers (EBP, EBX, ESI, EDI) called function will never use/smash or is responsible for store/restore original values if

required to be used.

3. Saved at the beginning and restored at the end (looks pointless but very important for stomping) a) EFLAGS Register (32-bit of FLAGS) bit flagging (Boolean operations T/F Compare; set after each instruction) b) ZF (Zero Flag) = 1 if result is 0 c) SF (Signed Flag) = MSB but last number (2s Compliment) 0x7FFFF is used because 0x80000 = (-) negative numbers (Compiler handles

negative numbers)• • x86 Instructions

• NOP = No operation (exchanges EAX -> EAX)• - The Stack (RAM) up to OS where to put it (Reserves some chunk of RAM for FIFO) - Stack sequences from biggest address to little

address• - Data is pushed on and popped off (ESP always points at the first of the stack)• - Keeps track of parent function while going into called function (Just like Higher-Level-Language stacks)• - PUSH = Push value (Constants/Register Address's Value) onto stack (Not EIP; caller/jump handles that)• - POP = Gets top stack value puts into a register• - Calling Conventions• - cdecl(C declaration), stdcall (how to pass function arguments) • - cdecl = args are pushed onto stack from right to left• - take frame pointer (create new stack area) • - parent is responsible to clear passed parameters from

stack• - stdcall - callee is responsible to clear received parameters

from stack• - CALL = Set EIP

7.5 C & C++ 1. C++ contains

◌ Text Editor◌ Compiler – (.h & .cpp) → (.o) – Includes a Pre-

processor / Pre-Compiler that translates # items)◌ Linker – Links object code to missing functions (libraries)◌ Standard Library◌ Class Libraries

Page 88: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

◌ Debugger

2. Libraries◌ StdLib = C++ Standard Library◌ STL = Standard Template Library◌ Boost = Pre StdLib libraries

3. Standards = Committees have been organized to produce “standard” programming language specifications that compiler writers are encouraged to follow◌ ANSI

• Developed the ANSI C standard◌ ISO/IEC

• Developed the C++ Standard https://isocpp.org/std/the-committee

✔ Reserved ID naming◌ '__' and '_[A-Z]' - double underscore and underscore + capitol letter are reserved naming notations◌ '_*' - prefixed underscore is reserved at the global namespace; class and local naming is okay◌ is[a-z]* , mem[a-z]* , str[a-z]* , to[a-z]* , wcs[a-z]* are all reserved naming conventions and should not be used◌ E[A-Z]*, LC_[A-Z]* , SIG[A-Z]*, SIG_[A-Z]* are all reserved “macro” naming conventions and should not be used◌ C++ keywords are reserved

and break const double exte

rn if new private signed template typeid void

and_eq case const_ca

stdynamic_cast

false inline not protected sizeof this typena

mevolatile

asm catch continue else floa

t int not_eq public static throw union wchar_t

auto char default enum for long operator register static_c

ast TRUE unsigned while

bitand

class delete explicit frie

nd mutable or reintepret_cast struct try using xor

bitor

compl do export goto namespa

ce or_eq return switch typedef

virtual xor_eq

bool

✔ Literals = integer, float, boolean, char or string constant✔ Notation = dec, oct, hex

7.5.1 Compilers (GCC/MSVC)✔ GNU Compiler Collection (GCC) vs Microsoft Visual C++(MSVC)

◌ keyword 'abstract' is MS only◌ properties in C++ are MS only

✔ Pointer Unswizzling - is DE-referencing object pointers in memory before saving.✔ C++ Standard Library http://en.cppreference.com/w/cpp/header

✔ GCC = GNU Compiler Collection – An Integrated Compiler supporting multiple languages. (The abbreviation formerly stood for “GNU C Compiler”).

◌ Current language support – GCC can compile programs written in any of these languages▪ C – >gcc GNU C Compiler - Compiles (.c)(.cpp) as C and C++ respectively

✔ gcc compiling ANSI C files contains less predefined macros.▪ G++ – >g++ GNU C++ Compiler – Compiles (.c)(.cpp) both will be treated as C++

✔ Compiles straight to object code no ANSI C code will exist✔ Automatically include the 'std' C++ libraries (gcc does not do this)

▪ Objective-C – C++ compiler for OSX and iOS (Apple) with the Cocoa Library; also adds messaging to the C language (.mm source code fileextension)

▪ Ada – >GNAT Described in separate manual▪ Fortran – Described in separate manual▪ Java – Described in separate manual▪ Treelang – Described in separate manual

◌ Expanded language support – Front-ends to GCC are installers that expand language support▪ Mercury▪ Pascal

7.5.2 C++Standard Variables

Page 89: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

Data Types OPERATORSName Description Size* Range*char Character or small integer. 1byte signed: -128 to 127

unsigned: 0 to 255+ addition

- subtractionint Integer. 4bytes signed: -2147483648 to

2147483647unsigned: 0 to 4294967295

* multiplication

/ divisionbool Boolean value. (values: true or

false)1byte true or false % modulo

short int (short)

Short Integer. 2bytes signed: -32768 to 32767unsigned: 0 to 65535

long int (long) Long integer. 4bytes signed: -2147483648 to 2147483647unsigned: 0 to 4294967295

float Floating point number. 4bytes +/- 3.4e +/- 38 (~7 digits) CONDITIONALdouble Double precision floating point

number.8bytes +/- 1.7e +/- 308 (~15 digits) =

=Equal to

long double Long double precision floating point.

8bytes +/- 1.7e +/- 308 (~15 digits) != Not equal to

wchar_t Wide character. 2 or 4 bytes 1 wide character > Greater thanoperators which can appear in C++. From greatest to lowest priority, the priority order is as follows: < Less thanLevel Operator Description Grouping >

=Greater than or equal to

1 :: scope Left-to-right <=

Less than or equal to

2 () [] . -> ++dynamic_cast static_cast reinterpret_cast const_cast typeid

postfix Left-to-right && AND

3 ++ -- ~ ! sizeof new delete unary (prefix) Right-to-left || OR* & indirection and reference

(pointers)? : Condition ? True : False

+ - unary sign operator ESCAPE CHARACTERS4 (type) type casting Right-to-left \n newline5 .* ->* pointer-to-member Left-to-right \r carriage return6 * / % multiplicative Left-to-right \t tab7 + - additive Left-to-right \v vertical tab8 << >> shift Left-to-right \b backspace9 < > <= >= relational Left-to-right \f form feed (page feed)10 == != equality Left-to-right \a alert (beep)11 & bitwise AND Left-to-right \' single quote (')12 ^ bitwise XOR Left-to-right \" double quote (")13 | bitwise OR Left-to-right \? question mark (?)14 && logical AND Left-to-right \\ backslash (\)15 || logical OR Left-to-right16 ?: conditional Right-to-left17 = *= /= %= += -= >>= <<= &= ^= |

=assignment Right-to-left

18 , comma Left-to-rightCOMPOUND OPERATORS BITWISE OPERATORSexpression is equivalent to & AN

DBitwise AND

value += increase;

value = value + increase; | OR Bitwise Inclusive OR

a -= 5; a = a - 5; ^ XOR

Bitwise Exclusive OR

a /= b; a = a / b; ~ NOT

Unary complement (bit inversion)

price *= units + 1;

price = price * (units + 1); << SHL

Shift Left

>> SHR

Shift Right

A. Header File// C++ source code is typically broken out into 2-text files (.h/.cpp)/************************************************************************************************************ (.h) Header files = Define the Interface ( Classes / Prototypes / Structure )* - #includes Inherited classes that are required* - structure declares Struct, class, union* - global prototypes Global (non-member) function signatures, constants and variables* - see also: http://embeddedgurus.com/barr-code/2010/11/what-belongs-in-a-c-h-header-file/************************************************************************************************************/

A.1 #Pre-processor directives// PRE-PROCESSOR directives = Source code manipuation before compilation(ie: code -> executable)

#ifndef MYHEADER_H // 'MYHEADER_H' = If pre-processor variable is not defined THEN

Page 90: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

#define MYHEADER_H // Set MYHEADER_H as defined and include code block (#if->#endif)

A.2 #Include/Using

✔ <iostream> C++ standard library 'std' namespace = <stdio.h> in C▪ New style #include doesn't necessarily represent a file-name (why .h was removed) the actual file is decoded by the compiler.▪ New header files = Includes with no (.h) and prefix of 'c' (e.g. <cstring>) and all 'c' prefixes are part of the 'std'

namespace. (prevents name collisions)▪ “using namespace std” - puts the 'std' name-space into the global name-space for default non-name-space identified calls.

#include <stdafx.h> // #INCLUDE = Reference outside library code#include <iostream> //#include <string> //#include <array> // Standard Library(StdLib) Containers#include <vector> //#include <list> //#include <set> //#include <map> //#include <stack> //#include <queue> //

using namespace System; //------------------ SCOPE / TYPEDEF --------------------------------------------------------------------using namespace std; // using = Default namespace scope; Find commands in this namesapce if not specifically specifiedtypedef unsigned long ulong; // typedef = Name for existing type; typedef struct udt{...} is acceptable (e.g. ulong = "unsigned long")int inline InlineAdd(int a, int b) { // inline = Pre-Processor function declaration to be expanded to command-list where called

return a + b; }

A.3 Namespace/Class/Struct/Unionnamespace myspace { //------------------ BLOCK STRUCTURES -------------------------------------------------------------------

// namespace = Named block of top-level code (typically one namespace per project)// class = Named design containing data and/or function code (all members are 'private' by

default)class Arrays; // struct = Named class typically for data structures only (all members are 'public' by

default)union aunion; // union = Named single storage compartment having various data types associated with it

(protocol usage)// --- Class Types ---

class AbstractABC; // ABC = Abstract base class cannot be initialized / objectified (1+ pure-virtual members)

template<class T> class Concrete; // Concrete = a class that allows object instances (No pure-virtual members)

class Interface { // Interface = An abstract-base-class(ABC) never having any functionality (All pure-virtual members)

public:virtual void Input(int) = 0; // virtual = allows the function to be over-ridden in a derived classesvirtual int Output() = 0; // pure-virtual = a member "func() =0" which makes the class abstract(ABC)

};

struct Fundamental_Data_Types { //--------------------- DATA TYPES ----------------------------------------------------------------------

bool Abool; // Boolean = true/false 1-byteshort AShort; // Short = 32,767(+/-) 2-byteint AnInt; // Integer = 2,147,483,648(+/-) 4-bytelong ALong; // Long = 2,147,483,648(+/-) 4-bytefloat Afloat; // Float = E+/-38 ~7 digits 4-bytedouble Adouble; // Double = precision ~15 digits 8-bytechar AChar; // character = (1)ASCII character 1-byte others: char16_t, char32_t, wchar_t(2/4-byte)wchar_t AWChar;char Charray[5][5]; // arrays - Any data type can be a single[index] or multi[5][5] dimensional array.ulong ultype; // user-defined = typedef name (See 'typedef' above)

} FData; // ** Optionally ** classes, struct, and union can initiate objects(CSV) right away (e.g. 'FData' object)

struct STL_Containers {std::string name; // Multi-character stringsstd::vector<int> vect; // Dynamic array typestd::list<int> linklist; // Link liststd::set<int> aset; // Data Setsstd::map<string,int> amap; // Dictionary - Hash Tablestd::stack<string> astack; // Stackstd::queue<string> aqueue; // Queue

} STLCon;}//#endif

B. Source File/************************************************************************************************************ (.cpp) C++ source code "body" file* - File where header(.h) declaration are defined (over-riding the empty declarations)* -************************************************************************************************************/// #include <ThisFile.h>using namespace myspace;

class myspace::AbstractABC { //---------------------------- MEMBERS ------------------------------------------------------------------

private: // private = members that are visible/accessible in-classprotected: string thewords; // protected = members that are visible/accessible in-class and derived-classes

public: // public = members that are visible/accessible everywhere

Page 91: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

int LetterCount; // Field = public data membervirtual void Words(string in) { // Property(Set) = C++ doesn't natively support properties; use over-loading instead

this->thewords = in;} // this = pointer to the object instance currently being executedvirtual string Words() { // Property(Get) = OVER-LOADS function 'Words' (callers argument count/type determine which

function to use)return this->thewords;} // return = value returned by the call ('void'= no return value; 'string' in this case

is type returned)virtual void Display() = 0; // Function() = pure virtual function

};

template<class T> // template<T> = Identifies 'data type' used in the class; set by the initializing callerclass myspace::Concrete : // [:] = Inherits

public Interface, // ***** NOTE: Variables cannot be initialized in the original class definitions *****public AbstractABC { //private: T iIn; // typename T = is the received template argument passed to this class @ initializationpublic: //

Concrete(int a) { iIn = a;} // Constructor = Gets called automatically when an object of this class is created (ie: 'new')

~Concrete() { iIn = 0;} // Destructor = Gets called automatically when an object of this class is destroyed (ie: 'delete')

void Input(T In) { this->iIn = In;} // Implement code-bodies for the Interface membersT Output() { return this->iIn; } //void Display() { // Implement code-bodies for the AbstractABC class - Only Display() is still a pure-virtual

std::cout << "Input = " << Output()<< "\n";std::cout << "Words = " << Words() << "\n";printf("Protected 'thewords' = %s\n",this->thewords);

}};

int main() //--------------------------------- Main() Start-up Function ----------------------------------------{

//---------------------------- Storage Specifiers ---------------------------------------------------

auto Hi = "Hi there"; // auto = Initializing value automatically determine data type//extern Ext; // extern = object with external **linkage** defined in a different source file//mutable ConstChange; // mutable = data member that can be modified even if the containing object is constvolatile int HrdwIO; // volatile = a variable tied to a hardware register (changes w/o being set by code)static int iAllObjects; // static = One variable for all object instancesconst int CONST = 3; // const = Read only (can be applied to data types or classes)char hello[] = "Hello"; // Initial Bounds = array bounds are auto-set by initializing value.//int iarray[]; // Bound-less = Initialize a bound-less arraydecltype(Hi) Bye; // decltype = obtain data type for variable 'Hi'

//---------------------------- Value Assignments ----------------------------------------------------

FData.ALong = 1L; // (Pre)(Suf)fix = Assignment values can have type identifiersFData.ALong = 07L; // 0 = Octal L = LongFData.ALong = 0x1UL; // 0x = Hex U = UnsignedFData.Afloat = 1.1E-24F; // E = ExponentF = FLOATFData.AChar = L'a'; // L = wchar_tFData.AChar = '\07'; // Char Octal 7FData.AChar = '\xFF'; // Char Hex "FF"FData.AWChar = '\u00C0'; // Char Unicode ASCII character 0x03C0*/FData.Charray[0][0] = 'A'; //

FData.Adouble= (double)3; //----------------------------- Type Casting --------------------------------------------------------

FData.Abool = bool(1); ////FData.Afloat = const_cast<int>(&3); // Type must be pointer, reference or pointer to member of an object//FData.ALong = dynamic_cast; // Must be pointer or reference to a complete class type//FData.AShort = reinterpret_cast; //FData.AnInt = static_cast<int>(3.3); //

Console::WriteLine(L"Main()"); // Believe 'Console' is Windows Only

int IntVal = 50; //----------------------------- NAME & POINTER addressing -------------------------------------------

int *AddrPtr; // type [*] = declare pointer variablesprintf(" IntVal = %d\n", IntVal); // printf = ANSI C print to standard output (e.g. print the named variable 'IntVal')printf("&IntVal = %x\n", &IntVal); // [&] = AddressOfAddrPtr = &IntVal; // [=] = Assign (e.g. AddrPtr = AddressOf(IntVal))printf(" AddrPtr = %x\n", AddrPtr); //printf("*AddrPtr = %d\n\n", *AddrPtr); // [*] = Dereference pointer (ie: Return Value@Address)Concrete<int> myobj(111); // type 'name' = will auto-initiate a named objectConcrete<int> *ObjPointer; //ObjPointer = new Concrete<int>(3); // new = Initiate an un-named object at 'ObjPointer' addressmyobj.Display(); // [.] = call a named object memberObjPointer->Display(); // [->] = call a un-named pointer object member

STLCon.name = "Hello";std::cout << InlineAdd(2,3); //----------------------------- Flow Control

--------------------------------------------------------for(int i = 0; i < 5; i++) { // for-loop = for(variable; loop again condition; per loop command) { commands }

if (i == 1) // ifSTLCon.name = "One\n";

else if (i == 2) // else ifcontinue; // continue = immediate next-iteration ie: skip the rest of the loop

else if (i == 4)break; // break = immediate exit ie: Exit the loop without finishing

else // else =if (i != 0)

STLCon.name = "Empty\n";try { // try = Error Handling routine

Page 92: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

std::cout << STLCon.name; // cout = C++ send to standard output (e.g. standard output(console) receives STLCon.name)

throw exception("My Exception"); // throw = Raise a runtime error} catch (...) { // catch = Catch a runtime error; (...) = Catch 'ALL' exception errors

std::cerr << "Something"; // cerr = Send to startard output 'err' pipe}

}for(char c : STLCon.name) { // for : = for each item in region

std::cout << "[" << c << "]";} //while (IntVal > 0 ) { // while

std::cout << IntVal << "\n";IntVal--;}

do { // do-whilestd::cout << IntVal++ << "\n";

} while (IntVal <= 5);switch (IntVal) { // switch-case

case 1: // casestd::cout << "One";break; // if 'break' is missing both 'case 1' block and 'default' block would execute when IntVal = 1

case 2: //std::cout << "Two";break;

default: // default = no 'break' were incountered (ie: no cases were satisfied)std::cout << "Not One or Two";

} return 0; // main return = '0' to the Operating System(OS) indicating a successful run}

B.1 Details

✔ int main() in C++ = int main(void) in C ('void' isn't required in C++)✔ '<<' (output operator) in C++ shifts something into 'cout' the screen - C uses printf() to print on screen (C++ supports printf also)✔ '>>' (input operator) in C++ 'cin' = standard input device

✔ Single value initial assignments◌ Type X(99); is the same as Type X = 99;

✔ char me[] = "String Literal"; //Which is a character array with terminator \0✔ void* - Any data type but must be defined before *✔ NULL = 0 or pointer that goes no-where

✔ Lambda functions are code blocks (ie: Like a function w/o a name)✔ auto is like template T but determines type automatically (need to look into this one a little more)

✔ Struct, Class, Union◌ struct – A UDT or Class generally used to declared plain data structures, can also be used to declare classes that have member functions, with

the same syntax as with keyword class. The only difference between both is that members of classes declared with the keyword struct have public access by default, while members of classes declared with the keyword class have private access by default. For all other purposes both keywords are equivalent in this context.

◌ Unions - is different from that of classes declared with struct and class, since unions only store one data member at a time, but nevertheless they are also classes and can thus also hold member functions. The default access in union classes is public.

✔ Only base classes are allowed 'pure-virtual' members

✔ C++ Dynamic Link Library (DLL)◌ Has a main entry point “DllMain()” that gets called by each connecting application◌ DLL defines its own interface which is exported as a (.LIB) file that applications link to

✔ Reference◌ CplusPlus Tutorial http://www.cplusplus.com/doc/tutorial/◌ Standard C++ Library Reference http://www.cplusplus.com/reference/ ◌

C. Qt✔ Use CONFIG -= QT to omit all Qt libraries form the Qt Creator

◌ Had to un-install VS 6.0 to get to work; don't know why or how to get around it.◌ Add CONFIG += c++11 to your Qt .pro file for C11++ support.

D. Makefile 1. Variables

◌ NAME = VALUE◌ Special

• $@ = Name of the file to be made• $? = Names of the changed dependents

2. MS editions of Make is Nmake◌ Research also

• Visual Studio uses MSBuild• Nant scripts to automate build and test units (build server)

Page 93: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

• 'devenv.exe' = make commands• '.vcproj' = Makefile• '.sln' = $(Make) ie: Root directory makefile will find recursively other makefiles whereas .sln has list of projects and

dependancies• 'cl.exe' = 'g++' Compilers

3. about linux makefile

4. Line types: 5. -File dependancies 6. -shell commands 7. -variable assignments 8. -include statements 9. -conditional (loops & comments) 10.

• Extenting a line via \

Visual Studio make Utility

Command devenv.exe make

Compile and Link options

.vcproj Makefile

Dependency.sln has list of projects and dependencies

The root directory Makefile will recursively find other makefiles via the command (MAKE)

Compiler cl.exe gcc, g++, c++ (or any other compiler, even cl.exe)

Linker link.exe ld (or any other linker)

• http://cognitivewaves.wordpress.com/makefiles/

7.6 Java

✔ Java Source → Compiler → Java Byte-Code (object file) → Java Virtual Machine (Interpreter) →Machine Language

✔ Java – Incorporates both compiling and interpreting machine code generation methods◌ Compilation → Java Byte Code (Platform Independant)◌ Java Byte Code → Java Virtual Machine (JVM) → Machine Code◌ JVM can be installed at the hardware (Java Processor), system software (JVM) or application

layer (JVM)▪ Contains 2-Components; JVM Classes / (Compiled Libraries) / Java APIs & Execution Engine▪ See http://www.oracle.com/technetwork/java/embedded/javame/embed-

me/documentation/javame-embedded-apis-2181154.html

✔ Java Technologies See https://www.oracle.com/java/technologies/solutions.html ◌ Java Card◌ Java Cloud Service◌ Java EE Enterprise Edition with HTML5◌ Java Embedded◌ Java ME Embedded Client Micro Edition for small embedded devices.◌ Java ME SDK◌ Java SE Standard Edition◌ Java SE Advanced and Suite◌ Java SE Embedded◌ Java SE Support◌ Java TV◌ Java Wireless Client◌ Jrockit Jave SE + JVM + Profiling, Monitoring and diagnostic tools

✔ Java Virtual Machines (Besides Oracle)◌ http://www.skelmir.com/products ◌ Java Engine Contains algorithms that either compiles or Interprets Byte-Code (Platform independent byte-code → Platform

dependent machine code)▪ Interpretation Interprets source → machine code on each instruction line everytime its executed▪ WAT/AOT Way Ahead of Time / Ahead Of Time Compilation

▫ See http://www.atego.com/▫

▪ JIT Just In Time Compilation ( Interprets source once and stores the native form; allowing redundant code to be executed

Page 94: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

w/o reinterpreting )▫ Variations on the

✔ Java Virtual Machines (Besides Oracle)◌ http://www.skelmir.com/products ◌ Java Engine Contains algorithms that either compiles or Interprets Byte-Code (Platform independent byte-code → Platform

dependent machine code)▪ Interpretation Interprets source → machine code on each instruction line everytime its executed▪ WAT/AOT Way Ahead of Time / Ahead Of Time Compilation

▫ ▫

▪ JIT Just In Time Compilation ( Interprets source once and stores the native form; allowing redundant code to be executed w/o reinterpreting )

▫ Variations on the JIT compiler are referred to as “translators” or “dynamic adaptive compilation (DAC)”▫ Compilation to an “Intermediate Language” (.NET Common Intermediate Language (CIL))▫ See http://connect.smithmicro.com/insignia-device-management

✔ References◌ Java JIT-Compiler http://connect.smithmicro.com/insignia-device-management ◌ A Java AOT-Compiler http://www.atego.com/

7.7 C# ✔ Features of C#

◌ Versioning◌ Generics◌ Delegates◌ Data Types

▪ Value Types – variables that directly contain a value (copies the contained value ie: a=b)▪ Reference Types – variables that contain a pointer to an object but not the object itself.

7.8 VB6 & VBA

✔ VB6 Visual Basic version 6.0 Visual Basic version 6.0 and previous versions did not include a full-featured object-oriented programming nor the .NET framework

✔ VBA Visual Basic for Applications Visual Basic for Applications; Typically for MS-Office applications – Access by using alt-F11 from Word, Access or Excel

To write/read a file: iFileHandler = FreeFile Open <filename> For Output As #iFileHandler Write #iFileHandler <string> Close #iFileHandler

Late Binding: Public Me as Object Me = CreateObject(<Class(name)>) Set Me = ObejctFromSomewhere that is type identified.

Early Binding: Public Me as New <ClassName>

Programming Tips & Debug:DLL will crash Excel w/o debugger if a String() is attempted to be cast to a variantAlways check 0/? In match to prevent crashes, IIF(lTopNum <> 0, lTopNum/lBotNum,0) doesn't work since IIF evaluates both True/False spots.

Determining if the IDE or VBA is being used.A trick to determining if the code is running in a compiled project or within an IDE is by using the Debug.Print command which is ignored when

compiled.Example:

On Error Resume NextDebug.Print 1/0If Err = 0 then msgbox “running in a compiled project.”Else msgbox “running in debugger or vba”End if

Handy Windows APIPrivate Declare Sub Sleep Lib "kernel32" (ByVal lMilliseconds As Long)

Page 95: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

7.8.1 VB(6&A) – Learned Items 1. Dealing with VB6 Data Types

a) ENUM - in classes CAN be shared from a dll to Office Applications

b) TYPE – you can share a type structure defined in VB6 but you CANNOT pass a Type structure variable from the DLL to VBA. • The only way to pass a variable of “Type” is to change it to variant->VBA->back to Type Structure.

c) ARRAYS• Arrays cannot be an optional argument – Use CSV or variant type to pass an optional array.

• To check if an array is initialized use If ((Not Array) = -1) ‘Returns -1 if NOT initialized• Above notation only works on base variable types, UDT (User-Defined Type Arrays will not work)• If an empty string array is cast into a variant the above will not flag correctly;

• Use LenB(Join(VariantArrayName)) = 0 to determine if a String() that is passed as a variant has been initialized.

• Variants received as Non-Array Cannot be Cast to Array (Ex: variant = split(variant)) DOESN’T WORK. • For this a second Variable Dim VariantArray() as ?? need to be setup and only If – Then structure will work • Example; If IsArray(Variant) Then VariantArray = Split(Variant) Else VariantArray = Variant

2. Unexpected differences between Compiled and Debugging VB6

a) Util.Average Throws a ‘Expression Too Complex’ during DLL debugging, but works OK when not debugging. b) If a Function returns a String() then a For Each <Variant> will cause a compiled DLLs to Crash Excel but not during VB6 debugging. c) Never Use On Error Resume Next during a Open FILE operation because EOF() is never reached (endless-loop) with a compiled DLL but

works with VB6 debugger.

3. Using Conditional Compilation Arguments a) Pre-Compilation Options (ie: #IF something THEN) can be set either locally or project globally.

• Local - Use #Const something = <Integer> will apply only to the class/Module.• Be careful since local #Const something = Can be a string BUT global ones can only be integers. (+/- are supported)

• Global - Use VB6 or VBA Menu item Project → Properties “Conditional Compilation Arguments” (Under Make Tab in VB6).• Example; See UseEmulator setting below which will set all #If UseEmulator = 1 Then Statements in all modules and classes. • Multiple items can be assigned by separating them with a (:)

4. Modifying at run time and Importing VBA Code automatically

a) The “CodeModule” of a VBComponent allows a lot of Source Code Control and Code changing.• Example – Item(5) = a module which is found by looping all the vbcomponents .Name property

• ThisWorkbook.VBProject.VBComponents.Item(5).CodeModule.CountOfLines• ThisWorkbook.VBProject.VBComponents.Item(5).CodeModule.Lines(1,10) ‘Dumps lines 1-10 of the module

1.2. Source code to Import from an HTTP location into VBA

Public Function Import(ByVal sModuleName As String) Dim oHTTP As Object, sFirstLine As String, sImportedModName As String, lCnt As Long, bExists As Boolean Dim oNewComponent As VBComponent, sLine As String, sLines() As String, lLineCnt As Long, bInBEGIN As Boolean If LCase$(Left$(sModuleName, 7)) = "http://" Then Set oHTTP = CreateObject("MSXML2.ServerXMLHTTP") Call oHTTP.Open("GET", sModuleName, , "testdevRpt", "p3T)zpko") Call oHTTP.send("")

Page 96: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

sLines = Split(oHTTP.responseText, vbLf) For lLineCnt = 0 To IIf(UBound(sLines) > 30, 30, UBound(sLines)) If Left$(sLines(lLineCnt), 9) = "Attribute" Then '//If Attribute Line check for Module Name If InStr(1, sLines(lLineCnt), "Attribute VB_Name =") > 0 Then sImportedModName = Trim(Replace(Replace(Replace$(sLines(lLineCnt), "Attribute VB_Name = ", ""), """", ""), Chr(13), "")) sLines(lLineCnt) = "" '//Blank out Attribute lines End If If Left$(sLines(lLineCnt), 7) = "VERSION" Then sLines(lLineCnt) = "" If Left$(sLines(lLineCnt), 5) = "BEGIN" Then bInBEGIN = True If bInBEGIN And Left$(sLines(lLineCnt), 3) = "END" Then: bInBEGIN = False: sLines(lLineCnt) = "" If Left$(sLines(lLineCnt), 1) = "'" Then Exit For If bInBEGIN Then sLines(lLineCnt) = "" Next With ThisWorkbook.VBProject.VBComponents For lCnt = 1 To .count If LCase$(Trim(.Item(lCnt).name)) = LCase$(sImportedModName) Then MsgBox "Module '" & sImportedModName & "' already exists in this job." bExists = True End If Next If Not bExists Then Set oNewComponent = ThisWorkbook.VBProject.VBComponents.Add(vbext_ct_StdModule) oNewComponent.name = sImportedModName oNewComponent.name = "Datalog" oNewComponent.CodeModule.AddFromString Join(sLines, vbLf) End If End With End If Set oHTTP = NothingEnd Function

5. Grabbing object from Excel VBA into VB6 automatically (TheHdw & TheExec) without passing the object. a) Note: The VBA call function that returns the object must be a function (ie: It cannot be a property get) If TheHdw Is Nothing Or TheExec Is Nothing Then 'vvv[ Get TheHdw & TheExec Objects from Excel ]vvvvvvvvvv Dim ExApp As Excel.Application Set ExApp = GetObject(, "Excel.Application") Set TheHdw = ExApp.Run("tl_tm_GetTheHdw") Set TheExec = ExApp.Run("tl_tm_GetTheExec") Set ExApp = Nothing '^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^End If

6. Excel crashes when VB6 DLL Module has global names conflict with VBA names a) Its always a good idea to make VB6 modules “Private” to the VB6 Project.

Option ExplicitOption Private Module '//Prevent module clashes with Excel VBA - Keeps Module private to this Project.

7. Notes about VB6 Events (ie: Private WithEvents OBJ as CLS & Public Event Something())

a) Events CANNOT be handled in a Module (Must be contained in classes)• Object that trigger or handles Events must be put into a class.• Objects must be early-binded (late-binding doesn't cause events to trigger)• The class containing the Handling object “Public WithEvents OBJ as CLS” must also contain all Event handlers

• An object with events cannot be passed into a class that handles the events• All object variables must reside in the same class with the event handling subs.

• Event handler subs can objects CAN be Private• Any object variable “WithEvents” cannot be assigned within a TYPE structure.

b) When events don't work (something is out of place) – there is no error trapping/messages available that I know of.

Page 97: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

8. INDUSTRIAL CONTROL SYSTEMS (ICS)✔ ICS includes several types of control systems @ http://en.wikipedia.org/wiki/Industrial_Control_System

◌ SCADA = Supervisory control and data acquisition – Mostly composed of remote terminal units (RTU) across larger areas geographically◌ DCS = Distributed control system – Generally includes a network of PLC controllers◌ PLC = Programmable Logic Controller – Micro-controller device for industrial use

http://en.wikipedia.org/wiki/Programmable_logic_controller ◌ RTU = Remote Terminal Unit – Device control with an interface to DCS or SCADA systems

http://en.wikipedia.org/wiki/Remote_Terminal_Unit

1. Vendors http://www.directindustry.com/cat/automation-A.html

8.1 Allen-Bradley PLC ✔ A Rockwell Automation company http://www.ab.com/en/epub/catalogs/12762/2181376/Table-of-Contents.html

◌ PLC-5 System▪ http://ab.rockwellautomation.com/Programmable-Controllers/PLC-5 ▪ Programming Software = Rockwell RSLogix5

◌ SLC-500 System▪ http://ab.rockwellautomation.com/Programmable-Controllers/SLC-500 ▪ Programming Software = Rockwell RSLogix500

◌ FlexLogix / MicroLogix System (Considered Programmable Automation Controller (PAC))▪ http://ab.rockwellautomation.com/Programmable-Controllers/MicroLogix-Systems▪ Programming Software = Rockwell RSLogix5000

▪ Distributed I/O = Flex I/O

◌ ControlLogix System (Considered Programmable Automation Controller (PAC))▪ Programming Software = Rockwell RSLogix5000

Illustration 6: AB ControlLogix PLC ◌ CompactLogix System

▪ Programming Software = Rockwell RSLogix5000

Illustration 7: AB CompactLogix PLC ◌ SoftLogix System

▪ PC Host Controller Software

◌ Distributed I/O = PLC controls I/O modules in another panel located elsewhere.▪ Flex I/O ( believe PLC → Remote Adapter woks on DeviceNet Communication)▪ Point I/O▪ CompactBlock LDX

1. Communications a) EtherNet/IP

Illustration 3: Allen-Bradley PLC-5 System

Illustration 5: Allen-Bradley SLC-500 System

Illustration 4: AB MicroLogix System

Illustration 8: Allen-Bradley Flex I/O (Distributed I/O Solution)

Page 98: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

b) ControlNet c) DeviceNet d) Universal Remote I/O e) DH+, DH-486 (RS-232)

2. Software (Rockwell Automation) a) RSLogix = Ladder-Logic editor b) RSLinx = Connects RSLogix Programming software to the PLC-Controller c) RSView = Creates operator interfaces / human machine interface (HMI) d) RSNetWorx ???

3. Other Software of Interest a) HMI – Human Machine Interface (ie: Operator interfaces)

• Various Solutions @ http://discover.rockwellautomation.com/IS_EN_Performance_Performance_Visibility.aspx • RSView @ http://www.rockwellautomation.com/rockwellsoftware/performance/view32/overview.page • Wonderware InTouch @ http://software.invensys.com/wonderware/

8.2 Siemens ✔ STEP 7 SIMATIC PLC Series✔ CONFIGURATOR Appears to be related to sharing bits with HMI Software✔ See Also

◌ http://www.pcschematic.com/en/electrical-cad-design-drawing-software/siemens-simatic-plc-et200s-electrical-cad/simatic-et200-plc-configurator.htm

8.3 Omron ✔ Syswin (.swp extension files) Legacy Software For C-Series Omron PLCs✔ CX-Programmer CX-One (demo?) (.cxt or .cxp extension files)✔ WINNT Console connection program✔

8.4 Ladder-Logic on PLC ✔ PLC is programmed using Ladder-Logic which closely resembles wiring of relays

✔ Ladder-Logic comprises of◌ Rungs (horizontal lines span edge-to-edge)◌ Nodes (Internal Input / Output Points “bits”)◌ Inputs ( I:1.0 would be found on the PLC-Controller as ??? )◌ Outputs ( O:2.0 would be ??? on the PLC I/O Rack )

✔ See Also◌ Diagrams here include Ladder-Diagrams and how they relate to Gate Logic Circuits http://www.allaboutcircuits.com/

✔ Vendor Specific Software is Used to Program ladder-logic◌ Allen-Bradley RSLOGIX◌ Omron CXP, SYSWIN (Believe NTWIN is come kind of Omron Table)◌ Siemens STEP 7

8.5 Human Machine Interface (HMI) ✔ HMI(s) could also be called an Operator's Interface Panel

✔ Typically PLC(s) are programmed using Ladder-Logic and often User-Based “control knobs/settings” is offered through a Human Machine Interface (HMI)

◌ Allen-Bradley (Rockwell Software)▪ PanelBuilder Is design software used to program a special embedded system by Allen-Bradley called the Panel▪ RSView Is HMI design software that executes on a standard PC

◌ Invensys Wonderware A Company specifically for HMI Interfaces that supports various PLC Manufacturers out there.▪ IAS Industrial Application Server (by ArchestrA)▪ InTouch HMI development software

◌ Wonderware FactorySuite

Page 99: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

▪ Wonderware System Platform OS specifically for wonderware▫ Appliation Server Executes InTouch Applications (Like Java Engine) – Called StandAlone InTouch▫ Historian▫ Information Server▫ Device Integration Products

✔ See Also◌ https://wonderwarepacwest.com/◌ http://software.invensys.com/wonderware/◌ https://www.youtube.com/watch?v=pGtB7E4jBRc Invensys Wonderware - System Platform for Beginners◌

8.6 Instrumentation 1. Motor Control

a) Starter – Safe starts a large-load motor and protects against under-voltage overload protection b) Contactor – Heavy current relay c) Drives – Sometimes short for VFD or to describe large scale VFD. d) VFD = Variable Frequency Drives – Adjusts AC frequency and voltage to produce motor speed control e) Encoder – Measures motor rotations / speed f) Meger – Hand-Held test equipment to measure wire insulation (Commonly used to find a faulty motor)

2. Valves a) Solenoid Valves = Commonly used device the PLC activates to turn on/off air pressure to devices like pneumatic vales / cylinders

(rams) and etc... b) I/P Transducer = Converts electrical current/voltage to output pressure (I/P= Current → Pneumatic) c) Butter Fly Valve = 90-degree angle pipe valve d) Angle Seat Valve = Common Pneumatic actuated tank outlet valve

3. Sensors ( Transducers ) a) Condition

• Temperature• RTD = Resistance temperature detectors• Thermo-couples• Thermisters

• Pressure• Level• Flow• Speed• HVAC• pH Sensor

b) Proximity• Capacitive( Non-metal detection )• Inductive ( Metal object detection )• Photoelectric (Beam or Reflective)• Ultrasonic ( Reflective Sound – Level of water in tank )

c) Switches• Limit Switches• Safety Interlock switches

d) Flow• EMF – Electromagnetic Flow Meter (ie: MagMeter)• UFM = Ultrasonic Flow Meter

4. Acronyms a) CIP = Cleaning In Place

• An equipment cleaning process that doesn't require tear-down orremoval (Flush/Clean pipes with chemicals)

b) SIP = Sterilization In Place

Illustration 11: PLC Panel with ControlLogix PLC(Top), VFDs(Center) and Starters(Bottom)

Illustration 10: Solenoid Valves

Illustration 9: I/P

Page 100: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

9. NETWORKING✔ IEEE Committees

◌ 802.3 = Ethernet◌ 802.11 / 802.16 / 802.20= Wireless Local Area Networks (WLAN)◌ Cellular

9.1 IT Distributed Management (DMTF) ✔ DMTF = Distributed Management Task Force (IT Enterprise Infrastructure Technology for containing routers, printers, and etc... on a

common network)✔ DMI = Desktop Management Interface✔ MIB = Management Information Base/Database✔ SNMP = Simple Network Management Protocol

The DMTF DMI MIB provides the framework for accessing DMI instrumented information and receiving Desktop Management Interface (DMI) indications through an SNMP/DMI Mapping Agent.

✔ Reference◌ Wiki DMTF @ http://en.wikipedia.org/wiki/Distributed_Management_Task_Force ◌ Wiki MIB @ http://en.wikipedia.org/wiki/Management_information_base ◌ OID Tree @ https://support.ipmonitor.com/mibs_byoidtree.aspx

9.2 Cellular Networking

✔ 1G Networks (1st Generation Networks)◌ Advanced Mobile Phone Service (AMPS)

✔ 2G Networks (Mostly TDMA based)◌ TDMA (Time-division) Multiplexing◌ DAMPS = Digital AMPS – also known as TDMA and can also use first-generation AMPS Service◌ CDMA IS-95 = by Qualcomm◌ GSM = Global System for Mobile Communications standard; The most popular 2G network standard.

▪ 802.11 Access points are Towers

✔ 2.5G Networks (Mostly TDMA based)◌ TDMA (Time-division) Multiplexing◌ Enhanced networks and handsets (GPRS Services and Handsets)◌ Wireless internet applications started (previously text-based)◌ email, calendar, contact lists, instant messaging, still/moving images, job dispatch, remote LAN, and file sharing◌ Vehicle positioning applications

✔ 3G Networks (Mostly CDMA based)◌ CDMA Multiplexing = Code-division multiplexing (All nodes same freq but each has unique “chipping” sequence – Only one device accepts

signal)◌ First attempt at global standard (Third-Generation Partnership Program (3GPP)) – Resulted in 3-different standards

▪ CDMA2000▪ Wide-band CDMA (WCDMA)▪ Europe used Universal Mobile Telecommunications Systems (UMTS)▪ Enhanced Data Rates for Global Evolution (EDGE)▪ International Mobile Telecommunication-2000 (IMT-2000) standard was approved by International Telecommunication Union (ITU)

◌ Features

Page 101: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

▪ High (144Kbps), Full (384 Kbps), and Limited (2 Mbps) mobility bandwidth▪ QoS (IP-based) support from end-to-end

✔ 4G Networks◌ FDMA (Frequency-division) Multiplexing

✔ Reference◌ Cellular Network Standards @ Wiki http://en.wikipedia.org/wiki/Template:Cellular_network_standards ◌ Links

Bluetooth www.bluetooth.com

CDMA Development Group (CDG) www.cdg.org

ETSI, for HIPERLAN/2 specifications www.etsi.org

IEEE 802.15 www.ieee802.org/15/

IEEE 802.11 www.ieee802.org/11/;www.standards.ieee.org

Infrared Data Association (IrDA) www.irda.org

International Mobile Telecommunication-2000 (IMT-2000) www.imt-2000.org

International Telecommunications Union www.itu.int/home/index.html Mobitex Operator Information www.mobitex.org

QUALCOMM CDMA www.qualcomm.com/cdma/index.html

Third-Generation Partnership Project (3GPP) www.3gpp.org

Third-Generation Partnership Project 2 (3GPP2) www.3gpp2.org

3G Americas www.3gamericas.com

3G information www.3g.co.uk

Universal Mobile Telecommunications System (UMTS) www.umts-forum.org

Wi-Fi Alliance www.wi-fi.org

9.3 Area Networking (LAN/WAN) ✔ Overview

◌ Network Architectures▪ Peer-to-peer No centralized area of control▪ Client/Server Centralized control device (Server)▪ Hybrid Both Peer-to-peer and Server/Client Architectures

◌ Network Topology Is the physical arrangement of connected devices and connection medium (e.g. Cable, Wireless) and distance between devices

◌ Internetwork = 2+ Networks (ie: LANs) connected together via a Router and configured to use logical addressing (IPv4 or Ipv6)◌ Segmentation = Internetworks are divided into network segments (Logically[IP] and Physically[MAC]) for better performance (See IP

about network segmentation)

✔ Service Industry Terminology◌ SAP / Demarc = Service Access Point / Demarcation Point – Service Providers connection point to CPE begins◌ CPE = Customer Premises equipment – Leased equipment from service provider at customers site◌ DTE = Data Terminal Equipment – Customer-Site equipment (e.g. modem, hosts, printers, etc...)◌ DCE = Data Communication Equipment – Equipment of the Internetwork (e.g. Routers, Switches, etc...)

▪ CSU – Channel Service Unit▪ DSU – Data Service Unit

◌ M2M = Machine to Machine◌ NMS = Network management stations◌ IoT = Internet of Things◌ CO / POP = Central Office / Point of Presence – Customer network to providers network◌ Local Loop = Closest CO → Demarc◌ Toll Network = Trunk line in providers network◌ MTU = Maximum Transmission Unit

◌ Domain = Collection of networks under common administration and sharing a common routingstrategy

◌ AS = Autonomous System (ie: Domain)◌ ES = End System – Does not preform routing or forwarding (e.g. Printers,

Workstations, Servers)◌ IS = Intermediate System – Preforms routing or forwarding (e.g. Routers and Switches)

Illustration 12: Internetwork - Various networks connected together

Page 102: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

▪ Intradomain IS = Communicates only within the domain▪ Interdomain IS = Communicates within and “between” domains

✔ Network Category Naming◌ LAN = Local Area Network – typically Owned by a company / person

▫ Ethernet▫ Token Ring

◌ WAN = Wide Area Networks – typically Leased networks by a service provider▫ Frame Relay▫ High-Speed Serial Interface▫ Integrated Services Digital Network▫ Point-to-Point Protocol▫ Switched Multimegabit Data Service▫ Synchronous Data Link Control and Derivatives▫ X.25▫ Digital Subscriber Line (DSL)

◌ WPAN = Wireless Personal Area Network▫ IrDA (Infrared Data Association)▫ Bluetooth▫ IEEE 802.15

◌ WLAN = Wireless Local Area Networks▫ WiFI = IEEE 802.11 Wireless LAN

▫ 802.15 (1Mbps)▫ 802.11 a/g (54Mbps)▫ 802.11b (5-11 Mbps)

◌ WWAN = Wireless Wide Area Network (Mid to Long Range / Cellular Standards (Outdoor Networks))◌ WMAN = Wireless Metropolitan Area Networks

◌ VPN = Virtual Private Networks – allows private networking across the Internet medium▫ Remote Access = Telecommuters access to corporate network▫ Site-to-Site = Connection to backbone over public internet instead of using WAN or Frame Relay▫ Extranet = B2B (Business to Business) limited access to a corporate network

◌ VLAN = Virtual Local Area Network – Reserving a set of Switch Ports for an entirely independent network segment▫ Allows switches to break up broadcast domains (Usually done by routers)▫ A router must be connected between VLAN networks to obtain cross network communication▫ VTP = VLAN Trunk Protocol

◌ Ad-hoc = No Base Router – Node to Node connection (e.g. Only a Crossover Cable / Hub )

✔ Network Device Categories◌ Residential = Personal/Home◌ Small Office Home Office (SOHO) = Routers in this category come equipped with Internal Switch / Firewalls / DHCP / DNS / etc.. services◌ Enterprise = Has to work all the time with limited features (Routers are simplistic)

✔ Network Devices◌ NIC = Network Interface Card; Supplies host with network physical plug-in (e.g. Ethernet Card in a PC-Host)◌ Hub = (ie: Multiport Repeater) – All-Ports on single Collision Domain – All-Ports on single broadcast domain◌ Gateway = Access port to external mainframe / network (Broadcast Domain) sometimes used equivalently with “Router”◌ Switch = (ie: Multiport Bridge) – Per-Port Collision Domain – All-Ports on single broadcast domain; Unless VLAN(s)

exist▪ Data-Link Layer-2 Device – Locates and tracks devices per-port using a Physical MAC-Address▪ Trunk Port (ie: GBIC/Daisy Chain/Uplink Port) – If a device isn't on the local switch the “trunk port” will search an outside-other

connected switch for the device

▪ UN-Managed Switch = No Console; All configurations are done automatically▫ No QoS/CoS Configuration – Quality/Class of Service – Prioritizes packets (e.g. VoIP then Video then File Transfer)▫ No routing-loop trapping – Where a slave switch is not plugged into the trunk-port causing a endless communication

loop

▪ Managed Switch = Console Configurable / Hard-code settings are possible▫ Speed (10Mbps, 100Mbps, 1Gbps ) – Back-Plane Speed rating is the total cross-talk speed of all ports together (ie: Main-board

Illustration 13: Network Devices

Page 103: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

connecting all ports)▫ Duplexing (Half/Full – Duplex) – Legacy Half-Duplex supports “talk -OR- listen” whereas Full-Duplex supports “talk -AND-

listen” at the same time.▫ VLAN (Port-Group Networks) – Only available on Managed Switches; Group ports are entirely separated and cannot

communicate with each other

◌ Router▪ Network Layer-3 Device – Per-Port Broadcast & Collision Domain using logical addressing (Sometimes refereed to as a Layer-3

Switch)▪ Maps & Connects together – WAN(s) using a serial interface like V.35 physical interface / LAN(s) / VLAN(s) / Sub-nets (Doesn't

care about hosts; Just networks)▫ Routing Table Map

▫ Network Address – Device address in various addressing protocols / Ipv4, Ipv6, IPX, etc...▫ Interface – Exit interface packet will take when destined for a specific network▫ Metric – Physical distance to remote network

▫ Routing Table Data Gathering▫ Static Routing = Administrator hand-types the routing table▫ Dynamic Routing = Routers update each other through the network

▫ Preforms▫ Packet Switching – by means of logical addresses (IPv4 and IPv6)▫ Packet Filtering – by means of an access list▫ Internetwork Communication▫ Path Selection – by means of a routing table ( map of the Internetwork )

✔ Communication Basics◌ Device Addressing = Scheme used to identify a network device

▪ Logical – Typically; IP-Address (IPv4 or IPv6 )▪ Physical – Typically; MAC-Address

◌ Collision Domains = Parallel connected devices all receiving the same line signal; only one device can communicate at a time; Destination NIC filters the traffic

▪ Hub – All-ports are on the same Collision Domain▪ Switch – Per-port Collision Domain (Layer-2)▪ Router – Per-port Collision Domain (Layer-2)▪ Private Collision Domain= One host per Port (Private within the plug/port)

◌ Broadcast Domains = Group of devices that all receive the “Broadcast signals” (ie: Signals sent to IP - ###.###.###.255 or MAC xx:xx:xx:ff on a Class C Network)

▪ Hub – All ports are on the same Broadcast Domain▪ Switch – All ports are on the same Broadcast Domain▪ Router – Per-port Broadcast Domain (Layer-3)

◌ Domain Networks use the Domain Name Service (DNS) to obtain destination MAC address

◌ MS-Windows also allows a generic Data-Link Broadcast (ie: IP - ### . ### . ### . 255 , MAC ff:ff:ff:ff ) for Host Name to MAC address resolution

▪ Source Device Sends: Src: 192.168.0.2 - Dst: 192.168.0.255(ie: Data-Link Broadcasting Address) - Protocol: NBNS - Info: Name Query NB<DstHost><00>

▪ Destination Response: EthernetII,Src:192.168.0.2(00:14:22:be:18:3b),Dst:Broadcast(ff:ff:=ff:ff:ff:ff)▪ Source Device Sends: Src: 192.168.0.2 - Dst: 192.168.0.255 - Protocol: ARP - Info: Who has 192.168.0.37 Tell 192.168.0.2▪ Destination Response: Src: 192.168.0.3 – Dst: 192.168.0.2 – Protocol: ARP – Info: 192.168.0.3 is at 00:db:db:99:d3:5e▪ Destination Response: Src: 192.168.0.3 – Dst: 192.168.0.2 – Protocol: NBNS – Info: Name query response NB 192.168.0.3

◌ Communication Types▪ Layer-2/Hardware Broadcasts = Using MAC Wild-Card (ff) to address all nodes on a LAN ( Broadcast doesn't go past any routers / LAN

only )▪ Layer-3 Broadcasts = Using IP Wild-Card (255) to signal all nodes on a LAN▪ Unicast = Single destination host (e.g. DHCP)▪ Multicast = Single source → many devices on different networks (Subscribed in a group address list )

✔ Reference◌ Cisco Wiki @ http://docwiki.cisco.com/wiki/Main_Page

9.3.1 OSI Protocol Model✔ OSI Model = Open Systems Interconnection Communications Model (7 – layers)✔ PDU = Protocol Data Unit – General term describing a protocol attachment (ie: In the process of wrapping and encapsulation

Page 104: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

protocols)

✔ Protocol = Formal rules of behavior/Standards that define precisely the data communication methods/rules

◌ Protocol Categories▪ Interconnection – (ie: Router/Switch Protocols) Handle data transfers and routing from point to point▪ LAN Protocols▪ WAN Protocols▪ Network Protocols – Various upper-level (ie: Application) protocols that exist in a “Protocol Suite”

◌ Protocol Documentation▪ IANA – Internet Assigned Numbers Authority – Group that carries many of the protocols and standards used on the Internet▪ IETF – Internet Engineering Task Force – The group that creates Internet protocols and standards published as RFC(s)▪ RFC – Request for Comments – Documentation scheme used to document a technology and/or standards

▫ FYI = For Your Information – An RFC that is for Information▫ BCP = Best Current Practices – An RFC describing a Best practice▫ STD = Standards – An RFC Numbered separately and used for describing an Internet Protocol

◦ TS = Technical Specification – A STD RFC that defines the protocol; Progressively staged as 1st Proposed, 2nd Draft, then 3rd Internet Standard.

◦ AS = Applicability Statement – A STD RFC Document that describes when the protocol is to be used (e.g. Required, Recommended, Elective )

✔ Reference◌ Wiki List of Network Protocols (OSI model ) http://en.wikipedia.org/wiki/List_of_network_protocols_%28OSI_model%29

A. Application Layer-7 (HTTP/POP3)✔ Software implemented (e.g. Firefox, Outlook, Chrome, etc....)✔ TCP/UDP Port Numbers that define the application protocol

▪ Virtual Port Numbers = TCP/UDP:Port# ( 0-1023 reserved ); like virtual mail-boxes for Application protocol specific delivery; Used by the Transport Protocols

▫ Socket = IP : Port# (e.g. 192.168.10.20:80) Created for each communication task▫ Socket Pair = Includes the “Socket” identifier of both source and destination requiring at least one unique item per

communication task▫ Registered Ports – At http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml▫ System Specific – View C:\Windows\System32\Drivers\Etc\SERVICES

▪ Common Ports to Know▫ 21 = FTP (TCP) – File Transfer Protocol▫ 23 = Telnet (TCP) – Telnet Protocol▫ 25 = SMTP (TCP) – Simple Mail Transfer Protocol▫ 53 = DNS (TCP/UDP) – Domain Name Service Protocol▫ 69 = TFTP (UDP) – Trivial File Transfer Protocol (Allows remote file boot-up / OS )▫ 70 = Gopher(TCP/UDP)▫ 79 = Finger (TCP/UDP) – RFC4146▫ 80 = HTTP (TCP) – World Wide Web▫ 110 = POP3 (TCP/UDP) – Post Office Protocol V3▫ 119 = NNTP – Network News Transfer Protocol▫ 161 = SNMP (UDP) – Simple Network Management Protocol▫ 389 = LDAP (TCP/UDP) – Lightweight Directory Access Protocol▫ 443 = HTTPS (TCP) – Secure WWW▫ 993 = IMAP4 – Interactive Mail Access Protocol▫ 5353 = MDNS (TCP/UDP) – Multicast DNS Responder IPC (DNS has many flavors)

B. Presentation (Layer-6)✔ Presentation Layer = Manages a “common” data representation method between systems for communication data translation (OS-

Layer)▪ Big / Little Endian – Negotiates the Byte Order between systems

Illustration 14: OSI Model

Page 105: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

▪ Encryption – Enables encrypted data to be deciphered at the destination▪ Compression – Enables data compressed at the source to be DE-compressed at the destination▪ Text / Data – Negotiates common character sets (ie: US-ASCII, EBCDIC)▪ Video – Like QuickTime, Motion Picture Experts Group (MPEG)▪ Graphics – Graphics Interchange Format (GIF), Joint Photographic Experts Group (JPEG), Tagged Image File Format

(TIFF)✔ Protocols

▪ NVT = Network Virtual Terminal (Subset of the Telnet Specification)▪ IBM NetBIOS▪ XDR = Sun's External Data Representation▪ DCE RPC = Distributed Computing Environment's Remote Procedure Call

C. Session (Layer-5)✔ Session Layer = Establishes, Manages, and Terminates Communication Sessions between two systems (ie: Service Requests /

Service Responses) per application▪ ZIP = Zone Information Protocol▪ AppleTalk = Coordinates the name binding process▪ SCP = Session Control Protocol▪ DECnet Phase IV = ??

✔ Duplexing Control▪ Simplex▪ Half Duplex = Hubs – 10Mbps / 10BaseT ; Uses one set of wires ( Send -or- Receive )▪ Full Duplex = Switch / Crossover Cable – 100Mbps; Uses two sets of wires ( Send -and- Receive ) ; No collisions

D. Transport Layer-4 (TCP/UDP – Data Segment)✔ Provides = Transport Header + Data (ie: Segment) → Network Layer-3

▪ Segmentation▪ Sequencing▪ Virtual circuits▪ Data Integrity

▫ Connection-less Network Service = No flow control, CRC or ACK▫ Connection-Oriented = Uses Handshaking, sequencing, acknowledgment and Flow Control

✔ Buffering✔ Windowing = A window is the quantity in bytes the transmitter can send without receiving an ACK (TCP/IP

allows 1 or 3 bytes per ACK)✔ Congestion Avoidance

▪ QoS/CoS = Quality/Class of Service – Packet Prioritizing; VoIP/Video first then file transfer

✔ Protocols▪ User Data-gram Protocol (UDP) = No reliability; Used occasionally for a status update broadcast (like printer toner

low)▪ Transmission Control Protocol (TCP) = Uses Sequencing, ACK, and Windowing flow control for reliability▪ Resource Reservation Protocol (RSVP)

E. Network Layer-3 (IP – Packet Data)✔ Provides Logical (e.g. IP) network device addressing and routing (ie: Routers / Data & Routing Information)✔ Interconnection Protocols

▫ IP = Internet Protocol – Routed Protocol; Logical addressing and physical location for path determination – IP address

▫ ICMP = Internet Control Message Protocol – Runs on top of IP ( Generally generated by Routers; I think ); ICMP Echo is commonly named “Ping”

▫ ARP = Address Resolution Protocol – IP → MAC Address resolution (Doesn't use IP Transport)▫ RARP = Reverse Address Resolution Protocol – MAC → IP Address resolution▫ Proxy ARP = Allows Hot swap-able router additions – See also Cisco Host Standby Router Protocol (HSRP)

Page 106: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

✔ Routing Protocols = Used to build / maintain routing tables▫ RIP = Routing Information Protocol▫ EIGRP = Enhanced Interior Gateway Routing Protocol▫ OSPF = Open Shortest Path First

✔ Other Protocols▫ IPX = Legacy Novell IP-Technology that causes a lot of chatter▫ MPLS = Multiprotocol Label Switching ( Faster than a routing table )

E.1 Internet Protocol (IP)

✔ IP Octet / Versions▪ IPv4 = Addresses network devices using 4 – octets/bytes ( e.g. 192.168.10.20 )▪ IPv6 = Addresses network devices using 6 – octets/bytes ( e.g. 192.168.30.20.10.1 )

✔ IP-Class Schemes = An IP-Address has various schemes (ie: IP-Class) that is identified by it's first octet range▪ Class A = 0 → 127 Prefix “0” Subnets CIDR /8 → /15▪ Class B = 128 → 191Prefix “10” Subnets CIDR /16 → /23▪ Class C = 192 → 223Prefix “110” Subnets CIDR /24 → /30 (2-bits for hosts are required)▪ Class D = 224 → 239Multi-cast▪ Class E = 240 → 255Scientific

** e.g. “192.168.0.1” is a “Class C” IP which means its on Network (ie: LAN) “192.168.0” host “1”

✔ Wild-Card (0) = Typically used to address an entire Network (e.g. Class A: 10.0.0.0, Class B: 172.16.0.0, Class C: 192.168.10.0)▪ 0.0.0.0 – Default route or any network▪ 1.1.1.1 – All 1s Broadcast / Limited broadcast; reacts same as 255.255.255.255▪ 0.0.16.23 – “This(0)” network where network bytes are (0)▪ 1.1.16.23 – “All(1)” networks node 16.23▪ 127.0.0.1 – Loop-back (local node)

✔ Wild-Card (255) = Wild-card for a “Broadcast Signal”▪ 255.255.255.255 – Broadcast signal destined for → All networks; All nodes▪ 172.16.255.255 – Broadcast signal destined for → All Subnets and hosts on network

“172.16”.<xxx . xxx>

✔ Private IP = Addresses for local network only ( Not routable )▪ NAT = Network Address Translation – Converts Private IP to a routable one

▫ Static NAT = One to one mapping between local and global addresses▫ Dynamic NAT = Map unregistered IP addresses to registered IP(s)▫ PAT (ie: NAT Overloading) = Port Address Translation – Most popular; Maps multiple unregistered IP-Addresses to

a single registered IP-Address

✔ Tunneling Protocols for VPN(s)▪ L2F = Layer 2 Forwarding – By Cisco; Used in Virtual Private Dial-Up Networks (VPDN) proceeded by L2TP

which is compatible with L2F▪ PPTP = Point-to-Point Tunneling Protocol – By Microsoft; data transfer from remote networks to corporate networks▪ L2TP = Layer 2 Tunneling Protocol – By Cisco & Microsoft; Replacement of L2F & PPTP (Merging the two)▪ GRE = Generic Routing Encapsulation – By Cisco; Create point to point links that allow variety of protocol encapsulation

in the IP tunnel.▪ IPSec = IP Secure Transfer – A standard set of protocols for authentication & encryption services (IP-based

only; Others require GRE tunnel then IPSec)▫ AH = Authentication Header – Authentication is part of each data packet▫ ESP = Encapsulating Security Payload – Integrity check on the data packet

✔ All IP-Network Protocols are wrapped within an IP Header▪ ICMP = 1 Management and Messaging for IP ( Network status messaging including Buffer-full, Hops, Ping, Trace-route

(ie: >tracert )▪ IP in IP = 4 IP Tunneling▪ TCP = 6▪ IGRP = 9▪ UDP = 17▪ EIGRP = 88▪ OSPF = 89▪ Ipv6 = 41▪ GRE = 47▪ L2TP = 115 Layer 2 Tunneling Protocol

Page 107: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

▪ Complete List @ http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml

E.2 Subnet

✔ Subnet is the bit-wise masking of the IP-Address's “host portion” which divides IP-Addresses into separate LAN(s)▪ Types

▫ Classful = All nodes use the same subnet mask – Protocols RIPv1 and IGRP are Classful Only Routing protocols▫ Classless (VLSM) = Variable Length Subnet Masks – Protocols RIPv2, EIGRP and OSPF contains the subnet mask for each

router interface)

▪ CIDR = Classless Inter-Domain Routing▫ Syntax: “<IP>/#” = Where “#” is the number of 1s in the IP-Address mask Left → Right▫ Class C Network /25 Example

✔ Mask 1111-1111 . 1111-1111 . 1111-1111 . 1000-0000 . 0000-0000 Dec 255.255.255.128.0 CIDR255.255.255.128/25 ^-- Subnet bit differentiates the (2) Class C Subnet

✔ Subnet(0) Start: 192.168.10.1 → 192.168.126 Broadcast IP: 192.168.127✔ Subnet(128) Start: 192.168.10.129 → 192.168.10.254 Broadcast IP: 192.168.10.255

▫ Class C Network /26 Example✔ Mask 1111-1111 . 1111-1111 . 1111-1111 . 1100-0000 . 0000-0000 Dec 255.255.255.192 CIDR

255.255.255.192/26 ^^-- Subnet Bit differentiates the (4) Class C Subnet✔ Subnet(0) Start: 192.168.10.1 → 192.168.10.62 Broadcast IP: 192.168.10.63✔ Subnet(64) Start: 192.168.10.65 → 192.168.10.126 Broadcast IP: 192.168.10.127✔ Subnet(128) Start: 192.168.10.129 → 192.168.10.190 Broadcast IP: 192.168.10.191✔ Subnet(192) Start: 192.168.10.193 → 192.168.10.254 Broadcast IP: 192.168.10.255

▫ Subnetting /30 is good for WAN that have 2-Gateways since the two will be on their own network

F. Data-Link Layer-2 (MAC – Frame Data)✔ Data-Link Layer = Provides Framing and placing data on medium (Switches are Layer-2 Devices)

▪ Physical Addressing – MAC Address▪ Network Topology – Defines how devices are to be physically connected (ie: Bus/Ring topology)▪ Error Notification – Alerts upper-layer protocols of Data-Link layer errors▪ Frame Sequencing – Numerically orders frames so they can be reordered correctly▪ Flow Control – LLC Support services that moderates and keeps in-sync communication between the two devices

✔ Sub-Layers (Divided by IEEE)▪ LLC = Logical Link Control – Supports TCP/UDP Port protocols at the data-link layer (see IEEE 802.2 Spec)▪ MAC = Media Access Control – Provides protocol access to the physical network medium.

▪ MAC Frame = Bits → Bytes → Frames – Packets from the Network layer become a MAC Frame with CRC 802.3 frames or Ethernetframes

Ethernet II Preamble8-bytes

SFD DA6-bytes

SA6-bytes

Type2-bytes

Data?

FCS4-bytes

802.3 Ethernet Preamble8-bytes

SFD DA6-bytes

SA6-bytes

Length2-bytes

Data?

FCS?

▫ Preamble✔ SFD/Sync = Start Frame Delimiter

▫ DA = Destination Address – ff:ff:ff:ff:ff:ff:ff address is a “Ethernet Broadcast” going out to all devices▫ SA = Source Address

✔ Length (802.3) = Must be used with a proprietary LAN (e.g. IPX)✔ Type (Eth II) = Network layer protocol type (0x800 = IPv4, 0x86DD = IPv6 )

▫ Data= Packet data (64 to 1500 bytes)▫ FCS = Frame Check Sequence (CRC)

▪ Frame Data = Bits of Data containing all other OSI layers▪ MAC (ie: Hardware) = Media Access Control address (e.g. F1:F2:F3:|F4:F5:F6| )

▫ bit 47 - I/G = Individual -or- Group – 0 = Address is a device MAC address 1 = Address is a broadcast or multicast address

▫ bit 46 - G/L = Global/Universal -or- Local – 0 = Globally administered address 1 = Locally governed administered address (DECnet)

▫ 45-24 - OUI = Organization Unique Identifier – 3-bytes assigned by IEEE▫ 23-0 Device = Lower 24-bits is manufacturer assigned device code locally administered (often the same 6 hex digits are the

end of the serial number)▫ MAC addresses never go through a router (LAN access only)

▪ MAC Address (Hardware static) = Hardware Address▫ Name Resolution (Host Name to IP Address resolution)

Page 108: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

✔ Domain Name Service (DNS) Resolution✔ MS-Windows Networking (W/O DNS) Just

✔ Router Connected = IP-Address 192.168.0.255 MAC-Address (Data link layer broadcast) ff:ff:ff:ff:ff:ff✔ Beginning of MAC Address is Manufacturer and Serial Number on the end.✔ MAC address spoofing?

✔ Routing Protocols▫ STP = Spanning Tree Protocol– Used to stop network loops from occurring▫ Spanning Tree Protocol – UN-Managed doesn't have routing loop prevention (When two switches are connected

together using non-Trunk ports)✔ Allows switches to talk to each other and route packet fastest way from A → B✔ Prevents routing loops

✔ WAN Protocols▪ Typical Serial Interface Protocols

▫ HDLC = High-Level Data-Link Control Protocol – ISO-standard encapsulation method for data on synchronous serial links (Point-to-Point Protocol)

▫ PPP = Sets up point to point links for carrying HDLC – Used on asynchronous (dial-up) or synchronous (ISDN) serial media✔ LCP = Link Control Protocol – Method of establishing, configuring and terminating P2P connections✔ NCP = Network Control Protocol – Establishing/Configuring multiple network layer protocols (routed

protocols) on a P2P connection∙ IPCP = Internet Protocol Control Protocol∙ IPXCP = Internetwork Packet Exchange Control Protocol

▪ Frame Relay – Data-Link/Physical Protocol; successor to X.25; Provides dynamic bandwidth andcongestion control

▫ Classified as a Non-Broadcast Multi-Access (NBMA) Network; Doesn't send any broadcasts likeRIP updates

▫ Roots of X.25; It is a Leased-Line network (but not a HDLC/PPP network) – TELCO Network▫ Is a Packet-Switched technology (ie: Splits one communication path into multiple paths / inputs to

routers)▫ CIR = Committed Information Rate – Guaranteed maximum bandwidth▫ Packet Encapsulation

✔ Cisco = Used if both devices connected are Cisco devices✔ IETF = Internet Engineering Task Force

▫ Creates Virtual Circuits✔ Permanent Virtual Circuits (PVC) = Static mapping

∙ Identified to DTE end devices by Data Link Connection Identifiers (DLCI)∙ IARP= Inverse ARP is used to map DLCI to an IP Address in Frame Relay Networks∙ LMI = Local Management Interface – Signaling standard between router and first Frame Relay switch

✔ Switched Virtual Circuits (SVC) = Like a phone call – only established when data needs transferred (for Private usage)

▪ Others▫ ISDN = Integrated Services Digital Network – Voice + Data over existing phone lines up to T1▫ LAPB = Link Access Procedure, Balanced▫ LAPD = Link Access Procedure, D-Channel – Used with ISDN as D-Channel access▫ HDLC = High-level Data Link Control – HDLC is manufacturer proprietary▫ PPPoE = Encapsulates PPP frames into Ethernet Frames for ADSL services

✔ Convergence = Using Ethernet for irregular purposes ( other than file transfer )▪ PoE – Power over Ethernet ( Device power carried on Ethernet; Standards versions V1, V2, V3 )▪ VoIP – Voice over IP

G. Physical Layer-1 (PHY – Bit Data)✔ Medium = Physical transmission tools used to deliver information or data (ie: Cabling / Voltage / etc...)

▪ FDDI = Fiber Distributed Data Interface▪ Ethernet = [ IEEE 802.3 ]▪ Token Ring = [ IEEE 802.5 ]

✔ Protocols▪ Ethernet Protocol [ 802.3 ]

✔ Cabling▪ Networking Cables

▫ RJ45 Connector is used in Twisted pair cables▫ Straight-Through = Cable is used for host/device to hub/switch/router

Page 109: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

▫ Crossover Cable = is used for no network device PC to PC networking▫ Rolled Cable = Fancy word for an RS-232 Cat5 cable used for Network equipment's Terminal Emulation

▪ Service Access Point (SAP) cable ending standards▫ EIA/TIA-232 or TIA-449▫ V.35 = For CSU/DSU connection points▫ EIA-530▫ HSSI = High Speed Serial Interface

G.1 WAN Physical Layer

✔ Terms▪ HSSI = High Speed Serial Interface▪ CATV = Cable TV lines; Coaxial Cable; HFC Network

✔ DSL = Digital Subscribe Line▪ Symmetrical DSL = Up/Download speeds the same▪ Asymmetrical DSL = Different Up/Download Speeds▪ ADSL = ?? (Carries voice/data together)▪ HDSL = High-bit-rate DSL▪ RADSL = Rate Adaptive DSL▪ SDSL = Synchronous DSL (data only)▪ IDSL = ISDN DSL (data only)▪ VDSL = Very-high-data-rate DSL (Carries voice/data together)▪ LRE = Cisco's Long Range Ethernet (Employs VDSL)

✔ MPLS = Multiprotocol Label Switching✔ ATM = Asynchronous Transfer Mode ( Protocol used for DSL )

✔ Speeds▪ 64Kbps▪ 1.544Mbps(T1)▪ 4.5Mbps(T3)

✔ Wireless Local Area Networks (WLAN)

▪ 802.11 Wireless specification is like hub Ethernet; Uses Half-Duplex over Radio Frequency (RF)▫ 802.11b ( Released ? - 2.4GHz )

✔ Rate Shifting 1, 2, 5.5 and 11Mbps depending on signal integrity✔ CSMA/CA = Carrier Sense Multiple Access w/ Collision Avoidance using Request-To-Send (RTS) and Clear-To-Send

(CTS)✔ CSMA/CD = Carrier Sense Multiple Access with Collision Detection✔ Modulation via Direct Sequence Spread Spectrum (DSSS)

▫ 802.11g ( Released 2003 – 2.4GHz , 54 Mbps )✔ 802.11b compatible (DSSS Modulation) but delivers 54Mbps on OFDM Access Points (AP)✔ Modulation by Orthogonal Frequency Division Multiplexing (OFDM)

▫ 802.11h✔ Adds Multiple Input Multiple Output (MIMO) providing 250Mbps.

▫ 802.11a ( Released 1999 – 5GHz , 54Mbps )✔ Originally very expensive✔ Rate Shifts of 6, 9, 12, 18, 24, 36, 48 and 54Mbps✔ Extended as 802.11h adding Transmit Power Control (TPC) (For battery conservation) and Dynamic Frequency

Selection (DFS)

▪ Cisco Unified Wireless Solution▫ WMAN = Wireless Metropolitan Area Networks

▪ FCC Released Frequencies for Public Use▫ 900MHz – Referred to as the Industrial, Scientific, and Medical (ISM Band)▫ 2.4GHz – Also Referred to as the Industrial, Scientific, and Medical (ISM Band) – 802.11b/g/n▫ 5.7GHz – Referred to as the Unlicensed National Information Infrastructure (UNII Band) – 802.11a/h

9.4 Reference / Tools ✔ Emulation Software

◌ NetSim @ http://netsimk.com/ ◌ Cisco Console @ http://www.ciscoconsole.com/free-cisco-lab-simulators.html

✔ Wikipedia◌ Overlay Network @ http://en.wikipedia.org/wiki/Overlay_network ◌ Failover = Switching to redundant or standby servers @ http://en.wikipedia.org/wiki/Failover

Page 110: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

✔ IANA = Internet Assigned Numbers Authority @ http://www.iana.org ◌ RFC = Request For Comments◌ TCP/UDP Reserved Ports @ http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml

9.5 Cisco Systems ✔ Cisco Hierarchy Model

◌ Core Layer = No tables just fast switching (FDDI, Fast Ethernet, ATM)◌ Distribution Layer = Routers (ie: Workgroup Layer), Routing, Filtering, WAN Access and Core Bridge◌ Access Layer = (ie: Desktop Layer) Switches / Hosts

✔ IOS = Cisco's Internetworking Operating System – A Cisco OS Kernel for Routers / Switches✔ SDM = Cisco's Security Device Manager – Configuration by web interface (EWI = Embedded Web Interface)

✔ CLI = Command Line Interface – CLI Session also called an EXEC session.◌ Aux Port – Terminal access via Callable Telephone Modem (ie: out-of-band)◌ Ethernet – Terminal access via Ethernet (ie: In-band)◌ Serial Port – Terminal access via a serial RJ45

>ip subnet-zeroClass C you get subnets 0, 64, 128 and 192

10. RESOURCES 1. EDA.org http://www.eda.org/

a) 2. Electronic Circuits http://www.electronics-circuits.com/index.html

a) Circuit tutorials b) Circuit exampels (DIY) c) EDA Links and Resources

3. Free IP-Cores a) http://www.freemodelfoundry.com/ b) http://opencores.org/

4. Generic Acronyms & Terminology a) EMI – Electromagnetic interference b) Legacy Products Processors

• 1st Microprocessor was the Intel 4004• TI 99/4A was 16-bit; TMS9900 @ 3MHz• Commodore-64 was 8-bit; MOS-Technology 6510 @ 1MHz• TRS-80 Color Computer 2 was 8-bit; Motorola MC6809E @ 1MHz• Tandy 1000TL; was 16-bit 80286 @ 8MHz ( Tandy -> AST -> Samsung )• 8086(16-bit) / 8088(Is an 8086 with an 8-bit data bus for reverse compatibility)

10.1 Engineering Models ✔ Big Bang Model No planning or processes in place before and during the development of a system✔ Code & Fix Product requirements are defined by no formal processes are in place before the start of development✔ Waterfall Process for developing in steps where the results of one step flow into the next step✔ Spiral Process for developing in steps and throughout various steps – feedback is obtained and re-incorporated into the process

(Open Waterfall).

✔ Embedded System Design & Development Cycle◌ Phases

▪ Creating the architecture (Block Diagram of Interacting Elements)▫ Stages

▫ 1 – Strong Technical Foundation Research methodologies and standards in the market segment▫ 2 – Understand the Architectural Business Cycle▫ 3 – Define Architectural patterns and models▫ 4 – Define Architectural structures▫ 5 – Document the Architecture

∙ Block Diagrams Overview of major components✔ Central Processing Unit (CPU) Blocks✔ Memory Blocks✔ Input Device Blocks✔ Output Device Blocks✔ Bus Pathways Showing interconnects for data travel and bus control

∙ Schematics Circuit components (ie: Symbols) and connections∙ Wiring Diagrams Physical Layout of a PCB board showing Buses and connection between components

Page 111: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

∙ Logic Diagrams Depicts logic (AND, OR, NOT, XOR) of a circuit∙ Timing Diagrams Timing graphs of I/O signals of a circuit

▫ 6 – Analyze and review the Architecture▫ Primary architecture tool

▫ Application Software Layer▫ System Software Layer▫ Hardware Layer

▪ implementing the architecture▪ testing the system▪ maintaining the system

10.2 Market Segments

Embedded Systems often fall within an “Embedded Market Segment”✔ Consumer Electronics PDAs, TVs, Games, Toys, Home Appliances, Internet Applications✔ Medical Devices used to diagnose and treat humans✔ Industrial Automation and Controls Sensors, Motion controllers, HMI, Switches✔ Networking and Communications Hubs, Gateways, Routers Cell-Phones, Pagers, ATM Machines✔ Automotive Devices used in vehicles✔ Commercial / Home Office Printers, Scanners, Monitor, Faxes, Copiers, Bar-code readers✔ Aerospace and Defense

10.2.1 Market-Specific Standards

Hardware Engineers use IEEE for standards mostly – However no single entity exists for firmware / software standards

◌ Consumer Electronics▪ CEA Consumer Electronics Association http://www.ce.org/ ▪ JavaTV http://www.oracle.com/technetwork/java/embedded/javame/index.html

▪ DVB Digital Video Broadcasting https://www.dvb.org/standards▪ MHP Multimedia Home Platform

http://en.wikipedia.org/wiki/Multimedia_Home_Platform ▪ DAVIC Digital Audio Visual Council (ISO/IEC 16500) http://www.davic.org/

http://www.iso.org/iso/home.html ▪ ATSC Advanced Television Standards Committee http://www.atsc.org/cms/ ▪ DASE Digital TV Applications Software Environment▪ ATVEF Advanced Television Enhancement Forum http://www.atvef.com/ ▪ SMPTE Society of Motion Picture and Television Engineers (DDE-1) https://www.smpte.org/ ▪ DTVIA Digital Television Industrial Alliance of China▪ ARIB-BML Association of Radio Industries and Business of Japan http://www.arib.or.jp/ ▪ OCAP OpenCable Application Forum http://www.cablelabs.com/specs/specification-search/?

cat=video ▪ OSGi Open Services Gateway Initiative http://www.osgi.org/Main/HomePage ▪ OpenTV DVB-Compliant http://www.nagra.com/ ▪ MicrosoftTV http://windows.microsoft.com/en-us/windows/understanding-tv-

signals-tuners#1TC=windows-7 ▪ HAVi Home Audio Video Initiative

◌ Medical Devices▪ FDA US Food and Drug Administration http://www.fda.gov/ ▪ - Medical Devices Directive▪ - Medical Device Communications IEEE1073

◌ Industrial Automation and Controls▪ IEC International Electrotechnical Commission http://www.iec.ch/ ▪ ISO International Standards Organization http://www.iso.org/iso/home.html ▪ DICOM Digital Imaging and Communications in Medicine ` http://medical.nema.org/ ▪ - Department of Commerce http://trade.gov/td/health/ ▪ - The Machinery Directive

◌ Networking and Communications▪ Ethernet Institute of Electronics and Electrical Engineers IEEE 802.3

http://www.ieee.org/index.html ▪ TCP/IP Transmission Control Protocol / Internet Protocol - RFC 791(IP) & 793(TCP) http://www.faqs.org/rfcs/ ▪ PPP Point-to-Point Protocol▪ Cellular http://www.cdg.org/ http://www.tiaonline.org/ ▪ HTTP Hypertext Transfer Protocol http://www.w3.org/Protocols/Specs.html ▪ SIG-Bluetooth Bluetooth Special Interest Group https://www.bluetooth.org/en-us

Page 112: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

▪ HTML Hyper Text Markup Language◌ Automotive

▪ OPEL Engineering Material Specifications https://www.ihs.com/products/design-industry-standards-organizations-index.html

▪ FMVSS Federal Motor Vehicle Safety Standards http://www.nhtsa.gov/cars/rules/standards/ ▪ ISO/TS 16949 The Harmonized Standard for the Automotive Supply Chain http://www.iaob.org/ ▪ GM Global https://www.ihs.com/products/design-industry-standards-organizations-index.html ▪ Ford Standards same as above

◌ Aerospace and Defense▪ SAE Society of Automotive Engineers http://www.sae.org/ ▪ AIA/NAS Aerospace Industries Association of America http://www.aia-aerospace.org/ ▪ DOD Department of Defense▪ DISA Defense Information Systems Agency http://www.disa.mil/▪ JTA Joint Technical Architecture

◌ Office▪ TIP/SI TechnologyTransport Independent Printer/System Interface IEEE Std 1284.1 – 1997 IEEE▪ Postscript http://www.adobe.com/ ▪ ANSI/AIM Uniform Symbology Specification for Bar Codes http://www.aimglobal.org/standards/aimpubs.htm

10.2.2 General Purpose Standards✔ Programming Languages

◌ pJava Personal Java◌ J2ME Java 2 Micro Edition◌ .NET Compact Framework

✔ Security◌ IETF Netscape Internet Engineering Task Force http://netscape.aol.com/ ◌ SSL Secure Socket Layer◌ SILS Standards for Inter-operable LAN/MAN Security http://www.ieee802.org/

✔ QA - Quality Assurance◌ ISO 9000 International Standards Organization

10.3 Embedded System IDE ✔ Integrated Development Environment (IDE)

◌ Freescale▪ CodeWarrior Development Studio

▫ Uses Eclipse IDE w/Processor Expert Integrated▫ ARM Processors (ColdFire®, ColdFire+, DSC, Kinetis, MPC5xxx, RS08, S08 and S12Z )▫ http://en.wikipedia.org/wiki/CodeWarrior▫ http://www.freescale.com/webapp/sps/site/prod_summary.jsp?code=CW-MCU10&tid=vanCWMCU10

▪ Kinetis Design Studio (KDS)▫ http://www.freescale.com/webapp/sps/site/prod_summary.jsp?code=KDS_IDE&tid=vanKDS

◌ IAR Systems▪ https://www.iar.com/iar-embedded-workbench/

◌ mbeddr http://mbeddr.com/◌ WindRiver http://www.windriver.com/◌ Crossworks from Rowley http://www.rowley.co.uk/arm/◌ Nedit http://en.wikipedia.org/wiki/NEdit◌ Atollic TrueSTUDIO http://atollic.com/index.php/truestudio◌ Mentor Graphics CodeSourcery http://www.mentor.com/embedded-software/codesourcery◌ Keil's MDK uVision IDE http://www.keil.com/arm/mdk.asp

✔ Text Editors for Firmware Development◌ Notepad++ http://notepad-plus-plus.org/ ◌ Sublime Text http://www.sublimetext.com/◌ Slick Edit◌ Build Tools http://www.throwtheswitch.org/◌ Wiki Build Tools http://en.wikipedia.org/wiki/List_of_build_automation_software

Eclipse seems to be the most popular IDE

Page 113: Electronics Engineering N2NO - EEWeb Communitys.eeweb.com/.../08/14/ElectronicsEngineering_N2NO_forReview-1439… · Electronics Engineering N2NO Newbie-2-Novice-Outline Written By:

10.4 Symbols

10.4.1 Timing Diagrams

10.4.2 Schematic Symbols