摘自:http://www.best-microcontroller-projects.com/pic-microcontroller.html
What can youdo with a microcontroller?
Answer: Virtually Any Project
Easily!...
Microcontrollers give you a
fantastic way of creating projects.
APIC
microcontroller is a processor with built in memory and RAM and youcan use it to control your projects (or build projects around it). Soit saves you building a circuit that has separateexternal RAM, ROM and peripheral chips.
What this really means for youis that you have a very powerfuldevice that has many useful built in modules e.g.
- EEPROM.
- Timers.
- Analogue comparators.
- UART.
|
Even with just these four modules (note these are just examplemodules - there are more) you can make up manyprojects e.g.:
* Frequencycounter - using the internal timers and reporting throughUART(RS232) or output to LCD.
* Capacitancemeter - analogue comparatoroscillator.
* Event timer- using internal timers.
* Event datalogger -capturing analogue data using an internal ADC andusing the internalEEPROM for storing data (using an external I2C for high data storagecapacity.
* Servocontroller (Control through UART) - using the internal PWMmodule or using a software created PWM.
The PIC Micro is one of the most popular
microcontrollers and in case you were wondering
the difference betweena microprocessor and a microcontroller is that a microcontroller has aninternal bus with in built memory and peripherals.
In fact the 8 pin (DIL) version of the 12F675has 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 externalcrystal).
- An analogue comparator.
- 1024 words of program memory.
- 64 Bytes of RAM.
- 128 Bytes of EEPROM memory.
- External interrupt (as well as interrupts frominternal 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!
Inthe mid-range devices the memory space ranges from 1k to 8k (18Fparts have more) - this does not sound like a lot but the processor hasan efficient instruction set and you can make useful projects even with1k e.g. LM35 temperaturesensing project that reports data to the
serial port easilyfits within 1k.
Features
Infact a PIC microcontroller is an amazingly powerful fully featuredprocessorwith internal RAM, EEROM FLASH memory and peripherals. One ofthesmallest ones occupies the space of a 555 timer but has a 10bit ADC, 1kof memory, 2 timers, high current I/O ports a comparator a watch dogtimer... I could go on as there is more!
Programming
Oneof the most useful features of a PIC microcontroller is that you canre-programthem as they use flash memory (if you choose a part with an F in thepart number e.g. 12F675 not 12C509). You can also use the ICSP serialinterface built into each PIC Microcontroller for programmingand even do programming while it's still plugged into thecircuit!
Youcan either program a PIC microcontroller using
assembler or a highlevel languageand I recommend using a highlevel language such as C as it is much easier to use (afteran initial learning curve). Once you have learned the highlevel language you are not forced to use the same processor e.g. youcould go to an AVR or Dallas microcontroller and still use the samehigh level language.
Input / Output- I/O
APIC Microcontroller can controloutputs and react to inputs e.g. you could drive a relay or read inputbuttons.
With the larger devices it's possible to drive LCDsor seven segmentdisplays with very few control lines as all the work is done inside thePIC Micro.
Comparinga frequencycounterto discrete web designs you'll find two or threechips for the microcontroller design and ten or more for a discretedesign. So using them saves prototype design effort as you can usebuilt 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 soyou don't need to add an external
devices e.g. you can read an LM35temperature sensordirectly with no interface logic.
Peripherals
The PICmicrocontroller has many built inperipherals and this can makeusing them quite daunting at first which is why I have made thisintroductory page with a summary of each major peripheral block.
At the end is a
short summary of the maindevices used in projects shown on this site.
The best way to start is to learn about the main features of a chip andthen begin to use each peripheral in a project. I thinklearning by doing is the best way.
PICmicrocontroller Feature |
PICmicrocontroller feature description |
Flash memory |
Re-programmableprogram storage. |
RAM |
Memorystorage for variables. |
EEPROM |
Longterm stable memory :Electrically ErasableProgrammable Read Only Memory. |
I/Oports |
HighcurrentInput/Output ports (with pin direction change). |
Timers/Counters |
Typically3. |
USART |
Builtin RS232 protocol (only needs leveltranslator chip). |
CCP |
Capture/Compare/PWMmodule. |
SSP |
I2Cand SPI Interfaces. |
Comparator |
An analoguecomparator and internal voltage reference. |
ADC |
Analoguetodigital converter. |
PSP |
ParallelSlave Port (for 8 bit microprocessor systems). |
LCD |
LCDinterface. |
Specialfeatures |
ICSP,WDT,BOR,POR,PWRT,OST,SLEEP |
ICSP |
Simpleprogramming using InCircuit SerialProgramming. |
Note:theseare some of the main features
(some chips have all of these and some don't).
Flashmemory
This is theprogram storage area and gives you the
most important benefitfor using a PIC microcontroller - Youprogram the device many times. Since when does anyone get a programright first time ?
Devicesused in projects on this site can be re-programmed upto
100,000times (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 youcan't program it again!
ICSP
In CircuitSerial Programming ( ICSP)is the
nextmost important benefit. Instead of transferring your chipfrom theprogrammer to the development board you just leave it in theboard. By arranging the programming connections to yourcircuit correctly you won't need to remove the chip!
You can
re-programthe devicewhile it's still
in thecircuit so once your programmer is setup youcan leave it on the bench and test your programs without moving thechip around and it makes the whole process much easier.
I/OPorts
Input/ Output ports let you
communicatewith the outside world so you cancontrol leds, LCDs or just about anything with the right interface. You can also set them as inputs to gather information.
Pindirection
Most PIC microcontroller pins can be set as aninput or and output andthis can be done on the fly e.g. for a dallas 1 wire system a pin canbe written to generate data and read at a later stage. The TRISregister controls the I/O direction and setting a bit in this registerto
zerosets the pin as
outputwhile setting it as
one sets thepinas
input.
This allows you to use a pin for multiple operations e.g. the RealTime clock projectuses RA0, the first pin of PORTA, to output data to a seven segmentdisplay and at a later point in the program read the analogue value asan input.
Current
The PIC I/O ports are high current ports capable ofdirectly driving LEDs (up to 25ma output current) - the
total currentallowed usually ~200mA this is often for the whole chip (or specifiedfor several ports combined together).
Timer/ Counters
EachPIC microcontroller has up to three timers that you can eitheruseas a timer or a counter (Timer 1 & 2) or a baud clock (Timer2).
Timer0
Theoriginal timer: Timer 0 was the first timer developed and you can findit 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 aninternal (Fosc/4)orexternal clock. It generates an interrupt on overflow whenthe count goes from 255 to zero.
Timer 0 always synchronizes the input clock (when using external clock).
Note: Youcan read and write timer 0 but you can not read the prescaler.
Note: The prescaler changes its effect depending on whether it is atimer prescaler or a watch dog prescaler - so the same prescalersetting may prescale by 2 or by 1 depending on its use!
Timer1
This is a 16 bit timer that generatesanoverflow interrupt when it goes from 65535 to zero. It hasan 8 bitprogrammable prescaler and you can drive it from the internalclock (Fosc/4) oran external pin.
To eliminate false triggering it also has an optional inputsynchronizer for external pin input.
This timer can be used in sleep mode and will generate a wakeupinterrupt on overflow.
Timer 1 is also read by the CCP module to capture an event time.
Note: Usingthis timer in sleep mode will use more current.
In additionit can be used to drive a low power watch crystal. This is something that sounds good but I don't recommend youdoit as watch crystals are extremely difficult to drive correctly. You should only use it if you are going to make a pcb andfollowall the guidelines in making it noise free. I used a DS1307 in the RealTimeclock project which drives the crystal directly but even thisis difficult to get operating accurately.
Timer2
Thisis an 8 bit timer with an 8 bit prescaler and an 8 bit postscaler. It takes its input onlyfrom the internal oscillator (Fosc/4).
This timer is used for the timebase of a PWM when PWM is active and itcan be software selected by the SSP module as a baud clock.
It also hasa 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 andthenreset the timer and since it is done in hardware the operation is muchfaster - so you can generate fast clocks with periods that aremultiples of the main clock.
USART
TheUSART is a useful module and saves having to code up a software versionso it saves valuable program memory. You can find moreinformation on RS232 hereand how to makeit work. Look herefor pin outs.
All you need to interface it to a PC serial port is a MAX232 chip (orequivalent).
Note: An equivalent MAX232 chip is the SP202ECP that has the same pinout asthe MAX232 but lets you use 100nF capacitors - so you don't need thelarge 1uF caps.
BaudRates
You have to be careful using the baud rates asthey depend onthe main clock in use and normal oscillator values in general do notfit very well with 'real' baud rates.
There is atable of baud rates in microchip data sheet DS33023A whichindicates the expected percentage error for a specific clock rate andin general the higher the main clock the lower the error.
Yousometimes have to play around with the register settings to get abetter fit with your clock rate and the baud rate you want. Anexample is for an 8MHz clock - if you use BRGH=1 and an 8MHz clock (seethe 16F88 datasheet) you get accurate baud rates up to 38.4kbaud. You have to force this to work e.g. in mikroC the built inUSART routines use BRGH=0 so at 8MHz the baud rate is only accurate to9.6kbaud.
If you wanta super-accurate baud rate the best way is to use a clockcrystal that ends up giving you that baud rate i.e. work back throughthe baud rate equations to find the crystal you need.
CCP
The Capture/Compare/PWM module has three modes ofoperation:
- 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 Timer1 when a signal at the CCP pin goes high (or low depending on how theCCP is set up). The CCP can accurately capture the arrivaltimeof a signal at the CCP pin so it can be used for pulse time measurement.
Compare
Compare mode is used to generate an output whenTimer 1 reaches a value you put into CCPR1. One special eventtrigger mode lets you start the ADC when the compare mode triggers.
PWM
PWM gives you one Pulse Width Modulation outputwith 10 bit resolution and with no software overhead - once started itoperates all by itself unless you want to change the duty cycle.
It uses Timer 2 to define its operation using Timer 2 period registerto define the frequency of the PWM.
Note: Theduty cycle is not a percentage it is the number of periods of the PWMclock that the output is high!
SSP
TheSynchronous Serial Port lets you communicatewith devices that use either the SPI (Serial Peripheral Interface) orI2C (Inter IC communication) protocols. Note that for fullMaster mode I2C operation you need to choose a PIC device that has theMSSP device (Master Synchronous Serial Port).
SPI and I2C are shared so you can only use one at a time (or you coulduse the I2C bit banged routines in the RealTime Clockproject to have both at the same time).
You can find a project that uses I2C hereand you canfind more information on I2C here.
Comparatorandcomparator voltage reference
The comparator is module that has two analoguecomparators which can be set up in one of 8 different ways. Eitherdigital or analogue inputs can be compared to reference voltages.
In one mode an internally generated voltage reference is used as aninput to both comparators and in the same mode multiplexing lets youmonitor up to four different input pins.
You can even send the output of the comparator to a pin so that it isused independently from the microcontroller e.g. in a circuitwhere you need a comparator you don't need an extra chip!
The analogue level must be between Vdd and Vss as protection diodeswon'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 sourceimpedance of the analogue signal must be smaller than 10k.
ADC
The single 10 bit Analogue to Digital Converter canhave 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 soyou will get better conversion accuracy.
For the16F877A you can not just choose to use an analogue input if you feelthe need as there are only a specific and limited number of ways thatthe analogue input pins can be enabled. It is best to startwith AN0 and add more as necessary - see the datasheet for whichanalogue inputs can be enabled e.g. if you started a design using onlyAN5 you would find that you may have to enable a few more analogueinputs as well!
The 16F675 can measure 4 analogue input pins!
PSP
The Parallel Slave Port lets you to connectthe 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 activelow.
This willlet you add a PIC microcontroller to a system so that the PICmicrocontroller can be treated as a memory mapped peripheral. It will let the microcontroller behave just as though it wasanother microprocessor building block e.g. some memory or ram but inthis case you have full control over exactly what the building block isi.e. you can re-program the PIC microcontroller to do just aboutanything.
This provides an easy route to adding a PIC microcontroller to an 8bit system that already exists.
LCD
The LCDinterface lets you directly interface to anLCD saving you having to use an LCD module such as the HD44780. I have not used this feature as it is another commercialrequirement where removing a chip (HD44780) saves money in a productionrun. I think it is capable of driving a graphic LCD.
SpecialFeatures
ICSP |
InCircuit Serial Programming |
click here(jumps toICSP section). |
WDT |
Watchdog timer |
Thisis a software error protector. |
BOR |
BrownOut reset |
Thisdetects if the power supply dips slightly and resets the device if so. |
POR |
Poweron reset |
Thisstarts microcontroller initialization. |
PWRT |
PoWeRup Time |
Atime delay to let Vdd rise. |
OST |
Oscillatorstart up timer |
Waitfor 1024 cycles after PWRT. |
SLEEP |
PICmicrocontroller sleep mode |
Enterlowpower mode. |
WDT
If your software goes haywire then this timerresets theprocessor. To stop the reset the well behaved software mustperiodically issue the CLRWDT instruction to stop a resert. The WDTruns using its own oscillator. It runs during sleep andshares Timer 0 prescaler.
POR
Power On Reset startsPIC microcontroller initialization when it detects a rising edge onMCLR.
PWRT
If you enable this then 72ms after a POR the PICmicrocontroller isstarted.
OST
Oscillator Startup Timer delays for 1024 oscillatorcycles after PWRT (if PWRT is enabled) ensuring that the oscillator hasstarted and is stable. It is automatic and only used forcrystal oscillator modes and is active after POR or wake from sleep.
SLEEP
Sleep mode (or low power consumption mode) isentered by executing the 'SLEEP' command. The device can wakefrom sleep caused by an external reset, Watch Dog Timer timeout, INTpin RB port change or peripheral interrupt.
Projectdeviceoverview
This sitemainly uses three PIC devicesout of the hundreds ofdifferent chips that microchip produces. This does not sound like a lotbut you can use the devices in almost any project and they have so manybuilt 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 usefulif you want to tailor your designs to the system you build - butprobably more useful in a commercial environment where every centcounts in a production run.
All three devices are extremely powerful and the maindifference is thatthey have different numbers of pins and memory size.
Note: Thereare differences in using the devices i.e. there are some registers thatare different but in the generally youcan interchange them - this is made easier using a high level language.
The devices used in this site are:
PICmicrocontroller Device |
PICmicrocontroller No. Pins |
PICmicrocontroller Flash memoryWORDS |
12F675 |
8 |
1k |
16F88 |
18 |
4k |
16F877A |
40 |
8k |
Note : Whenlooking 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 8bitmicrocontroller (different program memory and data memory due to usingHarvard architecture).
(Note: that all of them have the letter F in - this means it is a Flashre-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 sureit's the final design).
PICMicrocontroller Flash Memorysize
You may think that 1k or even 8k is so tiny that itwon't be useful but each PIC microcontroller uses RISC (ReducedInstruction Set Computing) which simply means that it has acleverly 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 youwon'tneed to be too aware of the instruction set it just means you can do alot with a small amount of memory. Most of the projects onthis site although they are fully working projects fit within2k words!
Note: If youneed more memory you can always move to the 18F series of PICmicrocontrollers. Another option is to add an I2C serialeprom.
PICmicrocontroller RAM and EEPROMsize
The PICmicrocontroller
RAM sizeis also importantas it stores allyour variables and intermediate data.
Note: You can usually alter theprogram to
use
less RAMby choosing the right variable sizes orchanging how your program works
For example
don'tuse floating point alter itto use a different variable type e.g. you can use long integers withfixedpoint operation to avoid floating point.
PICmicrocontroller EEROM : Electrically Erasable ROM is usedto storedata that must besaved between power up and power down.
This area is readableand writable and has a much longer life than the main program storei.e. it has been designed for more frequent use.