PDF- c#.net books free download -Buckland's Complete Book of Witchcraft by Anonymouspdf - c What Happens ebook

Happens ebook




NOTICE The material presented in this book is for the education and amusement of students,

Every effort has been made to assure the accuracy of this infor­ mation and its suitability for this purpose

Square 1 Electronics and the author assume no responsibility for the suitability of this information for any application nor do we assume any liability resulting from use of this information

No patent liability is assumed for use of the information contained herein

All rights reserved

No part of this manual shall be reproduced or transmitted by any means (including photo copying) without written permission from Square 1 Electronics and the author

Copyright © 2008 David Benson

TRADEMARKS Registered trademarks of Microchip Technology,

Inc: PICmicro PIC PICSTART Plus PICkit 2 MPLAB ICD 2 ICSP In-Circuit Serial Programming Registered trademarks of Microsoft Corporation: Microsoft Windows Hyper Terminal Registered trademarks of Hilgraeve,

: HyperTerminal Private Edition


Square 1 Electronics P

Box 1414 Hayden,

ID 83835 U

Voice (208)664-4115 FAX (208)772-8236 EMAIL [email protected] http://www





Pins and functions Package Clock oscillator Reset Ports Special Features PIC microcontroller architecture Code and data protection Configuration bits CIRCUIT FOR PIC16F818 EXPERIMENTS CHOOSING DEVELOPMENT TOOLS

CCS compiler Device programming methods Device programmers and ease of running code examples Device programmer In-circuit serial programmer Choosing a device programmer Microchip PICSTART Plus Choosing an in-circuit programmer/debugger CCS ICD-U40 (or







What it looks like Typing accuracy Comments Text And Formatting BITS,

Bit Nibble Byte Binary Hexadecimal




Reserved words in C

43 44 45








main() function Functions Built-in functions

Executable statements Blocks Conditional statements Semicolon use rules


Program design

Programming concepts 70 Programming examples 72 Simple data transfers 75 Loop

! logical operator 96 && logical operator (two switches) 97 logical operator (two switches) 97 if/else,

write output bit 100 Event counting 102

Bit manipulation using bit manipulation functions Bit set/clear Bit testing Flags #bit pre-processor directive example typedef example Bit manipulation using bitwise operators Shift bits right or left Change specific bit to "1" Change specific bit to "0" Change specific bit to its compliment Goto Function library Cut and paste TALKING TO A PIC MICROCONTROLLER WITH A PC VIA A WINDOWS TERMINAL PROGRAM

"U"-turn experiment PC-to-PC "2-lane highway" experiment PC/PIC microcontroller PC baud rates RS-232 interface for a PIC microcontroller PIC microcontroller-to-PC serial communication Formatting PIC microcontroller data on a PC screen STRINGS ARRAYS

Index to an array Step through array elements Extract n**1 element from array Add offset to index Lookup tables 7-segment LED display STRUCTURES

Structures and ports

137 140

Mathematical operators 140 Operator precedence 140 Data type selection considerations 142 Formatting variables such as math results for printing 143 PASSING VARIABLES

Passing variables Returning variables Prototyping functions


Assignment operator Relational operators Logical operators Increment and decrement Mathematical operators Bitwise operators Pointer operators Structure operators Operators that don't fit the categories INTERRUPTS

External interrupt sources 152 Internal interrupt sources 152 Timer 0 interrupt 152 Port B interrupt on change

- bits 7,

Digital output waveforms Using timer 0 Prescaler Putting timer 0 to work Setting up timer 0 Starting timer 0 Counter How do we know timer 0 is doing something

? Timer 0 will keep on counting as long as: Timer 0 must be reloaded after each overflow for repeating time intervals Stopping timer 0 Timer 0 experiments Digital output waveform using timer 0










INTRODUCTION The internal operation of a microcontroller is all about reading and writing to registers,

or some­ times a bit in a register

This is done to: • • • • •

Control the operation of the microcontroller itself

To communicate with the outside world via input or output pins (lines)

To move data from one register to another

To perform mathematical calculations

And more

Assembly language programmers select and use instructions from the microcontroller's instruc­ tion set and put them in the proper order to make the desired (hopefully) things happen

C does a lot of this byte and bit level stuff for you

C is a high level language

create the overall plan in the form of C source code

The C compiler generates an assembly level program and the file containing the l's and 0's that get programmed into the microcontroller (device) itself

C does not have an instruction set

Functions and executable statements get the job done

Some functions are built-in to the compiler,

The C compiler that we will be using has a lot of built-in functions specific to PIC ® microcontrollers which will make your job much easier

You will write the executable statements

You will find that there are lots of ways to do the same thing in C (that work)

I have two goals which conflict

The most important one is to give you the basics in the simplest,

most consistent wray possible to minimize confusion and move you toward writing your own pro­ grams (that work) as soon as possible

The secondary goal is to show' you enough about other ways to do things that you will be able to understand other people's code,

especially the exam­ ples and drivers that come with the compiler which have been created by various authors over time

Reading this book will not give you an encyclopedic knowledge of C

It is not meant to be erudite

It is meant to be informal and user friendly

My goal is to help you be successful

No matter what programming language or specific device you use,

you will need to know some­ thing about the internal workings/layout of the device you choose to work w'ith and the electrical connections to the outside world

In this book,

we will use the PIC 16F818 for running the examples

The information that you need to understand the examples is provided so you won't have to look elsew'here for it (w ith the exception of some specific details listed in the CCS C Compiler Reference Manual)

When you move on to projects of your ow n using other devices,

you will need a copy of the Microchip data sheet for each device

It will be book-length and available for download at microchip

The PIC16F818,

like the majority of PIC microcontrollers,

has program memory made using flash technology,

which means it can be erased electrically

It can be programmed,

tested in-cir­ cuit and reprogrammed if necessary in a matter of a few minutes and without the need for an ultraviolet (UV) EPROM eraser

It is a small device (18-pins),

readily available to all including hobbyists and students at a cost of $4

Think of the PIC16F818 as a custom I/O handler

It looks at its inputs and,

it sends signals out its outputs

You can customize it to do what you w'ant via program­ ming

It is not a heavy duty number cruncher or data manipulator

A variety of device programmers arc available for the PIC16F818 from independent program­ mer manufacturers for as little as $40

Learning how PIC microcontrollers work and how to apply them involves study in three areas: • Use of a computer running Microsoft Window's (tm) (as needed)

• C programming language and C compiler

• PIC microcontroller itself

The use of "pow'er tools" for programming PIC microcontrollers is essential

This means learn­ ing to use an IBM compatible computer if you haven't already done so

It also means learning to use a C compiler which converts English-like readable instructions into machine language understood by the PIC microcontroller itself


learning about the PIC microcontroller's inner workings is possible once use of the power tools is understood

The usual approach used by others to teach the use of PIC microcontrollers has been to get into all of the theory and details of the programming language and then show advanced examples using one of the more complicated parts

As usual,

only 5 percent of this information is needed to get started,

The approach taken here will be to give you the 5 percent you need to get going using the P1C16F818 masquerading as a relatively simple part

The object is to make this process as easy and enjoyable as possible

Once you get through this and you have programmed a PIC16F818 for the first time,

You will be able to create more interesting projects and have more fun

The assumption is made that you know how' to do the following on a computer running Microsoft Window's: • Create a new folder

• Copy part of the contents of a CD to the folder

• Use a simple text editor to create a text file,

As a beginner,

you need to type the code examples in this book yourself,

make the typing mis­ takes we all make,

and learn what the error messages generated by C compiler mean

That is why the code in this book is not on our web site

The code for our intermediate and advanced level books is on our web site

GENERAL INFORMATION See our web site at http://www

com for updates and for errata

Let's C what happens

PIC MICROCONTROLLER PRODUCT OVERVIEW This book is not about one device

It is about the whole Microchip microcontroller product line

We need a place to start,

a simple (relatively speaking) device which will be available for an extended period

I feel that the best device for initial learning purposes is the PIC16F818

What you learn in the process of using it is applicable,

to the entire Microchip product line

In a simplistic way,

Microchip's 8-bit microcontroller line may be classified or categorized in three groups as follows: • 12-bit core base-line

The number of bits in the instruction words corre­ spond to the core width (in bits)

We don't really care how' many bits are in an instruction word or how' wide the core is

We merely need to know what category a given device belongs in so we know' which set of rules apply to it

All of these microcontrollers arc classified as 8-bit devices because the data and data bus are 8 bits wide

The most popular segment of the 8-bit product line is the 14-bit core mid-range parts

Our atten­ tion will be focused there

The 12-bit core base-line parts are less sophisticated than the 14-bit core parts and are a step backwards (dumbed down)

They still have plenty of capability for many low-end applications and are widely used where production volume is high and unit cost must be very low

They are not used much by experimenters

The 18 series parts have many similarities with the mid-range devices,

but require a separate dis­ cussion

This group is growing

Microchip has introduced a new' 16-bit microcontroller family

The data and data bus are 16 bits w ide

The core is 24 bits wide

These devices have a lot of computation capability and on­ board peripherals

Once you learn the fundamentals of using PIC microcontrollers,

there is plen­ ty of room to grow

the information in this book applies directly to the 14-bit core parts

Chances are that when you choose a part for a project or product,

it won't be the one you begin your learning experience with

Learn with the PIC16F818 and branch out later to learn about other devices that interest you

You will need an PIC16F818 data sheet (really a book) as a ref­ erence as well as a data sheet for each device you become interested in later on

This informa­ tion is available on Microchip's web site

Microchip has product family information available on their web site

As I am writing this,

you can select 8-bit PIC Microcontrollers,

then PIC16MCU to arrive at a matrix of information con­ sisting of devices going down and features going across the matrix

Their web site is constantly changing,

so you may have to poke around a little to get there

Compare the features and layout of devices of interest with the soon to be familiar PIC16F818 as a reference point

SELECTING A DEVICE FOR EXPERIMENTS This book is not about one or two specific PIC microcontrollers

The information presented will serve as a foundation for working with all Microchip microcontrollers

In order to do experi­ ments and to create code that works,

we must select a specific device to work with

By making minor changes,

the code examples in this book will run on many other PIC microcontrollers in the 14-bit core product line

One of the great things about C is that code can be ported from one device to another easily

I have chosen the PIC16F818 is the example because: • It has 18 pins (small)

• It has an internal clock oscillator with 8 speeds selectable via software

The 8 speed clock oscillator is a relatively new design used in many new devices currently being introduced by Microchip

• It has the best mix of on-board peripherals (timer/counters,

A/D converter) for beginner and intermediate level experimentation

• It has in-circuit debugging capability built into the device which you will find is a big advantage as you move forward to more complex projects

There are lots of features and their associated registers inside the PIC16F818 which I will keep hidden from you so you don't have to worry about them until some time down the road (next book)

The PIC 16F818 will appear to you as a simple device with a few pins which will go unused for now

When choosing a dcvice for an application,

one would look at factors such as program memory size,

on-board peripherals such as A/D,

When firing up a device you have not used before for the first time,

you must do the following: • Determine whether or not there are analog peripherals (A/D and/or comparators) which must be turned off if not used

The CCS C compiler will do this for you as a default

• If there is a multi-speed internal clock oscillator (software selectable speed),

you must determine what speed it will run at when the device is powered-up and whether or not the speed must be changed during initialization of the device to suit your application

• Determine what features are controlled by the configuration word(s) as the device is programmed by the device programmer and what selections should be made

Using C will greatly simplify this process for you

• Determine how many configuration registers there are and how to write to them

Using C will greatly simplify this process for you

Explanations of these things follow as appropriate

I have made the choices for you when using the PIC16F818 as your example for the experiments


I will show you how to do this on your own


The PIC 16F818 is fabricated using CMOS technology

It consumes very little power and is fully static meaning that the clock can be stopped and all register contents will be retained

The maximum sink or source current for a port at any given time is as follows:

Any I/O Pin Port A Port B Sink current Source current

Supply current is primarily a function of operating voltage,

frequency and I/O pin loading and is typically 2 mA or so for a 4MHz clock oscillator and 5 volts

This drops to less than 100 microamps (even a few microamps) in the power-managed modes (see data sheet)

Because the device is CMOS,

All unused inputs should be pulled up to the supply voltage (usually I 5 VDC) via a 10 K resistor

PACKAGE The PIC16F818 is available in an 18-pin DIP package suitable for the experimenter

The current part number is PIC 16F818-I/P

CLOCK OSCILLATOR The internal clock oscillator may be used (most common),

or an external clock oscillator may be used

The details of various external oscillator circuits and components as well as internal clock oscillator use options are given in the Microchip data sheet

At pro­ gramming time,

the part must be told via configuration bits which clock oscillator option will be used

This will be explained as we go along

For experimentation,

we will use the internal clock oscillator as follows: • Default frequency (31

• 4 MHz for applications using a time delay (built-in function or timer 0)

RESET The PIC16F818 has built-in power-on reset which works as long as the power supply voltage comes up quickly

Commonly the MCLR pin is merely tied to the power supply using a pull-up resistor

A switch may be used to regain control if things run away

For our experiments,

we will use pin 4 as MCLR which stands for Master Clear (reset)

It will be pulled up to +5volts via a 47 K resistor to keep the device out of reset unless the MCLR pin is pulled low by some external device

If you choose to use one of the ICD-type in-circuit serial programmers,

the programmer will use pin 4 for the programming threshold voltage,

which puts the device in programming mode

After programming is completed,

you may bring the device out of reset to test your program using the ICD control interface running on the PC

This makes programming and testing your codc fast and easy


Port B is 8 bits/lines wide or byte-wide

Each port line may be individually programmed as an input line or output line

This is done using a special function which matches a bit pattern with the port lines in registers callcd "tristate" or "tris" registers

A "0" associated with a port line makes it an output,

Examples follow

Pins which may have analog functions in use are analog functions when the microcontroller comes out of reset

For the PIC16F818,

the CCS compiler will generate an instruction which changes those pins to digital I/O as part of the initialization process unless the compiler encoun­ ters a call to setup_adc_ports ( )

This is a default and it is very important to keep in mind

The Port B lines have weak pullup resistors on them which may be enabled or disabled under software control

All 8 resistors are enabled/disabled as a group via a built-in function in the compiler (not used in this book)

The pullup resistor on an individual port line is automatically turned off when that line is configured as an output

The pullups are disabled on power-on reset

Port A,

bit 4 is shared with the external timer/counter input called TOCKI

As a digital input line,

As a digital output line,

so a pullup resistor is required

The output cannot source current,

For experimenting,

all unused port lines should be tied to the power supply via 10 K pullup resistors (CMOS rule

On reset,

SPECIAL FEATURES Watchdog Timer The watchdog timer is useful in some control applications where a runaway program could cause a safety problem

We will not deal with it exccpt to say that it is important to select "watchdog timer off' when programming the configuration bits

Power-up Timer (PWRT) The power7up timer holds the device in reset for a time which allows the power to come up to a level wjiich will provide reliable operation of the device at which time it is allowed to come out of resetV The power-up timer should be selected "enabled" when programming the configuration bits

Brown-out Reset (BOR) If Vdd falls below approximately 4 volts for about 100 microseconds,

The brown-out reset feature should be selected "enabled" when programming the configuration bits

Sleep Mode The feature of the "sleep mode" is drastically reduced power consumption achieved by turning off the main clock oscillator

In-Circuit Debugging The PIC16F818 is designed so that an in-circuit debugger may be connected to it (advanced topic)

Low-Voltage ICSP Programming Low voltage ICSP will not be used

Peripherals Peripherals such as timer/counters and A/D converters will be discussed in chapters devoted to the subjects

Special Feature Selection Details follow

PIC MICROCONTROLLER ARCHITECTURE PIC microcontrollers have two separate blocks of memory,

program memory and data memory

Program Memory The PIC16F818 program memory is 14 bits wide and 1K words long

Program memory is flash which means it can be erased electrically

Program memory is read-only at run time for the purposes of this book

PIC microcontrollers can only execute code contained in program memory

Pointed To By ■ Reset Vector

Pointed To By Interrupt Vector

A limited amount of data may be stored in program memory (see Writing Programs chapter)

Weird Hex Notation The "Ox" means hexadecimal

The Ox notation comes from the C programming language

The main thing is,

Some of the newer Microchip literature uses "h" to denote hexadecimal numbers

Data Memory Data memory consists of register files containing registers of two types: • General purpose registers which hold your data

• Special Function Registers (SFRs)

The register files are 8 bits wide (with the exception of the PCLATH register which is 5 bits wide)

The P1C16F818 has a 512 register file address space (0x000

but not all addresses are used

Register File 0x00 01 02

Indirect Address TMR0 PCL Status File Select Port A Data Port B Data

Indirect Address Pointer * Timer/Counter Program Counter Low Order 8 Bits Status Register


Program Counter Latch High Order 5 Bits Interrupt Control

General Purpose Registers Think

Of This Area As RAM (Data Memory) 0x7F Bank 0 Not Physically Implemented Note: Bank Switching And Banks 2 And 3 Ignored

For the most part,

the C compiler knows what to do with the SFRs and the address of each

Wc will discuss the very few situations in which the compiler needs help finding address­ es as the need arises

Data EEPROM Memory Data EEPROM memory is not directly mapped into the data memory register file address space described earlier


it is addressed using six special function registers and some built-in C functions

This topic is beyond the scope of this book

Oh yes,

I neglected to spell out what the acronym means

It stands for memory that can be read,

It is usually used to store data acquired during program execution (think data logger)

CODE AND DATA PROTECTION The code protection bits in the configuration register may be set so as to protect the code in pro­ gram memory,

and the data in EEPROM memory from examination by the outside world (so your code can't be ripped off)

Your program can still access and change the contents of data EEPROM memory with the code protection bits set

CONFIGURATION BITS The configuration bits are loeated in flash memory outside the main part of flash memory used for program storage

They are used to determine things like clock oscillator type,

functions of some of the pins,

There is a chapter devoted to this subject

The device programmer accesses these bits during the device programming procedure

By doing this,

the device will be in the correct configuration when it comes out of reset

CIRCUIT FOR EXPERIMENTS One simple circuit may be used for all but one of the experiments in this book

The exception utilizes a 7-segment LED digital display


Looking at what is included may give you some ideas about how you would like to construct it

My suggestions on how to proceed follow

A simple circuit board may be assembled which includes a socket for a PIC16F818,

power supply decoupling capacitors,

three 3-pin headers and shorting blocks for use in selecting functions for pins RAO,

RA1 and RA4,

screw terminal blocks as a means of connecting RAO/ANO,


and RBO/INT to the off-board components used in the experiments,

and DIP switches for pins RAO,

A modular jack is included for easy connection to any of the three ICD/programmers described in the book

If you decide to use a device programmer rather than use an ICD as a programmer,

I would defi­ nitely use a ZIF socket for the PIC microcontroller to avoid bending or damaging the pins

The once common part made by the TEXTOOL division of 3M is still available from Digi-Key

It is the gold plated (literally) version (3M part number 218-3341-00-0602J) and the cost is around $18

A 24-pin Aries socket is available from JAMECO,

Digi-Key and others

The Aries part number is 24-6554-10 (tin plated contacts) and the price will be in the $8 range

Simply ignore the extra 6 pins

Pullup resistors are used in the experiments primarily for the purpose of preventing unused inputs from floating

There are pullups on port B built into the PIC16F818

I decided not to use them because they just add confusion to the program examples and detract from explanation of the applications themselves

when you use the circuit module,

remember there are 10 K pullup resistors on all unused port lines

You can save refinements for later

A modular phone jack is used to connect to the ICD via cable

A printed circuit board style jack is shown

One manufacturer is tyco Electronics AMP

The part number is 5204703

The Digi-Key part number is A9049-ND

The modular phone jack is connected as shown:

Modular Jack 6-Conductor

P/N 520470-3 Digi-Key P/N A9049-ND

If you arc not able to find the small modular phone jack and you want one NOW,

you may pur­ chase a wall-mount phone jack and whack it down to size using a saw

It will have screw termi­ nals on the back

Short wires may be used to connect it to your board or a solderless bread­ board

The example in the photos has one end cut off to show the concept

The one that I have used for some time has all four sides of the mounting plate portion cut off

CCS has a nice PIC16F818 board available which includes what I have described above plus a little more

See Appendix B

- Sources

CHOOSING DEVELOPMENT TOOLS CCS C COMPILER One of the great things about the CCS C compiler is that it includes tots of built-in functions (think subroutines if you are not familiar with C) which control the PIC microcontroller on­ board peripherals

You will not have to learn about or concern yourself with many of the inter­ nal workings (think control registers) of the microcontroller

If you want to read the A/D con­ verter,

simply use the READ ADC() function

Precision time delay built-in functions are avail­ able for your use

CCS also supplies drivers to control popular external devices so you don't have to work so hard figuring out how to do it on your own

The CCS C compiler is a power tool for creating the code for your applications

DEVICE PROGRAMMING METHODS Device Programmers And Ease Of Running Code Examples There are two choices

remove it from the socket on the programmer,

place it in the socket on the test circuit,

This is easier than it sounds

• Use an in-circuit debugger (ICD) as a programmer This is done using a method called in-circuit serial programming (tm) (ICSP) (tm) and the device is programmed in the experiment board

Immediately after programming,

the circuit may be exercised by clicking on a "run" (or similarly named) button on-screen

Moving the device is not necessary

This is the easiest method

ICDs are the least expensive way to go these days unless you already own a device programmer

Device Programmer A device programmer is used to load code into a device and that's it

The device is usually clamped in the programmer's zero insertion force (ZIF) socket during programming

After pro­ gramming is completed,

the device is removed from the ZIF socket and inserted in the socket on the experiment board

The board is powered-up and the code is tested

In-Circuit Serial Programmer An in-circuit debugger (ICD) may be used to download code into a device,

Debugging is not covered in this book,

a debugger may be used to load the example programs in this book into a device followed by bringing the device out of reset so the code will run

The device is part of the example circuit when the programming takes place,

a process called in-circuit serial programming (ICSP)

In-circuit serial programming requires the use of two port lines,

To keep things simple,

the examples in this book do not use these two pins for the test circuit

This allows in-circuit programming followed immediately by running the program using the ICD on-screen controls to bring the microcontroller out of reset which allows the program to run

In an industrial/commercial product development environment,

pins 7 and 6 would be used in the application and special means (a special substitute device or a header containing one) would be used to gain access to the part for debugging purposes while leaving port B,

This is an advanced topic and wc won't concern ourselves with the details here

The PIC16F818 may be programmed using an ICD as an in-circuit serial programmer followed,

Available ICD's include the CCS ICD-U40 (or ICD-S40),

Three advantages of using this method over using a device programmer (only) are: • The convenience of running the code immediately following programming

• The ICD will be available for debugging when you move up to more advanced projects

CHOOSING A DEVICE PROGRAMMER Selecting a programmer (only,

not an ICD) for PIC microcontroller development is a personal choicc based on the following criteria: • Range of parts which can be programmed


inexpensive device programmers are available which run under Microsoft Windows

As product offerings are continually changing in this fast-paced market,

I suggest you contact the programmer manufacturers directly for the latest information

Note that some programmers are connected to the PC's parallel (printer) port,

some arc connected to a serial port (usually COM2),

Microchip PICSTART Plus (tm) Microchip's PICSTART Plus will program their 5 volt dual in-line (DIP) packagc devices

The latest version of the PICSTART Plus contains a PIC 18 scries microcontroller which converts information received from the PC's serial port to the appropriate signals to program each device

Since these devices have differing requirements,

the code in the PIC 18 microcontroller must be updated to cover the requirements of new devices as they become available

The latest code (firmware) may be downloaded from Microchip's web site at no charge

The PICSTART Plus operates under Windows and is connectcd to one of the PC's serial ports (usually COM2)

The control software for the PICSTART Plus is incorporated in MPLAB (tm) which is Microchip's development software

MPLAB is also updated frequently to incorporate support for new devices as they are introduced

The PICSTART Plus currently sells for about $200


They each use different control software

The CCS ICD will program the devices used as examples used in this book using ICSP and will allowr the program to run after the device is programmed

The ICD Control Software is separate from the compiler software

The ICD-U40 or

Microchip PICkit 2 (tm) The PICkit 2 uses a USB interface

The PICkit 2 will program the devices used as examples used in this book using ICSP and will allow the program to run after the device is programmed

Control software comes with the PICkit 2 and will handle the tasks we need to perform with the examples in this book

The PICkit 2 may be used under the control of MPLAB for many devices

We will use the PICkit 2 control software in our examples

The PICkit 2 MCU programmer (PG164120) currently costs about $35

I suggest purchasing a RJ-11 to ICSP adapter (AC 164110) ($ 10) to go with it

It has a header at one end to interface with the PICkit 2 and a short 6-conductor cable with a modular plug on the other to interface w ith the modular jack on your board

Microchip ICD 2 (tm) The ICD 2 will also program the device used as an example in this book using ICSP and will allow the program to run after the device is programmed

MPLAB is used to control the ICD 2

An ICD 2 with a USB cable and powrer supply sells for approximately SI90

Programming (only) Connections

Programming Software

CCS ICD Control Software

PICkit 2 Application Software (MPLAB for some devices)




USING THE ICD AS A PROGRAMMER To program a C object file (

cot) into a PIC microcontroller: Connect the 1CD-U40 to your PC using the USB cable included with the ICD module

Connect the ICD to your target board using the short modular phone cable (6-conductor) supplied with the ICD

The target board should be powered by your +5 volt logic power supply

Power-up the PC which will supply power to the ICD via the USB interface

Power-up the Target board

Open the ICD control software

Note that this program is separate from the compiler software

The ICD Control Program window appears

Targets Supported: All

To program and exercisc an example program,

The ICD Advanced window appears

Our objectives are: • Halt the device (hold the MCLR line low)

_____ • Run example programs (put the target device in run mode by allowing the MCLR line to be pulled high)

• Program (write) example programs into a device

We will not concern ourselves with debugging as that is an advanced topic

Halt vs

Run can be selected by clicking on the appropriate button in the Target State area in the ICD Advanced window

To program a dcvicc,

cof file must have been created previously using the compiler

With the ICD Advanced window open: Halt the target device

In the Write Device area,

The Download To Target window will appear

Navigate to the object file you wish to write to the target device and select it (will be highlighted when you have selected it)

Click Open

This will initiate programming

In the message area in the lowrer left comer of the ICD Advanced window,

a message should appear indicating that your source file has been written to the target device

Click on the Run button

There will be a slight delay

Observe your program running (look at LEDs or whatever depending on what the code is supposed to do)

When you have finished your celebration (you did do everything correctly didn't you

You may repeat the programming process to test another program

When you are finished: Power-off the target board first (always

Power-off the PC last

Disconnect the USB cablc

When using the CCS ICD to program a PIC microcontroller,

hex files are much smaller and do not contain the C source,

hex files are more often used in a production setting


cof file into a PIC microcontroller: The PICkit 2 comes with its own programming software which we will use here

Some devices may be programmed using MPLAB and accessing the PICkit 2 as one of the programmer options under MPLAB

The PICkit 2 has a 6-pin header socket as the interface to a user board

Products are often designed with a 6-pin header on them to allow in-circuit serial programming (ICSP) after the product is assembled and just before it is shipped allowing the latest firmware version to be pro­ grammed into the product

Firmware may also be changed by the customer in the field after the product is in use

for experimenting and development,

Microchip offers an adapter consisting of a very small board with a header to mate with the socket on the PICkit 2 plus a modular phone jack

A short 6-conductor phone cable is included to conncct the adapter to a modular phone jack on your board

The Microchip part number is AC 164110 (ICD 2 to ICSP adapter)

Connect the PICkit 2 ,

Conncct your board to your +5 volt logic power supply (power supply off)

Connect the PICkit 2 to your PC using the USB cable supplied with it

Power-up the PC

Power-up your board

Open the PICkit 2 programming software

The PICkit 2 software will come up recognizing the device on your board (assuming the devicc family you are using was selected the last time the software was used)

If not,

Check /MCLR in the small Vdd PICkit 2 box

Load your

cof file into MPLAB’s Program Memory (zone)

File>Import Hex Navigate to your

Select the file

Click Open

A message will appear indicating that the file has been imported

Click on the Write button to program the device

A message should appear reporting success

Uncheck /MCLR in the small Vdd PICkit 2 box

Your program should run

To halt program execution check /MCLR

This will hold the device in reset

To program and run another program,

cof file and repeat the programming procedure

When you have finished experimenting,

power-down using the reverse sequence: Power-down the target board

Power-down the PC

PROGRAMMING A DEVICE USING THE ICD 2 DESCRIPTION The Microchip in-circuit debugger (ICD 2) consists of software which runs on a PC (included in MPLAB) and hardware which looks like a colorful hockey puck (two of the colors are shown here)

For the purposes of this book,

the ICD 2 will be used as an In-Circuit Serial Programmer (tm)

The unit has a USB connector for serial communication with a host PC and a 6-conductor modu­ lar phone jack for communication with a flash PIC microcontroller

The PIC microcontroller resides on a so-called "target" board which is the user's (your) board

Microchip strongly recommends using USB and NOT the RS-232 connection which is built into the ICD 2 for communications between the host PC and the ICD 2

Following the current version of the Microchip USB Port Setup instructions is a MUST

Refer to the "Readme for MPLAB ICD 2" contained in the Readmes folder in the MPLAB folder

I recommend purchasing the ICD 2 full kit with power supply (DV164007) and storing the RS-232 serial cable somewhere

The ICD 2 can operate in two operating modes: • Debugger mode (not discussed here)

In the programmer mode,

your code is programmed into the device for stand alone (without the ICD 2 connected) operation

The code can,

be run with the ICD 2 connected

Selecting the best option for powering the ICD 2 and the target is critical

Based on my experi­ ence and that of others,

I recommend powering the ICD 2 using Microchip's wall transformer power supply and NOT via the USB port

I also recommend powering the target (your circuit) with your own power supply

USER BOARD = TARGET BOARD For the purposes of this book,

the PIC16F818 experiment board described earlier is set up to be used with the ICD 2

You can easily set up another board of your own in a similar way by pro­ viding the modular phone jack and using the 47 K pull-up resistor on MCLR (reset)

SETTING UP THE ICD 2 Connect the ICD 2 to your PIC16F818 board using a short 6-conductor modular phone cable

Connect your PIC 16F818 board to a suitable +5 volt DC power supply

When powering-up the ICD 2 and PIC16F818 board the first time or for use with a new project,

use the following procedure: 1

At start-up,

NO power should be applied to the PIC 16F818 board

Power-up the host PC

Power the ICD 2

The green "Power" LED in the ICD 2 should be on


At this point,

cof file suitable to be programmed into the PIC16F818 on your board

Configure>Select Devicc

Select PIC16F818

Select ICD 2 as the programmer to be used

Programmer>Select Programmer>MPLAB ICD 2

A Setup wizard will appear the first time the ICD 2 is connected

Select USB as the communications method

Select target has owrn power supply

Select auto connect to ICD 2

Select ICD 2 automatically downloads the required operating system

Select Programmer>Settings

The MPLAB ICD 2 Settings dialog box will open

Click the Power tab and ensure that the check box for "Power target circuit from ICD 2" is NOT checked

Click OK

This is important

Power-up your PIC 16F818 board

Open the output window


Select Programmer>Connect

Observe the activity in the output window

On completion,

the next to the last two text lines should read "Running ICD Self Test

Passed" and the last text line should read "MPLAB ICD 2 Ready"

You should now be able to debug and erase the PIC16F818 on your board

Reverse the procedure to power-down (PIC16F818 board off,

ICD 2 off,

PC off)


use the following procedure to program a

cof file into a PIC microcontroller: 1

Connect the ICD 2 to your board (target board)

Connect the ICD 2 to your PC

Power-up the PC

Power-up the ICD 2 using the ICD 2 power supply

Power-up the target board using your own power supply


Configure>Select Device

Programmer>Select Programmer

Select MPLAB ICD 2

Programmer>Connect (if you don't have auto-connect selected)

Import your

cof file into MPLAB's Program Memory (zone)


Navigate to your

Select the file

Click Open

A message will appear indicating that the file has been imported


A message in the Output window should report success

Programmer>Release from Reset to run your program

Import another

cof file and repeat the procedure

Programmer>Disable Programmer (assuming you are finished programming devices for a while)

Power-down using the reverse sequence: Power-down the target board

Power-down the IC’D 2 by disconnecting the power cable

Power-down the PC


To program a

cof file into a PIC microcontroller: Connect the PICSTART Plus to your PC (as usual)

Power-up the PICSTART Plus


Configure>Select Device

Programmcr>Se 1 ect Programmer

Select PICSTART Plus

Programmer>Enable Programmer

A message in the Output window will indicate your PICSTART Plus firmware version

Load your

cof file into MPLAB's Program Memory (zone)


Navigate to your

Select the file

Click Open

A message will appear indicating that the file has been imported

Insert the device in the ZIF socket

Be careful about pin orientation


A message in the Output window should report success

Remove the programmed device from the ZIF socket

Programmer>Disable Programmer (assuming you are finished programming devices for a while)

Power-down the PICSTART Plus

NEVER power-up the PICSTART Plus with a device in it as the device may be damaged



USING THE COMPILER Create a new' folder for your C stuff

Create a source file

File>New>Source Csl The compiler will add

Type your first source code

Call it Csl as an example

Create a new project


The Select main source file window appears

Select device

Select your file (Csl or whatever)

Click Open

The Project options window appears

Your file name has been selected automatically (if you had one open)

Click Apply

Compile your code

Click on the Compile tab on the menu bar at the top of the screen

The Compile menu ribbon will appear

Click on the Compile icon on the Compile menu ribbon

Your source code will be compiled successfully,

The Output window will appear indicating how the compile process turned out

For the examples in this book,

a warning message will appear: »>Warning 208 Csl

c Line 6 (i,5): Function not void and does not return a value main Ignore the warning

This is what we wanted,

cof file) was created as part of the process of compiling your source code (done in the background)

It is located in the same folder as your source code (Csl

This is the file that will be programmed into the PIC microcontroller

If you have PIC microcontroller assembly language programming expcricnce,

you may want to take a look at the assembly language listing of the code generated by the compiler

To do this,

click on the Output files icon on the right end of the Compile menu ribbon

Click on the C/ASM List icon

! One missing semicolon can result in a lot of compiler error messages of various kinds

I am cer­ tain that you will never experience this

C SOURCE CODE This is what C source code looks like: ////first C program ala pictl

asm Csla #include #fuses INTRC_IO,NOWDT,PUT,NOPROTECT,BROWNOUT,MCLR,NOLVP,NOCPD,NOWRT,NODEBUG #fuses CCPB2 //internal clock osc with I/O on RA7,

RA6 //watchdog timer disabled power-up timer enabled //code protection off brown-out reset enabled //mclr enabled low-voltage programming disabled //no EE data protection write protection off //no debug CCPl function pin RB2 (arbitrary) main()

//4 MHz clock oscillator //bit pattern to port B //circle,

} This is a very simple program which runs on a PIC16F818

We will assume that there are 8 LEDs connected to port B

Executing this program causes 4 LEDs to be off and 4 LEDs to be on

I am sure this program looks very cryptic to you now

When you have finished reading this book and doing the experiments,

this program and much more complex ones will no longer seem cryptic

As you read the next few chapters,

you can refer to this program to see how the topics relate to this program

For now,

let's make some observations about the overall look of the program

TYPING ACCURACY Typing accuracy is very important when creating C source code

A punctuation mark,

either typed by mistake or omitted,

can cause a lot of head scratching (or worse) because your "per­ fect" program won't compile

The compiler sees exactly what you type

COMMENTS Comments help anyone (including you) who reads your code understand what it does

There arc two styles

The compiler ignores all comments

Comments between /* and */ Comments between // and end of line

TEXT AND FORMATTING Formatting such as spaces,

Formatting makes code readable to us

White space resulting from laying out a program so it appears better organized is a good thing

This comes from using spaces,

The compiler will ignore white space

Use tabs for indentation instead of several spaces

The number of spaces per tab is usually adjustable

Three spaces per tab works well

ANSI (or standard) C is case sensitive,

BIT One bit in memory or a register can represent 1 of 2 possible states,

"0" or "1"

In the world of digital electronics,

it is convenient to build circuit elements which have two states,

These states can be represented by "0" or "1"

POSITIVE LOGIC Binary Number 0 1

Voltage 0 volts (approximately) 5 volts (approximately) in a 5 volt system

The exact voltage ranges which represent 0 and 1 vary depending on the logic supply voltage and the integrated circuit logic chip family used (TTL,

The choice of using binary 0 to represent 0 volts is arbitrary

Positive logic is shown above

It can be done the opposite way which is called negative logic

NIBBLE A nibble consists of 4 bits and can represent 16 possible states

A nibble is typically the upper or lower half of a byte (most significant or least signi (leant nibble)

BYTE A byte consists of 8 bits and is said to be 8 bits wide

BINARY A binary' number with more than one bit can represent numbers larger than " I"

How much larg­ er depends on the number of bits

An 8-bit binary number (byte) can represent 256 possible numbers (0 to 255)

A 16-bit binary number can represent numbers from 0 to 65,535

If we use a byte to transmit information,

we can transmit 256 possible combinations,

enough to represent the 10 decimal digits,

A commonly used code used to represent these characters is called ASCII (American Standard For Information Interchange)

Binary numbers arc based on powers of 2

The value of bit 0 is 2° = 1 if it contains a 1,

The value of bit 1 is 21 = 2 if it contains a 1,

The value of bit 3 is 23 = 8 if it contains a 1,

For a 16-bit binary number,

bit 0 is the least significant bit,

and bit 15 is the most significant bit

The following table shows the value of each bit position if it contains a " I

Bit 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 Most Significant

Least Significant

The value of a binary number contained in a 16-bit timer/counter would be determined by multiplying the contents of each bit by the value of each bit

Counting up in binary goes like this: 0000 0001 0010 0011 0100 0101 etc

You can use this information when you observe what happens to some LEDs used to display the count in a binary count up example program

PIC on-board timer/counters count in binary

A binary number may be used to represent byte-wide bit patterns sent to output ports

HEXADECIMAL Binary numbers which are two bytes long are difficult to recognize,

remember and write without errors,

so the hexadecimal numbering system is sometimes used instead

Think of hex as a kind of shorthand notation to make life easier rather than some kind of terrible math

Hexadecimal Binary Decimal 0 1 2 3 4 5 6 7 8 9 A B C D'E F

Hex is sometimes used in this book to represent addresses in memory and is sometimes used to represent bytes of data

Using hex is not difficult

All you need is a little practice

One byte requires two hex digits

Note that the bits representing a byte are sometimes shown in groups of four

Note that the most significant hex digit is on the left

Hex numbers are denoted by "Ox" in this book

Some of the more recent Microchip literature uses the "h" to designate a number as hexadecimal

To summarize: Binary 1


0 1 5 F

0 1 5 15


Two Bytes 0000 0000 0000 1111

Hexadecimal OxFFFF (the very top of the program memory address space in some microcon­ trollers) is much easier to write or remember than either 1111 1111 1111 1111 or 65535

CONSTANTS A literal constant may be defined as part of a built-in function such as: output_b (OxOf)

//defines hex byte OxOf and sends bit pattern // to port B

A symbolic constant may be defined using the key word const which is a modifier that can be applied to any numeric declaration

// defines integer type constant named // level with a value of 10

After the symbolic constant is defined,

it is referred to by name in the program

The #define pre-processor directive may be used for defining constants

This method for defining constants is probably used more often than the key word const method

A convention in C is to use upper case letters in all constant names

Constants are stored in program memory and cannot be changed during program execution

VARIABLES Variables are memory locations used to store data

A variable must be defined prior to use in a program by using the assignment operator

variable = data '---assignment operator

Variables are named according to the data type that will be stored in them,

an integer variable holds integer data,

The variable definition process tells the compiler how much memory space should be allocated for the variable being defined

A variable,

may be changed during program execution and will be stored in a general purpose file register (RAM location) in the PIC microcontroller

Variables are either global or local

• Global variables are defined outside a function and can be used by any function

• Local variables are defined inside a function (after an opening brace) and used within that function (before the corresponding closing brace)

It is considered good practice to use local variables wherever possible so you can control access to them

If a function needs to use another function's local variable,

that variable can be passed to the function that needs it

Access to local variables is controlled,

Passing variables (arguments) will be discussed in a later chapter on the subject

Declaration of a variable will be demonstrated in the following chapter after data types have been explained

Naming of variables is explained in the chapter after that

DATA Basic data types used in this book are (see note below): Character (ASCII) A character is a single ASCII character which may be represented by 8 bits

There are 256 ASCII characters

The characters most commonly used in microcontroller applications are contained in a table later in this chapter

Apostrophes indicate a character 'A' 'a' ' 1 '6' More than one character is called a string and is designated by quotation marks " " (see Strings chapte

C++ Za Apsolutne Pocetnike

Objektno orijentisano programiranje u realnom vremenu na

download tutoriali C C++ za apsolutne pocetnike pdf C++ programiranje za apsolutne početnike Sadržaj PRO MIL 3 Sažimanje koda Sadržaj Naš prvi program Varijable Grafika Polja Uvod Donošenje odluke pokusnageneracija wp content uploads 2017 10 Cpp Sadrzaj varijable A se uvecava

C0040 USMC Catalog Vol3

Untitled - The Black Vault

Providing scientific and technical advice and assistance to the Military Committee in the field of development (with particular regard to its military application); W5J9CQ 11 C 0040 5b One of the military's top priorities is to aid Soldiers in developing skills that will

C03 BB Config Guide en US

Input/Output Configuration Program User's Guide and ESCON - IBM

PDF Cisco IOS ISO CLNS Configuration Guide, Release 12 2SR cisco us configuration guide iso 12 2sr book pdf PDF Configuring Integrated IS IS Cisco cisco c en


Evault Mobile Security Target - CyberSecurity Malaysia

C090 – 90 days of credit based upon invoice date, paid next coming Thursday Payment Frequency • Volvo Group units should only execute payments to  Both the C090 and C090E are tie clasp modules C090 has a separate battery transformer housing and connector with belt clip

C1-C2 Grammalysis Tests Students

B1 For All Coursebook Answers - Budget Bin

PDF contents MitakosBooks mitakosbooks gr media wysiwyg files grammalysis c1 c2 pdf PDF Interactive Skills C1 – C2 Teacher's book tieexams gr wp content Teachers Book C1 C2 pdf PDF Books 2016 2017

C1 Conversa VALENCIÀ


aulanube docs 1 Curs de valencià C1 pdf El curs de Valencià C1 d’Aulanube proporciona un pla de treball específic per a preparar les proves de certificació de maig juny dels diferents organismes examinadors (JQCV, EOI i CIEACOVA) Atenent els objectius d’aprenentatge establits pel MECR, hi ha

C1 Kurs-und Ubungsbuch Losungen

Literaturauswahl DaZ-/DaF-Lehrmittel - Hep-Verlag

Lösungen Kapitel 1 Heimat ist Wortschatz Ü2 (1) Geburtsort, (2) vertraut, (3) Kindheit, (4) Welt, (5) Menschen Ü2 Fachsprache, Kurssprache Sprachkurs, Band C1 oder C1 1 + C1 2 Band C1 1 Abschlusskurs als Vollband oder

C1 livre

Grille d’évaluation de la production orale C1

lovelineindustries book c2ngj8v dalf c1 Pdf Dalf C1 Passeport Pour Le Diplme Livre Du Professeur document other than just manuals as we also make available many user guides, specifications documents, promotional details, setup documents and more EPUB Dalf C1 Passeport Pour Le Diplme Livre Du Professeur currently available

C1 Redaccions


uchceu es actividades culturales 2015 cursos Valencià C1 | Quadern d'examen | 21 de juny de 2014 | 4 1 V F La llargària de la camisa arribava fins al colze on es podia afegir un rombe de llenç amb què es protegien les parts del cos més delicades

Home back Next