Saturday, June 6, 2009

Microcontrollers give you a fantastic way of creating projects.

Microcontrollers give you a
fantastic way of creating projects.

A PIC microcontroller is a processor with built in memory and RAM and you can use it to control your projects (or build projects around it). So it saves you building a circuit that has separate external RAM, ROM and peripheral chips.

What this really means for you is that you have a very powerful device that has many useful built in modules e.g.


  • EEPROM.
  • Timers.
  • Analogue comparators.
  • UART.

Even with just these four modules (note these are just example modules - there are more) you can make up many projects e.g.:

* Frequency counter - using the internal timers and reporting through UART (RS232) or output to LCD.

* Capacitance meter - analogue comparator oscillator.

* Event timer - using internal timers.

* Event data logger -capturing analogue data using an internal ADC and using the internal EEPROM for storing data (using an external I2C for high data storage capacity.

* Servo controller (Control through UART) - using the internal PWM module or using a software created PWM.

The PIC Micro is one of the most popular microcontrollers and in case you were wondering the difference between a microprocessor and a microcontroller is that a microcontroller has an internal bus with in built memory and peripherals.

In fact the 8 pin (DIL) version of the 12F675 has an amazing number of internal peripherals. These are:
  • Two timers.
  • One 10bit ADC with 4 selectable inputs.
  • An internal oscillator (or you can use an external crystal).
  • An analogue comparator.
  • 1024 words of program memory.
  • 64 Bytes of RAM.
  • 128 Bytes of EEPROM memory.
  • External interrupt (as well as interrupts from internal peripherals).
  • External crystal can go up to 20MHz.
  • ICSP : PIC standard programming interface.
And all of these work from within an 8 pin DIL package!

In the mid-range devices the memory space ranges from 1k to 8k (18F parts have more) - this does not sound like a lot but the processor has an efficient instruction set and you can make useful projects even with 1k e.g. LM35 temperature sensing project that reports data to the serial port easily fits within 1k.

Features

In fact a PIC microcontroller is an amazingly powerful fully featured processor with internal RAM, EEROM FLASH memory and peripherals. One of the smallest ones occupies the space of a 555 timer but has a 10bit ADC, 1k of memory, 2 timers, high current I/O ports a comparator a watch dog timer... I could go on as there is more!

Programming

One of the most useful features of a PIC microcontroller is that you can re-program them as they use flash memory (if you choose a part with an F in the part number e.g. 12F675 not 12C509). You can also use the ICSP serial interface built into each PIC Microcontroller for programming and even do programming while it's still plugged into the circuit!

You can either program a PIC microcontroller using assembler or a high level language and I recommend using a high level language such as C as it is much easier to use (after an initial learning curve). Once you have learned the high level language you are not forced to use the same processor e.g. you could go to an AVR or Dallas microcontroller and still use the same high level language.

Input / Output - I/O

A PIC Microcontroller can control outputs and react to inputs e.g. you could drive a relay or read input buttons.

With the larger devices it's possible to drive LCDs or seven segment displays with very few control lines as all the work is done inside the PIC Micro.

Comparing a frequency counter to discrete web designs you'll find two or three chips for the microcontroller design and ten or more for a discrete design. So using them saves prototype design effort as you can use built in peripherals to take care of lots of the circuit operation.

Many now have a built in ADC so you can read analogue signal levels so you don't need to add an external devices e.g. you can read an LM35 temperature sensor directly with no interface logic.

Peripherals

The PIC microcontroller has many built in peripherals and this can make using them quite daunting at first which is why I have made this introductory page with a summary of each major peripheral block.

At the end is a short summary of the main devices used in projects shown on this site.

The best way to start is to learn about the main features of a chip and then begin to use each peripheral in a project. I think learning by doing is the best way.

PIC microcontroller
Feature
PIC microcontroller
feature description
Flash memory Re-programmable program storage.
RAM Memory storage for variables.
EEPROM Long term stable memory : Electrically Erasable Programmable Read Only Memory.
I/O ports High current Input/Output ports (with pin direction change).
Timers/Counters Typically 3.
USART Built in RS232 protocol (only needs level translator chip).
CCP Capture/Compare/PWM module.
SSP I2C and SPI Interfaces.
Comparator An analogue comparator and internal voltage reference.
ADC Analogue to digital converter.
PSP
Parallel Slave Port (for 8 bit microprocessor systems).
LCD LCD interface.
Special features
ICSP,WDT,BOR,POR,PWRT,OST,SLEEP
ICSP Simple programming using In Circuit Serial Programming.

Note:these are some of the main features
(some chips have all of these and some don't).

Flash memory

This is the program storage area and gives you the most important benefit for using a PIC microcontroller - You program the device many times. Since when does anyone get a program right first time ?

Devices used in projects on this site can be re-programmed up to 100,000 times (probably more) as they use Flash memory - these have the letter F in the part name. You can get cheaper (OTP) devices but these are One-Time-Programmable; once programmed you can't program it again!

ICSP

In Circuit Serial Programming (ICSP) is the next most important benefit. Instead of transferring your chip from the programmer to the development board you just leave it in the board. By arranging the programming connections to your circuit correctly you won't need to remove the chip!

You can re-program the device while it's still in the circuit so once your programmer is setup you can leave it on the bench and test your programs without moving the chip around and it makes the whole process much easier.

I/O Ports

Input / Output ports let you communicate with the outside world so you can control leds, LCDs or just about anything with the right interface. You can also set them as inputs to gather information.

Pin direction

Most PIC microcontroller pins can be set as an input or and output and this can be done on the fly e.g. for a dallas 1 wire system a pin can be written to generate data and read at a later stage. The TRIS register controls the I/O direction and setting a bit in this register to zero sets the pin as output while setting it as one sets the pin as input.

This allows you to use a pin for multiple operations e.g. the Real Time clock project uses RA0, the first pin of PORTA, to output data to a seven segment display and at a later point in the program read the analogue value as an input.

Current

The PIC I/O ports are high current ports capable of directly driving LEDs (up to 25ma output current) - the total current allowed usually ~200mA this is often for the whole chip (or specified for several ports combined together).

Timer / Counters

Each PIC microcontroller has up to three timers that you can either use as a timer or a counter (Timer 1 & 2) or a baud clock (Timer 2).

Timer 0


The original timer: Timer 0 was the first timer developed and you can find it in all the earliest devices e.g. 16F84 up to the most current e,g, 16F877A.

It is an 8 bit timer with an 8 bit prescaler that can be driven from an internal (Fosc/4) or external clock. It generates an interrupt on overflow when the count goes from 255 to zero.

Timer 0 always synchronizes the input clock (when using external clock).

Note: You can read and write timer 0 but you can not read the prescaler.

Note: The prescaler changes its effect depending on whether it is a timer prescaler or a watch dog prescaler - so the same prescaler setting may prescale by 2 or by 1 depending on its use!

Timer 1

This is a 16 bit timer that generates an overflow interrupt when it goes from 65535 to zero. It has an 8 bit programmable prescaler and you can drive it from the internal clock (Fosc/4) or an external pin.

To eliminate false triggering it also has an optional input synchronizer for external pin input.

This timer can be used in sleep mode and will generate a wakeup interrupt on overflow.

Timer 1 is also read by the CCP module to capture an event time.

Note: Using this timer in sleep mode will use more current.

In addition it can be used to drive a low power watch crystal. This is something that sounds good but I don't recommend you do it as watch crystals are extremely difficult to drive correctly. You should only use it if you are going to make a pcb and follow all the guidelines in making it noise free. I used a DS1307 in the Real Time clock project which drives the crystal directly but even this is difficult to get operating accurately.

Timer 2

This is an 8 bit timer with an 8 bit prescaler and an 8 bit postscaler. It takes its input only from the internal oscillator (Fosc/4).

This timer is used for the timebase of a PWM when PWM is active and it can be software selected by the SSP module as a baud clock.

It also has a period register that allows easy control of the period. When timer 2 reaches the PR2 register value then it resets. This saves having to check the timer value in software and then reset the timer and since it is done in hardware the operation is much faster - so you can generate fast clocks with periods that are multiples of the main clock.

USART

The USART is a useful module and saves having to code up a software version so it saves valuable program memory. You can find more information on RS232 here and how to make it work. Look here for pin outs.

All you need to interface it to a PC serial port is a MAX232 chip (or equivalent).

Note: An equivalent MAX232 chip is the SP202ECP that has the same pinout as the MAX232 but lets you use 100nF capacitors - so you don't need the large 1uF caps.

Baud Rates

You have to be careful using the baud rates as they depend on the main clock in use and normal oscillator values in general do not fit very well with 'real' baud rates.

There is a table of baud rates in microchip data sheet DS33023A which indicates the expected percentage error for a specific clock rate and in general the higher the main clock the lower the error.

You sometimes have to play around with the register settings to get a better fit with your clock rate and the baud rate you want. An example is for an 8MHz clock - if you use BRGH=1 and an 8MHz clock (see the 16F88 datasheet) you get accurate baud rates up to 38.4kbaud. You have to force this to work e.g. in mikroC the built in USART routines use BRGH=0 so at 8MHz the baud rate is only accurate to 9.6kbaud.

If you want a super-accurate baud rate the best way is to use a clock crystal that ends up giving you that baud rate i.e. work back through the baud rate equations to find the crystal you need.

CCP

The Capture/Compare/PWM module has three modes of operation:
  • Capture - Capture the time of an event.
  • Compare - Generate an output when Timer 1 reaches a value.
  • PWM - Pulse Width Modulation.

Capture

Capture mode is used to capture the value of Timer 1 when a signal at the CCP pin goes high (or low depending on how the CCP is set up). The CCP can accurately capture the arrival time of a signal at the CCP pin so it can be used for pulse time measurement.

Compare

Compare mode is used to generate an output when Timer 1 reaches a value you put into CCPR1. One special event trigger mode lets you start the ADC when the compare mode triggers.

PWM

PWM gives you one Pulse Width Modulation output with 10 bit resolution and with no software overhead - once started it operates all by itself unless you want to change the duty cycle.

It uses Timer 2 to define its operation using Timer 2 period register to define the frequency of the PWM.

Note: The duty cycle is not a percentage it is the number of periods of the PWM clock that the output is high!

SSP

The Synchronous Serial Port lets you communicate with devices that use either the SPI (Serial Peripheral Interface) or I2C (Inter IC communication) protocols. Note that for full Master mode I2C operation you need to choose a PIC device that has the MSSP device (Master Synchronous Serial Port).

SPI and I2C are shared so you can only use one at a time (or you could use the I2C bit banged routines in the Real Time Clock project to have both at the same time).

You can find a project that uses I2C here and you can find more information on I2C here.

Comparator and comparator voltage reference

The comparator is module that has two analogue comparators which can be set up in one of 8 different ways. Either digital or analogue inputs can be compared to reference voltages.

In one mode an internally generated voltage reference is used as an input to both comparators and in the same mode multiplexing lets you monitor up to four different input pins.

You can even send the output of the comparator to a pin so that it is used independently from the microcontroller e.g. in a circuit where you need a comparator you don't need an extra chip!

The analogue level must be between Vdd and Vss as protection diodes won't allow anything else.

The module will generate an interrupt if the comparator output changes.

You can use it in sleep mode and the interrupt will wake it up.

The source impedance of the analogue signal must be smaller than 10k.

ADC

The single 10 bit Analogue to Digital Converter can have up to 8 inputs for a device multiplexed from input pins.

The ADC can be used during sleep but you have to use the RC clock mode. One benefit of this is that there will be no digital switching noise so you will get better conversion accuracy.

For the 16F877A you can not just choose to use an analogue input if you feel the need as there are only a specific and limited number of ways that the analogue input pins can be enabled. It is best to start with AN0 and add more as necessary - see the datasheet for which analogue inputs can be enabled e.g. if you started a design using only AN5 you would find that you may have to enable a few more analogue inputs as well!

The 16F675 can measure 4 analogue input pins!

PSP

The Parallel Slave Port lets you to connect the PIC microcontroller directly into a microprocessor system. It provides an 8 bit read/write data bus and RD (read) WR (write) and CS (chip select) inputs - all active low.

This will let you add a PIC microcontroller to a system so that the PIC microcontroller can be treated as a memory mapped peripheral. It will let the microcontroller behave just as though it was another microprocessor building block e.g. some memory or ram but in this case you have full control over exactly what the building block is i.e. you can re-program the PIC microcontroller to do just about anything.

This provides an easy route to adding a PIC microcontroller to an 8 bit system that already exists.

LCD

The LCD interface lets you directly interface to an LCD saving you having to use an LCD module such as the HD44780. I have not used this feature as it is another commercial requirement where removing a chip (HD44780) saves money in a production run. I think it is capable of driving a graphic LCD.

Special Features

ICSP In Circuit Serial Programming click here (jumps to ICSP section).
WDT Watch dog timer This is a software error protector.
BOR Brown Out reset This detects if the power supply dips slightly and resets the device if so.
POR Power on reset This starts microcontroller initialization.
PWRT PoWeR up Time A time delay to let Vdd rise.
OST Oscillator start up timer Wait for 1024 cycles after PWRT.
SLEEP PIC microcontroller sleep mode Enter low power mode.

WDT

If your software goes haywire then this timer resets the processor. To stop the reset the well behaved software must periodically issue the CLRWDT instruction to stop a resert. The WDT runs using its own oscillator. It runs during sleep and shares Timer 0 prescaler.

POR

Power On Reset starts PIC microcontroller initialization when it detects a rising edge on MCLR.

PWRT

If you enable this then 72ms after a POR the PIC microcontroller is started.

OST

Oscillator Startup Timer delays for 1024 oscillator cycles after PWRT (if PWRT is enabled) ensuring that the oscillator has started and is stable. It is automatic and only used for crystal oscillator modes and is active after POR or wake from sleep.

SLEEP

Sleep mode (or low power consumption mode) is entered by executing the 'SLEEP' command. The device can wake from sleep caused by an external reset, Watch Dog Timer timeout, INT pin RB port change or peripheral interrupt.

Project device overview

This site mainly uses three PIC devices out of the hundreds of different chips that microchip produces. This does not sound like a lot but you can use the devices in almost any project and they have so many built in peripherals that you can make hundreds of projects with them.

The other microchip devices are all useful in different situations - perhaps they have more memory or different peripherals - this is useful if you want to tailor your designs to the system you build - but probably more useful in a commercial environment where every cent counts in a production run.

All three devices are extremely powerful and the main difference is that they have different numbers of pins and memory size.

Note: There are differences in using the devices i.e. there are some registers that are different but in the generally you can interchange them - this is made easier using a high level language.

The devices used in this site are:

PIC microcontroller Device PIC microcontroller No. Pins PIC microcontroller Flash memory WORDS
12F675 8 1k
16F88 18 4k
16F877A 40 8k

Note : When looking at the microchip site the memory size is kwords - ignore kbytes - you need the kword size as this is what each instruction occupies - the kbyte size is for comparison to other types of micros (probably). But the microcontroller data bus is 8 bits wide so it is an 8 bit microcontroller (different program memory and data memory due to using Harvard architecture).

(Note: that all of them have the letter F in - this means it is a Flash re-programmable part - don't go and buy a part with O in as its OTP - programmable only once! - only do that if you are really really sure it's the final design).

PIC Microcontroller Flash Memory size

You may think that 1k or even 8k is so tiny that it won't be useful but each PIC microcontroller uses RISC (Reduced Instruction Set Computing) which simply means that it has a cleverly arranged instruction set that only has a few instructions. The mid range parts have 35 instructions.

If you use the high level language as recommended in this site then you won't need to be too aware of the instruction set it just means you can do a lot with a small amount of memory. Most of the projects on this site although they are fully working projects fit within 2k words!

Note: If you need more memory you can always move to the 18F series of PIC microcontrollers. Another option is to add an I2C serial eprom.

PIC microcontroller RAM and EEPROM size

The PIC microcontroller RAM size is also important as it stores all your variables and intermediate data.

Note: You can usually alter the program to use less RAM by choosing the right variable sizes or changing how your program works

For example don't use floating point alter it to use a different variable type e.g. you can use long integers with fixed point operation to avoid floating point.

PIC microcontroller EEROM : Electrically Erasable ROM is used to store data that must be saved between power up and power down.

This area is readable and writable and has a much longer life than the main program store i.e. it has been designed for more frequent use.

Building a Digital Thermometer

Now that you understand a little bit about your Stamp and the LCD, we can add another component and create a digital thermometer. To create a thermometer, we will use a chip called the DS1620. This chip contains:

  • A temperature-sensing device
  • An analog-to-digital (A/D) converter for the temperature-sensing device
  • A shift register to read the data out of the A/D converter
  • A little EEPROM (electrically erasable programmable read-only memory) to remember settings

The DS1620 has two modes: In one mode, it acts as a stand-alone thermostat chip, and in the other mode you hook it up to a computer and use it as a thermometer. The EEPROM remembers the current mode as well as the set temperatures for the thermostat.

Hooking up the DS1620 to the Stamp is very easy. The DS1620 comes in an 8-pin chip. Supply +5 volts from the Stamp to pin 8 of the DS1620. Supply ground to pin 4 of the DS1620. You then use three I/O pins from the Stamp to drive three pins on the DS1620:

  • Pin 1 on the DS1620 is the data pin. You read and write data bits on this pin.
  • Pin 2 on the DS1620 is the clock pin. You clock data in and out of the shift register with this pin.
  • Pin 3 on the DS1620 is the reset/select pin. You set pin 3 high to select the chip and communicate with it.
For this example code, it is assumed that:
  • The data pin goes to I/O pin 2 on the Stamp.
  • The clock pin goes to I/O pin 1 on the Stamp.
  • The reset/select pin goes to I/O pin 0 on the Stamp.
The completed wiring looks like this:


You can get a DS1620 either from Jameco (part number 146456) or Parallax (part number 27917) in an "application kit" that includes the chip, the capacitor, some good documentation and sample code. Or you can buy the chip on its own from Jameco (part number 114382). I would suggest getting the application kit the first time you try using the DS1620 because the documentation is very useful.

You can assemble the DS1620 in the prototype area of the Stamp carrier board or on a separate breadboard. Once you have assembled it, hook your LCD display up to I/O pin 3 of the Stamp, and then load and run the following program:

symbol RST = 0 ' select/reset line on 1620
symbol CLK = 1 ' clock line for shift registers on 1620
symbol DQ = 2 ' data line on 1620
symbol DQ_PIN = pin2 ' pin representation for DQ
symbol LCD = 3 ' data line for LCD

begin:
low RST ' deselect the 1620 unless talking to it
high CLK ' clock pin on 1620 should default high
pause 1000 ' wait for the thermometer and LCD to boot

setup:
high RST ' select the 1620
b0 = $0C ' $0c is the 1620 command byte
' saying "Write Config"
gosub shift_out ' send it to the 1620
b0 = %10 ' %10 is the 1620 command byte
' to set thermometer mode
gosub shift_out ' send it to the 1620
low RST ' deselect the 1620
pause 50 ' delay 50ms for EEPROM

start_convert:
b0 = $EE ' $EE is the 1620 command byte
' to start conversions
high RST ' select the 1620
gosub shift_out ' send it to the 1620
low RST ' deselect the 1620

' This is the main loop
' - reads and displays temperature every second
main_loop:
high RST ' select the 1620
b0 = $AA ' $AA is the 1620 command byte
' for reading temperature
gosub shift_out ' send it to the 1620
gosub shift_in ' read the temperature
' from the 1620
low RST ' deselect the DS1620.
gosub display ' display the temp in degrees C
pause 1000 ' wait a second
goto main_loop

' The shift_out subroutine sends whatever is in
' the b0 byte to the 1620
shift_out:
output DQ ' set the DQ pin to
' output mode
for b2 = 1 to 8
low CLK ' prepare to clock the bit
' into 1620
DQ_PIN = bit0 ' Send the data bit
high CLK ' latch data bit into 1620
b0 = b0/2 ' shift all bits right
' toward bit 0
next
return

' The shift_in subroutine gets a 9-bit
' temperature from the 1620
shift_in:
input DQ ' set the DQ pin to
' input mode
w0 = 0 ' clear w0
for b5 = 1 to 9
w0 = w0/2 ' shift input right.
low CLK ' ask 1620 for next bit
bit8 = DQ_PIN ' read the bit
high CLK ' toggle clock pin
next
return

' Displays the temperature in degrees C
display:
if bit8 = 0 then pos ' if bit8=1
' then temp is negative
b0 = b0 &/ b0 ' invert b0 by NANDing it
' with itself
b0 = b0 + 1
pos:
serout LCD, n2400, (254, 1) ' clear the LCD
serout LCD, n2400, ("Temp = ") ' display "Temp="
' on the display
bit9 = bit0 ' save the half degree
b0 = b0 / 2 ' convert to degrees
if bit8 = 1 then neg ' see if temp is negative
serout LCD, n2400, (#b0) ' display positive temp
goto half
neg:
serout LCD, n2400, ("-", #b0)' display negative temp
half:
if bit9 = 0 then even
serout LCD, n2400, (".5 C") ' display the half degree
goto done
even:
serout LCD, n2400, (".0 C") ' display the half degree
done:
return
If you run this program, you will find that it displays the centigrade temperature with an accuracy of one-half degree.

The DS1620 measures temperatures in centigrade half-degrees. It returns the temperature in a 9-bit 2s-complement number with a range of -110 to 250 F (-55 to 125 C). You divide the number you receive by 2 to get the actual temperature. 2s-complement binary numbers are a convenient way to represent negative values. The following list shows the values for a 4-bit 2s-complement number:

    0111 : 7
    0110 : 6
    0101 : 5
    0100 : 4
    0011 : 3
    0010 : 2
    0001 : 1
    0000 : 0
    1111 : -1
    1110 : -2
    1101 : -3
    1100 : -4
    1011 : -5
    1010 : -6
    1001 : -7
    1000 : -8

­ You can see that instead of the 4 bits representing values from 0 to 15, the 4 bits in a 2s-complement number represent the values -8 to 7. You can look at the left-most bit to determine if the number is negative or positive. If the number is negative, you can invert the bits and add 1 to get the positive representation of the number.

Here's what goes on with the digital thermometer program shown here:

  1. It uses the symbol keyword to set up several constants that make the program slightly easier to read (and also make it easy for you to move the chip to different I/O pins on the Stamp).

  2. It sets the CLK and RST pins on the DS1620 to their expected values.

  3. It writes a command byte to the EEPROM on the DS1620 to tell the chip to operate in "thermometer mode." Because the mode is stored in EEPROM, you only have to do it once, so you could technically take this section of the code out of the program after you run the program once (to save program space).

  4. The program sends the command $EE ("$" means "hexadecimal number" -- $EE is 238 in decimal) to tell the thermometer to start up its conversion process.

The program then enters a loop. Every second, it sends a command to the DS1620 telling the DS1620 to return the current temperature, and then it reads the 9-bit value that the DS1620 returns into the w0 variable. The Stamp sends and receives data 1 bit at a time by toggling the CLK line on the DS1620. Remember that the w0 (16-bit) variable overlays the b0/b1 (8-bit) variables, which overlay the bit0/bit1/.../bit15 (1-bit) variables, so when you insert a bit from the DS1620 into bit 8 and divide w0 by 2, what you are doing is shifting each bit to the right to store the 9-bit temperature from the DS1620 into w0. Once the temperature has been saved in w0, the display subroutine determines whether the number is positive or negative and displays it appropriately on the LCD as a centigrade temperature. The conversion from degrees C to degrees F is:

    dF = dC * 9/5 + 32

At this point, we have succeeded in creating an extremely expensive thermometer. What might you do with it? Here's one idea. Let's say you work for a drug company and you are shipping expensive drugs across the country that MUST remain at a certain temperature the entire way or the drugs will spoil. What you can do with a Stamp is create a data logging thermometer. Both Jameco (part number 143811) and Parallax (part number 27960) sell a device called the "RAM Pack module." It contains a low-power 8-kilobyte (or optionally 32-kilobyte) RAM chip with a serial interface. You could add this component (or something similar) to your Stamp and write code that saves temperature readings to the RAM every minute. You could then slip your Stamp into the drug shipment, and at the other end of the trip retrieve the Stamp. The RAM module would contain the temperature history of the entire trip and you would know whether or not the drugs ever thawed out.

There are all kinds of neat, useful devices like this that you can build with a Stamp now that you know how microcontrollers work!

For more information on microcontrollers and related topics, check out the links on the next page.

Creating a Really Expensive Digital Clock

Spending $79 to flash an LED may seem extravagant to you. What you would probably like to do is create something useful with your BASIC stamp. By spending about $100 more you can create a really nice digital clock! This may seem extremely extravagant, until you realize that the parts are reusable in a variety of other projects that you may want to build later.

Let's say that we would like to use the I/O pins on the BASIC Stamp to display numeric values. In the digital clock article, we saw how to interface to a 7-segment LED display using a 7447 chip. 7447s would work just as well with the BASIC Stamp. You could wire four of the I/O pins straight into a 7447 and easily display a number between 0 and 9. Since the BS-1 Stamp has eight I/O pins, it is easy to drive two 7447s directly like this.

For a clock, we need a minimum of four digits. To drive four 7447s with eight I/O pins, we have to be slightly more creative. The following diagram shows you one approach:


In this diagram, the eight I/O lines from the Stamp enter from the left. This approach uses four lines that run to all four 7447s. Then the other four lines from the Stamp activate the 7447s in sequence ("E" on the chips means "Enable" -- on a 7447, that would be the blanking input on pin 5). To make this arrangement work, the BASIC program in the Stamp would output the first digit on the four data lines and activate the first 7447 by toggling its E pin with the first control line. Then it would send out the value for the second digit and activate the second 7447, sequencing through all four of the 7447s like this repeatedly. By wiring things slightly differently, you could actually do this with only one 7447. By using a 74154 demultiplexer chip and some drivers, you could drive up to 16 digits using this approach.

This is, in fact, a standard way to control LED displays. For example, if you have an old LED calculator, turn it on and shake it while watching the display. You will actually be able to see that only one digit is ever illuminated at once. The approach is called multiplexing the display.

While this approach works fine for clocks and calculators, it has two important problems:

  • LEDs consume a lot of power.
  • 7-segment LEDs can only display numeric values.

An alternative approach is to use an LCD screen. As it turns out, LCDs are widely available and can be easily hooked to a Stamp. For example, the two-line by 16-character alphanumeric display shown below is available from both Jameco (part number 150990) and Parallax (part number 27910). A typical display is shown here, mounted on a breadboard for easier interfacing:



This sort of LCD has several advantages:

  • The display can be driven by a single I/O pin. The display contains logic that lets a Stamp communicate with it serially, so only one I/O pin is needed. In addition, the SEROUT command in Stamp BASIC handles serial communication easily, so talking to the display is simple.
  • The LCD can display alphanumeric text: letters, numbers and even custom characters.
  • The LCD consumes very little power -- only 3 milliamps.
The only problem is that one of these displays costs $59. Obviously, you would not embed one of these in a toaster oven. If you were designing a toaster oven, however, you would likely prototype with one of these displays and then create custom chips and software to drive much cheaper LCDs in the final product.

To drive a display like this, you simply supply it with +5 volts and ground (the Stamp supplies both from the 9-volt battery) and then hook one of the I/O pins from the Stamp to the display's input line. The easiest way I have found to connect the Stamp's I/O pins to a device like an LCD is to use a wire-wrap tool (Jameco part number 34577) and 30-gauge wire wrap wire (Jameco part number 22541 is typical). That way, no soldering is involved and the connections are compact and reliable.

The following BASIC program will cause a BASIC Stamp to behave like a clock and output the time on the LCD (assuming the LCD is connected to I/O pin 0 on the Stamp):

pause 1000                 'wait for LCD display to boot
serout 0, n2400, (254, 1) 'clear the display
serout 0, n2400, ("time:") 'Paint "time:" on the display
'preset before loading program
b0 = 0 'seconds
b1 = 27 'minutes
b2 = 6 'hours

again:
b0 = b0 + 1 'increment seconds
if b0 < 60 then minutes
b0 = 0 'if seconds=60
b1 = b1 + 1 ' then increment minutes
minutes:
if b1 < 60 then hours
b1 = 0 'if minutes=60
b2 = b2 + 1 ' then increment hours
hours:
if b2 < 13 then show
b2 = 1 'if hours=13 reset to 1

show:
serout 0, n2400, (254, 135) 'position cursor on display,
'then display time
serout 0, n2400, (#b2, ":", #b1, ":", #b0, " ")
pause 950 'pause 950 milliseconds
goto again 'repeat

In this program, the SEROUT commands send data to the LCD. The sequence (254, 1) clears the LCD (254 is the escape character and 1 is the command to clear the screen). The sequence (254, 135) positions the cursor. The other two SEROUT commands simply send text strings to the display.

This approach will create a reasonably accurate clock. By tweaking the PAUSE statement you can get the accuracy to within a few seconds a day. Obviously, in a real clock you would like to wire up a push-button or two to make setting it easier -- in this program, you preset the time before you download the program to the Stamp.

While this approach is simple and works, it is not incredibly accurate. If you want better accuracy, one good approach would be to wire a real-time clock chip up to your Stamp. Then, every second or so, you can read the time from the chip and display it. A real-time clock chip uses a quartz crystal to give it excellent accuracy. Clock chips also usually contain date information and handle leap year correction automatically.

One easy way to interface a real-time clock to a stamp is to use a component called the Pocket Watch B.


Pocket Watch B Module


The Pocket Watch B is available from both Jameco (part number 145630) and Parallax (part number 27962). This part is about as big as a quarter and contains the clock chip, crystal and a serial interface so that only one I/O pin is necessary to communicate with it. This component costs about $30 -- again, not something you want to embed in a toaster oven, but easy to play with when constructing prototypes.

Playing with a BASIC Stamp

If you would like to play with a BASIC Stamp, it's very easy to get started. What you need is a desktop computer and a BASIC Stamp starter kit. The starter kit includes the Stamp, a programming cable and an application that you run on your desktop computer to download BASIC programs into the Stamp.

You can get a starter kit either from Parallax (the manufacturer) or from a supplier like Jameco (who should be familiar to you from the electronic gates and digital clock articles). From Parallax, you can order the BASIC Stamp D Starter Kit (part number 27202), or from Jameco you can order part number 140089. You will receive the Stamp (pictured below), a programming cable, software and instructions. The kit is $79 from both suppliers. Occasionally, Parallax runs a special called "We've Bagged the Basics" that also includes Scott Edward's Programming and Customizing the BASIC Stamp Computer.

Hooking up the Stamp is easy. You connect it into the parallel port of your PC. Then you run a DOS application to edit your BASIC program and download it to the Stamp. Here is a screenshot of a typical editor (in this case, the one from Scott Edward's book):



To run the program in this editor, you hit ALT-R. The editor application checks the BASIC program and then sends it down the wire to the EEPROM on the Stamp. The Stamp then executes the program. In this case, the program produces a square wave on I/O pin 3. If you hook up a logic probe or LED to pin 3 (see the electronic gates article for details), you will see the LED flash on and off twice per second (it changes state every 250 milliseconds because of the PAUSE commands). This program would run for several weeks off of a 9-volt battery. You could save power by shortening the time that the LED is on (perhaps it is on for 50 milliseconds and off for 450 milliseconds), and also by using the NAP instruction instead of PAUSE.

Programming the BASIC Stamp

You program a BASIC Stamp using the BASIC programming language. If you already know BASIC, then you will find that the BASIC used in a Stamp is straightforward but a little stripped-down. If you don't know BASIC, but you do know another language like C, Pascal or Java, then picking up BASIC will be trivial. If you have never programmed before, you probably want to go learn programming on a desktop machine first. Here is a quick rundown on the instructions available in Stamp BASIC. (For complete documentation, go to Parallax: BASIC Stamp Documentation.)

Standard BASIC instructions:

  • for...next - normal looping statement
  • gosub - go to a subroutine
  • goto - goto a label in the program (e.g. - "label:")
  • if...then - normal if/then decision
  • let - assignment (optional)
  • return - return from a subroutine
  • end - end the program and sleep

Instructions having to do with I/O pins:

  • button - read a button on an input pin, with debounce and auto-repeat
  • high - set an I/O pin high
  • input - set the direction of an I/O pin to input
  • low - set an I/O pin low
  • output - set the direction of an I/O pin to output
  • pot - read a potentiometer on an I/O pin
  • pulsin - read the duration of a pulse coming in on an input pin
  • pulsout - send a pulse of a specific duration out on an output pin
  • pwm - perform pulse width modulation on an output pin
  • reverse - reverse the direction of an I/O pin
  • serin - read serial data on an input pin
  • serout - write serial data on an output pin
  • sound - send a sound of a specific frequency to an output pin
  • toggle - toggle the bit on an output pin

Instructions specific to the BASIC Stamp:

  • branch - read a branching table
  • debug - send a debugging string to the console on the desktop computer
  • eeprom - download a program to EEPROM
  • lookdown - return the index of a value in a list
  • lookup - array lookup using an index
  • nap - sleep for a short time
  • pause - delay for the specified time
  • random - pick a random number
  • read - read a value from EEPROM
  • sleep - power down for the specified time
  • write - write data to EEPROM

Operations:

  • + - addition
  • - - subtraction
  • * - multiplication (low-word)
  • ** - multiplication (high-word)
  • / - division
  • // - mod
  • max - return maximum of 2 values
  • min - return minimum of 2 values
  • & - AND
  • | - OR
  • ^ - XOR
  • &/ - NAND
  • |/ - NOR
  • ^/ - XNOR

If statement logic:

  • =
  • <>
  • <
  • <=
  • >
  • >=
  • AND
  • OR

Variables

All variables in the BS-1 have pre-defined names (which you can substitute with names of your own). Remember that there are only 14 bytes of RAM available, so variables are precious. Here are the standard names:

  • w0, w1, w2...w6 - 16-bit word variables
  • b0, b1, b2...b13 - 8-bit byte variables
  • bit0, bit1, bit2...bit15 - 1-bit bit variables
Because there are only 14 bytes of memory, w0 and b0/b1 are the same locations in RAM, and w1 and b2/b3 are the same, and so on. Also, bit0 through bit15 reside in w0 (and therefore b0/b1 as well).

I/O pins
You can see that 14 of the instructions in the BS-1 have to do with the I/O pins. The reason for this emphasis is the fact that the I/O pins are the only way for the BASIC Stamp to talk to the world. There are eight pins on the BS-1 (numbered 0 to 7) and 16 pins on the BS-2 (numbered 0 to 15).

The pins are bi-directional, meaning that you can read input values on them or send output values to them. The easiest way to send a value to a pin is to use the HIGH or LOW functions. The statement high 3 sends a 1 (+5 volts) out on pin 3. LOW sends a 0 (Ground). Pin 3 was chosen arbitrarily here -- you can send bits out on any pin from 0 to 7.

There are a number of interesting I/O pin instructions. For example, POT reads the setting on a potentiometer (variable resistor) if you wire it up with a capacitor as the POT instruction expects. The PWM instruction sends out pulse-width modulated signals. Instructions like these can make it a lot easier to attach controls and motors to the Stamp. See the documentation for the language for details. Also, a book like Scott Edward's Programming and Customizing the BASIC Stamp Computer can be extremely helpful because of the example projects it contains.

Using Microcontrollers

In How Electronic Gates Work, you learned about 7400-series TTL devices, as well as where to buy them and how to assemble them. What you found is that it can often take many gates to implement simple devices. For example, in the digital clock article, the clock we designed might contain 15 or 20 chips. One of the big advantages of a microcontroller is that software -- a small program you write and execute on the controller -- can take the place of many gates. In this article, therefore, we will use a microcontroller to create a digital clock. This is going to be a rather expensive digital clock (almost $200!), but in the process you will accumulate everything you need to play with microcontrollers for years to come. Even if you don't actually create this digital clock, you will learn a great deal by reading about it.

The microcontroller we will use here is a special-purpose device designed to make life as simple as possible. The device is called a "BASIC Stamp" and is created by a company called Parallax. A BASIC Stamp is a PIC microcontroller that has been customized to understand the BASIC programming language. The use of the BASIC language makes it extremely easy to create software for the controller. The microcontroller chip can be purchased on a small carrier board that accepts a 9-volt battery, and you can program it by plugging it into one of the ports on your desktop computer. It is unlikely that any manufacturer would use a BASIC Stamp in an actual production device -- Stamps are expensive and slow (relatively speaking). However, it is quite common to use Stamps for prototyping or for one-off demo products because they are so incredibly easy to set up and use.

They are called "Stamps," by the way, because they are about as big as a postage stamp.

Parallax makes two versions of the BASIC Stamp: the BS-1 and the BS-2. Here are some of the differences between the two models:

Spec BS-1BS-2
RAM14 bytes26 bytes
EEPROM256 bytes2 kilobytes
Max program lengthabout 75 instructionsabout 600 instructions
Execution speed2,000 lines/sec4,000 lines/sec
I/O pins816


The specific BASIC Stamp we will be using in this article is called the "BASIC Stamp Revision D" (pictured below).



The BASIC Stamp Revision D is a BS-1 mounted on carrier board with a 9-volt battery holder, a power regulator, a connection for a programming cable, header pins for the I/O lines and a small prototyping area. You could buy a BS-1 chip and wire the other components in on a breadboard. The Revision D simply makes life easier.

You can see from the previous table that you aren't going to be doing anything exotic with a BASIC stamp. The 75-line limit (the 256 bytes of EEPROM can hold a BASIC program about 75 lines long) for the BS-1 is fairly constraining. However, you can create some pretty neat stuff, and the fact that the Stamp is so small and battery operated means that it can go almost anywhere.

What is a Microcontroller?

A microcontroller is a computer. All computers -- whether we are talking about a personal desktop computer or a large mainframe computer or a microcontroller -- have several things in common:

  • All computers have a CPU (central processing unit) that executes programs. If you are sitting at a desktop computer right now reading this article, the CPU in that machine is executing a program that implements the Web browser that is displaying this page.
  • The CPU loads the program from somewhere. On your desktop machine, the browser program is loaded from the hard disk.
  • The computer has some RAM (random-access memory) where it can store "variables."
  • And the computer has some input and output devices so it can talk to people. On your desktop machine, the keyboard and mouse are input devices and the monitor and printer are output devices. A hard disk is an I/O device -- it handles both input and output.

The desktop computer you are using is a "general purpose computer" that can run any of thousands of programs. Microcontrollers are "special purpose computers." Microcontrollers do one thing well. There are a number of other common characteristics that define microcontrollers. If a computer matches a majority of these characteristics, then you can call it a "microcontroller":

  • Microcontrollers are "embedded" inside some other device (often a consumer product) so that they can control the features or actions of the product. Another name for a microcontroller, therefore, is "embedded controller."

  • Microcontrollers are dedicated to one task and run one specific program. The program is stored in ROM (read-only memory) and generally does not change.

  • Microcontrollers are often low-power devices. A desktop computer is almost always plugged into a wall socket and might consume 50 watts of electricity. A battery-operated microcontroller might consume 50 milliwatts.

  • A microcontroller has a dedicated input device and often (but not always) has a small LED or LCD display for output. A microcontroller also takes input from the device it is controlling and controls the device by sending signals to different components in the device.

    For example, the microcontroller inside a TV takes input from the remote control and displays output on the TV screen. The controller controls the channel selector, the speaker system and certain adjustments on the picture tube electronics such as tint and brightness. The engine controller in a car takes input from sensors such as the oxygen and knock sensors and controls things like fuel mix and spark plug timing. A microwave oven controller takes input from a keypad, displays output on an LCD display and controls a relay that turns the microwave generator on and off.

  • A microcontroller is often small and low cost. The components are chosen to minimize size and to be as inexpensive as possible.

  • A microcontroller is often, but not always, ruggedized in some way.

    The microcontroller controlling a car's engine, for example, has to work in temperature extremes that a normal computer generally cannot handle. A car's microcontroller in Alaska has to work fine in -30 degree F (-34 C) weather, while the same microcontroller in Nevada might be operating at 120 degrees F (49 C). When you add the heat naturally generated by the engine, the temperature can go as high as 150 or 180 degrees F (65-80 C) in the engine compartment.

    On the other hand, a microcontroller embedded inside a VCR hasn't been ruggedized at all.

The actual processor used to implement a microcontroller can vary widely. For example, the cell phone shown on Inside a Digital Cell Phone contains a Z-80 processor. The Z-80 is an 8-bit microprocessor developed in the 1970s and originally used in home computers of the time. The Garmin GPS shown in How GPS Receivers Work contains a low-power version of the Intel 80386, I am told. The 80386 was originally used in desktop computers.

In many products, such as microwave ovens, the demand on the CPU is fairly low and price is an important consideration. In these cases, manufacturers turn to dedicated microcontroller chips -- chips that were originally designed to be low-cost, small, low-power, embedded CPUs. The Motorola 6811 and Intel 8051 are both good examples of such chips. There is also a line of popular controllers called "PIC microcontrollers" created by a company called Microchip. By today's standards, these CPUs are incredibly minimalistic; but they are extremely inexpensive when purchased in large quantities and can often meet the needs of a device's designer with just one chip.

A typical low-end microcontroller chip might have 1,000 bytes of ROM and 20 bytes of RAM on the chip, along with eight I/0 pins. In large quantities, the cost of these chips can sometimes be just pennies. You certainly are never going to run Microsoft Word on such a chip -- Microsoft Word requires perhaps 30 megabytes of RAM and a processor that can run millions of instructions per second. But then, you don't need Microsoft Word to control a microwave oven, either. With a microcontroller, you have one specific task you are trying to accomplish, and low-cost, low-power performance is what is important.

How Microcontrollers Work

Introduction to How Microcontrollers Work

Microcontrollers are hidden inside a surprising number of products these days. If your microwave oven has an LED or LCD screen and a keypad, it contains a microcontroller. All modern automobiles contain at least one microcontroller, and can have as many as six or seven: The engine is controlled by a microcontroller, as are the anti-lock brakes, the cruise control and so on. Any device that has a remote control almost certainly contains a microcontroller: TVs, VCRs and high-end stereo systems all fall into this category. Nice SLR and digital cameras, cell phones, camcorders, answering machines, laser printers, telephones (the ones with caller ID, 20-number memory, etc.), pagers, and feature-laden refrigerators, dishwashers, washers and dryers (the ones with displays and keypads)... You get the idea. Basically, any product or device that interacts with its user has a microcontroller buried inside.
In this article, we will look at microcontrollers so that you can understand what they are and how they work. Then we will go one step further and discuss how you can start working with microcontrollers yourself -- we will create a digital clock with a microcontroller! We will also build a digital thermometer. In the process, you will learn an awful lot about how microcontrollers are

PIC Programming With the Basics - Article 2

This is the second article of this tutorial series. Up to now, we have already finished basic arrangements of the project, as well as the coding. (We will be dealing about the coding in a separate article more deeply. Until we will use the previous coding part) now we have to do the compiling pert and the simulating part.

Step 1: After you have finished the coding part, we have to compile and see whether there are errors or not. For that you have to press the build project button (ctrl+F9).

The button is displayed in the picture. It will be compiled automatically when you press the button.

Build the Project

Then you have to wait until you get the result.

Step2: If the project compiled successfully, it will be displayed as in the above picture. If it wasn't there should be a problem some where of your project. Most probably in the coding. As you may have forgotten to put a semicolon or may be a wrong code. (We will discuss about these things later.)

If so you have to correct those errors until you are getting the successfully compiled programme. If so, now we have finished our first project. All we have to do is, run the project & get the out put.

Step3: We are going to use the Proteus 7 Software for this task. Just open the software. You will be given an interface as below.

Now you need to pick the devices to run the pragramme. Just click the pick button there and get the needed devices.

Step4: Pick a pic16f84, LogicProbe (Active) to see the out put. You can just type the devices you need to get, and then they will be appearing. Then just double click on top of them to get them in to your devices list. Finally just click "ok".

Step5: Now you have to arrange the devices as a circuit. Just click on the top of the name of the device (Example: pic16f84), and then place it on the right hand side area. Finally it should look like this.

Step6: Finally you need to load the ".hex" file in to your pic-microcontroller. For that, just double click on the top of the pic. Then a dialog box will be appearing.

Loading the ".hex" file

Set the clock frequency as 4MHz.As we made it to 4, when we were starting our programme.

Ok, that's all. Just click the OK button. Then our target is achieved. Just click the Play button at the bottom of the page. Then you can see the whole PortB of the pic is blinking. Although we have used only one logic state, whole the port should blink.

Anyway that's the end of the first task. Follow the other articles, if you wish to follow the other techniques too.

Thanks. Your Comments are highly appreciated. So please don't hesitate to post your comments.

Visit http://www.picbestsite.com for more details.Learn PIC programming from the basics.Figures were used frequently to demonstrate the facts easily.Download the needed software, materials freely. visit http://www.picbestsite.com

PIC Programming With the Basics - Article 1 (Assembly)

This article will helps you to develop the knowledge of your Assembly language, which is used to programme a pic. Example programmes, projects would be covered in the next articles.

PIC (16f) has only 35 instructions.35 means not that much. Every specific instruction would be done a specific task. The whole article is reserved to understand the tasks of the each and every instruction.

Notes!

Some PICs have slightly different instruction sets, but if you know the basics, you'll be able to handle the differences with just a little study.

Here there are some of the instruction were discriped. Take a look at them. We will use these instructions little later when we get in to, tutorials of Assembly language.

MOVLW

Example: MOVLW 07

Side effects: none

The W register is central to most programs. This instruction moves a constant into the W register.

MOVF, MOVWF

Examples:

MOVF temp,W

MOVF temp,F

MOVWF temp

Side effects: Sets or clears Z flag (MOVF); none (MOVWF)

These instructions allow you to move data between registers and the W register. The first example moves the value in register temp into W. The third example moves W into temp. The second example moves the value of temp into temp. At first, that seems pointless, but it sets the Z condition flags without disturbing anything else, so it is useful for conditional jumps. If the number moved is 0, the Z flag is set. Otherwise it is cleared.

While you can use a number for a register is more common & easy to name them using EQU.

For example:

temp equ 0×70

movlw 0×10

movwf temp

ADDWF, ANDWF, IORWF, SUBWF, XORWF

Example:

ADDWF temp,W

XORWF x,F

These instructions do the specified operation on the W register and another register of your choice. Add and subtract work as you'd expect. The logical AND, IOR (inclusive OR) and XOR functions are the classic boolean logic primitives.

The result can be placed in the W register or back in the original register as you wish. For example:

MOVLW 1 ; put 1 in W

ADDWF temp,F ; add 1 to temp, store in temp

; w still equals 1 here

ADDWF x,W ; W=x+W, x is unchanged

The subtraction operation always computes F-W, so be careful that you don't mean W-F. So if W contains 3 and x contains 10, performing a subtraction will result in 7.

To compute the two's compliment of a negative number, write the magnitude as a binary number. So for 7, we have 00000111. Then invert all the bits (11111000) and add 1 (11111001). You can easily reverse the process, so if I tell you the subtraction yields 0xF9, you can write it as binary (11111001), subtract 1 (11111000) and then invert the bits (00000111) to know that it means -7.

All the instructions in this section set the Z flag if their result is zero. Otherwise, the Z flag is cleared.

ADDLW, ANDLW, IORLW, SUBLW, XORLW

Example:

ADDLW .30

XORLW 0x80

These instruction act just like the normal add, subtract, and, inclusive or, and exclusive or instructions except they operate on a literal.

So:

ADDLW 2

adds 2 to W (and, of course, leaves the result in W). All the flags are modified just as they are in the register-based versions of these instructions (see above). The subtract instruction computes literal-W which is often confusing. So instead of writing:

SUBLW 2 ; computes 2-W

You probably meant to write:

ADDLW -2 ; This is probably what you really want

CLRF, CLRW

Example:

CLRF temp

CLRW

Side effect: Sets the Z flag to 1

It is a very common operation to load a zero into a register and this instruction can do that in one step. The CLRW instruction clears W, which is odd since MOVLW 0 will do this also

INCF, DECF

Example:

INCF temp,W

DECF x,F

Another common operation is to add or subtract 1 from a register. These instructions do that (INCF is +1; DECF is -1).

INCFSZ, DECFSZ

Example:

INCFSZ temp,W

DECFSZ x,F

These instructions are similar to INCF and DECF. They add or subtract one from the indicated register and store the result as directed. However, these instructions don't set the Z flag. Instead, if the result is zero, they skip the next instruction. This is useful, of course, for loops. Here's an example:

CLRF y

MOVLW .10 ;

MOVWF i ; i=10

MOVF x,W ; W=X

LOOP: ADDWF y,F ; Y=Y+X

DECFSZ i,F

GOTO LOOP

; Leave here with the answer in y

RLF, RRF

Example:

RLF temp,F

These instructions move the bits in the register left by one bit (RLF) or right (RRF).

This is often useful to manipulate bits, but there is another interesting property: shifting left multiplies a number by 2 and shifting right divides by 2! You can often combine this with adding to get easy multiplications. For example, suppose you want to compute y=10*x. Well, that is the same as y=8*x+2*x, right? So try this:

BCF status,C ; C=0

RLF x,F ; X=2*X

BCF status,C

RLF x,W ; W=2*X (so 4*X)

MOVWF temp

BCF status,C

RLF temp,W ; W=2*X (so 8*X)

ADDWF x,W ; W=8X+2X = 10X

MOVWF y

BCF, BSF

Example:

BCF status,Z

These instructions clear (BCF) or set (BSF) the indicated bit in a register. The bit may have a name (like Z) or you can use a number from 0 to 7 (0 is the least significant bit and 7 is the most significant). Sometimes you can use these to save a few instructions. For example, suppose you had written:

MOVLW 0x7F

ANDWF temp,F

You could replace this with a single BCF temp,7 instruction. Not only is this faster and takes less space, but it doesn't destroy the W register either!

GOTO

Example:

GOTO main

As you'd expect, the GOTO instruction forces your program to resume execution at the label you indicate. The instruction only holds an 11 bit address, so the top bits of the new program counter come from the PCLATH register.

RETLW

Example:

RETLW .99

RETLW is exactly like RETURN except that it loads a literal value into the W register before it returns.

RETFIE

Example:

RETFIE

This will Sets GIE

RETFIE is exactly like a return, but it also sets the global interrupt enable (GIE). When a hardware interrupt occurs, it clears GIE and executes what amounts to a CALL instruction. Using RETFIE allows you to enable interrupts and return to the main program all in one step. If you don't want interrupts enabled again, just execute a RETURN instead.

BTFSC, BTFSS

Example:

BTFSS temp,7

When you want to perform a conditional jump, you need one of these instructions. They test a bit and skip the next instruction if the bit is set (BTFSS) or clear (BTFSC). Most often the next instruction is a GOTO or a CALL, but it could be any single instruction. For example, this code tests temp to see if it is zero. If it is, it loads temp with 0×80. Otherwise, temp is unchanged:

MOVF temp,F ; set Z flag, no data really moved

BTFSC status,Z ; skip if not zero

BSF temp,7 ; since temp was 0, now it is 0x80!

CLRWDT

Example:

CLRWDT

This instruction informs the watchdog timer that your program is still executing.

***********************************************************

I know that the above description will not be helpful to you to carry on. We have to have the practical experience. So we will do some tutorials, based on Assembly language in future. Stay with us.

If there are any questions, feel free to ask.

Thanks (Admin).

Visit http://www.picbestsite.com for more details. Learn PIC programming from the basics.Figures were used frequently to demonstrate the facts easily. Download the needed software, materials freely. visit http://www.picbestsite.com

Is the PIC 16F84 Dead? - The Most Popular Microcontroller Of All Time

Is the 16F84 too old for your electronic projects?

If you don't know what a 16F84 is then you have never heard of Microchip(R) - a company that creates powerful stand alone microcontrollers. A microcontroller is simply a very small computer but unlike standard computing systems everything is contained within the device itself. There are no external peripherals such as RAM, EPROM, I/O devices.

If you are looking for an easy way to create your own projects then microcontrollers fit the bill because they:

  • Are very Small (some have 8 pins and even smaller have 5).
  • Have many internal peripherals.
  • Are based on reprogrammable internal memory
  • Have built in timers.
  • Have internal RAM.

In short they are ideal for controlling your projects -- all you have to do is program them.

This is one of the spectacular advantages over doing discrete designs since if you make a mistake in a discrete design you will have to debug and re-wire. With a microcontroller you can just re-program the device in circuit (having simulated the code to figure out the mistake first).

Even better is the fact that you can make advanced projects, because internally the peripherals operate quite fast e.g. you could create a 50MHz frequency counter using no external components (except a display).

Languages

In fact you can program them in many different languages but the most popular is machine code. The reason for it's popularity is the fact that MicroChip(R) created all the tools necessary for development of a machine code program for free so you will find many many examples of assembler code on the internet.

Personally I don't like machine coding in assembler (although I can use it if needed e.g. for speed) because it takes a huge amount of time compared to using a high level language. In fact I would say it takes 10 times as long with assembler. Also assembler is a totally unstructured language; meaning that it is very hard to maintain i.e. if you want to add a module then you probably have to review the whole of the code whereas with a high level language areas of code are protected saving you from making mistakes.

Microchip has released many hundreds of different devices (now vastly improved over the 16F84) but the fundamental operation of each one is based on the original design and even if you only studied the original 16F84 (OK there was a 16C84) you would have a pretty good idea of how all of the range of devices work.

That is the great power of the MicroChip(R) devices i.e. you learn something using one device and you are adding to your knowledge for the whole range - for instance to program a 12F675, 16F84, 16F88 or 16F877 you need to know only about ICSP because that interface is shared across the whole range. This means your learning curve is greatly reduced.

Of course there are some specialized peripherals that are for professional developers such as driving the pins of a dedicated LCD but you only need to concentrate on the standard peripherals (good examples are in the 12F675, 16F88, 16F628 and 16F877).

Peripherals

In fact there are about 15 standard internal peripherals for the modern (16F range) device whereas the 16F84 has only one.

This is why I believe that the 16F84 has had a good running but it's now time to say goodbye to it. Other reasons for this are that it has a quarter the memory size of a 16F88 and now costs about 5 times as much.

Note The 16F88 and 16F628 borrow heavily from the 16F84 even having the same pinout so you won't have any trouble if you are already used to a 16F84.

Summary

The 16F84 is probably too old for serious design because there are newer (backwards compatible) devices that will allow you to create far more capable projects.

John Main's website provides microcontroller resources and free projects which are fully documented and include schematics and source code.

You can find example of a 50MHz Seven segment here: Frequency counter circuit. This uses a 16F877 as the microcontroller.

Vist this site for more: http://www.best-microcontroller-projects.com