You are on page 1of 132

INTRODUCCION A LOS MICROCONTROLADORES

Los microcontroladores estn conquistando el mundo. Estn presentes en nuestro trabajo, en nuestra casa y en nuestra vida, en general. Se pueden encontrar controlando el funcionamiento de los ratones y teclados de los computadores, en los telfonos, en los hornos microondas y los televisores de nuestro hogar. Pero la invasin acaba de comenzar y el nacimiento del siglo XXI ser testigo de la conquista masiva de estos diminutos computadores, que gobernarn la mayor parte de los aparatos que fabricaremos y usamos los humanos.

Controlador y microcontrolador. Recibe el nombre de controlador el dispositivo que se emplea para el gobierno de uno o varios procesos. Por ejemplo, el controlador que regula el funcionamiento de un horno dispone de un sensor que mide constantemente su temperatura interna y, cuando traspasa los lmites prefijados, genera las seales adecuadas que accionan los efectores que intentan llevar el valor de la temperatura dentro del rango estipulado. Aunque el concepto de controlador ha permanecido invariable a travs del tiempo, su implementacin fsica ha variado frecuentemente. Hace tres dcadas, los controladores se construan exclusivamente con componentes de lgica discreta, posteriormente se emplearon los microprocesadores, que se rodeaban con chips de memoria y E/S sobre una tarjeta de circuito impreso. En la actualidad, todos los elementos del controlador se han podido incluir en un chip, el cual recibe el nombre de microcontrolador. Realmente consiste en un sencillo pero completo computador contenido en el corazn (chip) de un circuito integrado.

Un microcontrolador dispone normalmente de los siguientes componentes: Procesador o UCP (Unidad Central de Proceso). Memoria RAM para Contener los datos. Memoria para el programa tipo ROM/PROM/EPROM. Lneas de E/S para comunicarse con el exterior. Diversos mdulos para el control de perifricos (temporizadores, Puertas Serie y Paralelo, CAD: Conversores Analgico/Digital, CDA: Conversores Digital/Analgico, etc.). Generador de impulsos de reloj que sincronizan el funcionamiento de todo el sistema. El microcontrolador es en definitiva un circuito integrado que incluye todos los componentes de un computador. Debido a su reducido tamao es posible montar el controlador en el propio dispositivo al que gobierna. En este caso el controlador recibe el nombre de controlador empotrado (embedded controller).

Diferencia entre microprocesador y microcontrolador

El microprocesador es un circuito integrado que contiene la Unidad Central de Proceso (UCP), tambin llamada procesador, de un computador. La UCP est formada por la Unidad de Control, que interpreta las instrucciones, y el Camino de Datos, que las ejecuta.

Las patitas de un microprocesador sacan al exterior las lneas de sus buses de direcciones, datos y control, para permitir conectarle con la Memoria y los Mdulos de E/S y configurar un computador implementado por varios circuitos integrados. Se dice que un microprocesador es un sistema abierto porque su configuracin es variable de acuerdo con la aplicacin a la que se destine

Aplicaciones de los microcontroladores


Cada vez existen ms productos que incorporan un microcontrolador con el fin de aumentar sustancialmente sus prestaciones, reducir su tamao y coste, mejorar su fiabilidad y disminuir el consumo. Los microcontroladores estn siendo empleados en multitud de sistemas presentes en nuestra vida diaria, como pueden ser juguetes, horno microondas, frigorficos, televisores, computadoras, impresoras, mdems, el sistema de arranque de nuestro coche, etc. Y otras aplicaciones con las que seguramente no estaremos tan familiarizados como instrumentacin electrnica, control de sistemas en una nave espacial, etc. Una aplicacin tpica podra emplear varios microcontroladores para controlar pequeas partes del sistema. Estos pequeos controladores podran comunicarse entre ellos y con un procesador central, probablemente ms potente, para compartir la informacin y coordinar sus acciones, como, de hecho, ocurre ya habitualmente en cualquier PC.

Qu microcontrolador emplear?
A la hora de escoger el microcontrolador a emplear en un diseo concreto hay que tener en cuenta multitud de factores, como la documentacin y herramientas de desarrollo disponibles y su precio, la cantidad de fabricantes que lo producen y por supuesto las caractersticas del microcontrolador (tipo de memoria de programa, nmero de temporizadores, interrupciones, etc.): Costes. Como es lgico, los fabricantes de microcontroladores compiten duramente para vender sus productos. Y no les va demasiado mal ya que sin hacer demasiado ruido venden 10 veces ms microcontroladores que microprocesadores. Aplicacin. Antes de seleccionar un microcontrolador es imprescindible analizar los requisitos de la aplicacin: Procesamiento de datos, Entrada-salida, Consumo, Memoria, Ancho de palabra,

Arquitectura bsica
Aunque inicialmente todos los microcontroladores adoptaron la arquitectura clsica de von Neumann, en el momento presente se impone la arquitectura Harvard. La arquitectura de von Neumann se caracteriza por disponer de una sola memoria principal donde se almacenan datos e instrucciones de forma indistinta. A dicha memoria se accede a travs de un sistema de buses nico (direcciones, datos y control). La arquitectura Harvard dispone de dos memorias independientes una que contiene slo instrucciones y otra slo datos. Ambas disponen de sus respectivos sistemas de buses de acceso y es posible realizar operaciones de acceso (lectura o escritura) simultneamente en ambas memorias.

Los microcontroladores PIC responden a la arquitectura Harvard.

Recursos comunes a todos los microcontroladores

Al estar todos los microcontroladores integrados en un chip, su estructura fundamental y sus caractersticas bsicas son muy parecidas. Todos deben disponer de los bloques esenciales Procesador, memoria de datos y de instrucciones, lneas de E/S, oscilador de reloj y mdulos controladores de perifricos. Sin embargo, cada fabricante intenta enfatizar los recursos ms idneos para las aplicaciones a las que se destinan preferentemente.

Los principales recursos microcontroladores son:

especficos

que

incorporan

los

Temporizadores o Timers. Perro guardin o Watchdog. Proteccin ante fallo de alimentacin o Brownout. Estado de reposo o de bajo consumo. Conversor A/D. Conversor D/A. Comparador analgico. Modulador de anchura de impulsos o PWM. Puertas de E/S digitales. Puertas de comunicacin.

Herramientas para el desarrollo de aplicaciones

Uno de los factores que ms importancia tiene a la hora de seleccionar un microcontrolador entre todos los dems es el soporte tanto software como hardware de que dispone. Un buen conjunto de herramientas de desarrollo puede ser decisivo en la eleccin, ya que pueden suponer una ayuda inestimable en el desarrollo del proyecto.

Las principales herramientas de ayuda al desarrollo de sistemas basados en microcontroladores son:

Desarrollo del software:


Ensamblador. La programacin en lenguaje ensamblador puede resultar un tanto ardua para el principiante, pero permite desarrollar programas muy eficientes, ya que otorga al programador el dominio absoluto del sistema. Los fabricantes suelen proporcionar el programa ensamblador de forma gratuita y en cualquier caso siempre se puede encontrar una versin gratuita para los microcontroladores ms populares. Compilador. La programacin en un lenguaje de alto nivel (como el C) permite disminuir el tiempo de desarrollo de un producto. No obstante, si no se programa con cuidado, el cdigo resultante puede ser mucho ms ineficiente que el programado en ensamblador. Las versiones ms potentes suelen ser muy caras, aunque para los microcontroladores ms populares pueden encontrarse versiones demo limitadas e incluso compiladores gratuitos.

Depuracin
Simuladores. Son capaces de ejecutar en un PC programas realizados para el microcontrolador. Los simuladores permiten tener un control absoluto sobre la ejecucin de un programa, siendo ideales para la depuracin de los mismos. Placas de evaluacin. Se trata de pequeos sistemas con un microcontrolador ya montado y que suelen conectarse a un PC desde el que se cargan los programas que se ejecutan en el microcontrolador. Las placas suelen incluir visualizadores LCD, teclados, LEDs, fcil acceso a los pines de E/S, etc. El sistema operativo de la placa recibe el nombre de programa monitor.

Emuladores en circuito. Se trata de un instrumento que se coloca entre el PC anfitrin y el zcalo de la tarjeta de circuito impreso donde se alojar el microcontrolador definitivo. El programa es ejecutado desde el PC, pero para la tarjeta de aplicacin es como si lo hiciese el mismo microcontrolador que luego ir en el zcalo. Presenta en pantalla toda la informacin tal y como luego suceder cuando se coloque la cpsula.

LA FAMILIA DE LOS PIC COMO ELECCIN

Los PIC tienen ngel, tienen algo que fascina a los diseadores, puede ser la velocidad, el precio, la facilidad de uso, la informacin, las herramientas de apoyo... . Quizs un poco de todo eso es lo que produce esa imagen de sencillez y utilidad. Es probable que en un futuro prximo otra familia de microcontroladores le arrebate ese algo.

Los detalles ms importantes que vuelven locos a los profesionales de la microelectrnica y microinformtica y las razones de la excelente acogida que tienen los PIC son los siguientes: Sencillez de manejo: Tienen un juego de instrucciones reducido; 35 en la gama media. Buena informacin, fcil de conseguir y econmica. Precio: Su coste es comparativamente inferior al de sus competidores. Poseen una elevada velocidad de funcionamiento. Buen promedio de parmetros: velocidad, consumo, tamao, alimentacin, cdigo compacto, etc. Herramientas de desarrollo fciles y baratas. Muchas herramientas software se pueden recoger libremente a travs de Internet desde Microchip (http://www.microchip.com).

Existe una gran variedad de herramientas hardware que permiten grabar, depurar, borrar y comprobar el comportamiento de los PIC.

Diseo rpido. La gran variedad de modelos de PIC permite elegir el que mejor responde a los requerimientos de la aplicacin.
Una de las razones del xito de los PIC se basa en su utilizacin. Cuando se aprende a manejar uno de ellos, conociendo su arquitectura y su repertorio de instrucciones, es muy fcil emplear otro modelo.

Descripcin de las caractersticas ms representativas de los PIC


Arquitectura. La arquitectura del procesador sigue el modelo Harvard. En esta arquitectura, la CPU se conecta de forma independiente y con buses distintos con la memoria de instrucciones y con la de datos.

Segmentacin. Se aplica la tcnica de segmentacin (pipe-line) en la ejecucin de las instrucciones. La segmentacin permite al procesador realizar al mismo tiempo la ejecucin de una instruccin y la bsqueda del cdigo de la siguiente. De esta forma se puede ejecutar cada instruccin en un ciclo (un ciclo de instruccin equivale a cuatro ciclos de reloj).

Formato de las instrucciones. El formato de todas las instrucciones es de la misma longitud. Todas las instrucciones de los microcontroladores de la gama baja tienen una longitud de 12 bits. Las de la gama media tienen 14 bits y ms las de la gama alta. Esta caracterstica es muy ventajosa en la optimizacin de la memoria de instrucciones y facilita enormemente la construccin de ensambladores y compiladores.

Juego de instrucciones. Procesador RISC (Computador de Juego de Instrucciones Reducido). Los modelos de la gama baja disponen de un repertorio de 33 instrucciones, 35 los de la gama media y casi 60 los de la alta. Todas las instrucciones son ortogonales Cualquier instruccin puede manejar cualquier elemento de la arquitectura como fuente o como destino. Arquitectura basada en un banco de registros

Esto significa que todos los objetos del sistema (puertas de E/S, temporizadores, posiciones de memoria, etc.) estn implementados fsicamente como registros.

Diversidad de modelos de microcontroladores con prestaciones y recursos diferentes


La gran variedad de modelos de microcontroladores PIC permite que el usuario pueda seleccionar el ms conveniente para su proyecto.

Herramientas de soporte potentes y econmicas La empresa Microchip y otras que utilizan los PIC ponen a disposicin de los usuarios numerosas herramientas para desarrollar hardware y software. Son muy abundantes los programadores, los simuladores software, los emuladores en tiempo real, Ensambladores, Compiladores C, Intrpretes y Compiladores BASIC, etc.

Las gamas de PIC


Para resolver aplicaciones sencillas se precisan pocos recursos, en cambio, las aplicaciones grandes requieren numerosos y potentes. Siguiendo esta filosofa Microchip construye diversos modelos de microcontroladores orientados a cubrir, de forma ptima, las necesidades de cada proyecto. As, hay disponibles microcontroladores sencillos y baratos para atender las aplicaciones simples y otros complejos y ms costosos para las de mucha envergadura.

Microchip dispone de cuatro familias de microcontroladores de 8 bits para adaptarse a las necesidades de la mayora de los clientes potenciales.

La gama enana: PIC12C(F)XXX de 8 patitas

Se trata de un grupo de PIC que ha acaparado la atencin del mercado. Su principal caracterstica es su reducido tamao, al disponer todos sus componentes de 8 patitas. Se alimentan con un voltaje de corriente continua comprendido entre 2,5 V y 5,5 V, y consumen menos de 2 mA cuando trabajan a 5 V y 4 MHz. El formato de sus instrucciones puede ser de 12 o de 14 bits y su repertorio es de 33 o 35 instrucciones, respectivamente.

Aunque los PIC enanos slo tienen 8 patitas, pueden destinar hasta 6 como lneas de E/S para los perifricos porque disponen de un oscilador interno R-C.

MODELO

MEMORIA PROGRAMA

MEMORIA DATOS

FRECUENCIA MAXIMA

LINEAS E/S

AD C 8BITS

TEMPORIZADORE S

PATITA S

PIC12C508 PIC12C509

512x12 1024x12

25x8 41x8

4 MHz 4 MHz

6 6

TMR0 + WDT TMR0 + WDT

8 8

PIC12C670
PIC12C671 PIC12C672 PIC12C680 PIC12C681

512x14
1024x14 2048x14 512X12 FLASH 1024x14 FLASH

80x8
128x8 128x8 80x8 16x8 EEPROM 80x8 16x8 EEPROM

4 MHz
4 MHz 4 MHz 4 MHz 4 MHz

6
6 6 6 6 2 4 4

TMR0 + WDT
TMR0 + WDT TMR0 + WDT TMR0 + WDT TMR0 + WDT

8
8 8 8 8

Gama baja o bsica: PIC16C5X con instrucciones de 12 bits.


Se trata de una serie de PIC de recursos limitados, pero con una de la mejores relaciones coste/prestaciones. Sus versiones estn encapsuladas con 18 y 28 patitas y pueden alimentarse a partir de una tensin de 2,5 V, lo que les hace ideales en las aplicaciones que funcionan con pilas teniendo en cuenta su bajo consumo (menos de 2 mA a 5 V y 4 MHz). Tienen un repertorio de 33 instrucciones cuyo formato consta de 12 bits. No admiten ningn tipo de interrupcin y la Pila slo dispone de dos niveles.

Gama media. PIC16CXXX con instrucciones de 14 bits


Es la gama ms variada y completa de los PIC. Abarca modelos con encapsulado desde 18 patitas hasta 68, cubriendo varias opciones que integran abundantes perifricos. Dentro de esta gama se halla el fabuloso PIC16X84 y sus variantes.

En esta gama sus componentes aaden nuevas prestaciones a las que posean los de la gama baja, hacindoles ms adecuados en las aplicaciones complejas. Admiten interrupciones, poseen comparadores de magnitudes analgicas, convertidores A/D, puertos serie y diversos temporizadores. El repertorio de instrucciones es de 35, de 14 bits cada una y compatible con el de la gama baja. Sus distintos modelos contienen todos los recursos que se precisan en las aplicaciones de los microcontroladores de 8 bits. Tambin dispone de interrupciones y una Pila de 8 niveles que permite el anidamiento de subrutinas.

Gama alta: PIC17CXXX con instrucciones de 16 bits


Se alcanzan las 58 instrucciones de 16 bits en el repertorio y sus modelos disponen de un sistema de gestin de interrupciones vectorizadas muy potente. Tambin incluyen variados controladores de perifricos, puertas de comunicacin serie y paralelo con elementos externos, un multiplicador hardware de gran velocidad y mayores capacidades de memoria, que alcanza los 8 k palabras en la memoria de instrucciones y 454 bytes en la memoria de datos. Quizs la caracterstica ms destacable de los componentes de esta gama es su arquitectura abierta, que consiste en la posibilidad de ampliacin del microcontrolador con elementos externos. Para este fin, las patitas sacan al exterior las lneas de los buses de datos, direcciones y control, a las que se conectan memorias o controladores de perifricos Esta filosofa de construccin del sistema es la que se empleaba en los microprocesadores y no suele ser una prctica habitual cuando se emplean microcontroladores.

Gama mejorada PIC18


Es la ltima gama que ha salido. Tiene memoria de programa hasta de 1M de palabras. La mayora de las instrucciones son de 16 bits aunque tambin tiene de 32. El nmero total de instrucciones es de 76. Esta gama est diseada para aplicaciones de control, todos los modelos tienen convertidor A/D y algunos de ellos tienen interfase para bus USB y CAN

Family

ROM [Kbytes]

RAM [bytes]

Pins

Clock Freq. [MHz]

A/D Inputs

Resolution Comparof A/D ators Converter

8/16 bit Timers

Serial Comm.

PWM Outputs

Others

Base-Line 8 - bit architecture, 12-bit Instruction Word Length PIC10FXXX PIC12FXXX PIC16FXXX PIC16HVXXX 0.375 - 0.75 0.75 - 1.5 0.75 - 3 1.5 16 - 24 25 - 38 25 - 134 25 6-8 8 14 - 44 18 - 20 4-8 4-8 20 20 0-2 0-3 0-3 8 8 8 0-1 0-1 0-2 1x8 1x8 1x8 1x8 1-2x81x 16 1-2x81x 16 EEPROM EEPROM Vdd = 15V

Mid-Range 8 - bit architecture, 14-bit Instruction World Length PIC12FXXX PIC12HVXXX 1.75 - 3.5 1.75 64 - 128 64 8 8 20 20 0-4 0-4 10 10 1 1 0-1 0-1 EEPROM -

PIC16FXXX
PIC16HVXXX

1.75 - 14
1.75 - 3.5

64 - 368
64 - 128

14 - 64
14 - 20

20
20

0 - 13
0 - 12

8 or 10
10

0-2
2

1 - 2 x 8 1 x USART 16 I2C SPI


2 x 8 1 x 16 USART I2C SPI

0-3
-

High-End 8 - bit architecture, 16-bit Instruction Word Length

PIC18FXXX

4 - 128

256 - 3936

18 - 80

32 - 48

4 - 16

10 or 12

0-3

USB2.0 0 - 2 x 8 2 - CAN2.0 3 x 16 USART I2C SPI


USB2.0 0 - 2 x 8 2 - USART 3 x 16 Ethernet I2C SPI 1 x 8 3 x 16 USART I2C SPI

0-5

PIC18FXXJXX

8 - 128

1024 - 3936 28 - 100

40 - 48

10 - 16

10

2-5

PIC18FXXKXX

8 - 64

768 - 3936

28 - 44

64

10 - 13

10

PIC16F887

THE PIC16F887 BASIC FEATURES


RISC architecture Only 35 instructions to learn All single-cycle instructions except branches Operating frequency 0-20 MHz Precision internal oscillator Factory calibrated Software selectable frequency range of 8MHz to 31KHz Power supply voltage 2.0-5.5V Consumption: 220uA (2.0V, 4MHz), 11uA (2.0 V, 32 KHz) 50nA (stand-by mode) Power-Saving Sleep Mode Brown-out Reset (BOR) with software control option 35 input/output pins High current source/sink for direct LED drive software and individually programmable pull-up resistor Interrupt-on-Change pin 8K ROM memory in FLASH technology Chip can be reprogrammed up to 100.000 times In-Circuit Serial Programming Option Chip can be programmed even embedded in the target device

THE PIC16F887 BASIC FEATURES

256 bytes EEPROM memory Data can be written more than 1.000.000 times 368 bytes RAM memory A/D converter: 14-channels 10-bit resolution 3 independent timers/counters Watch-dog timer Analogue comparator module with Two analogue comparators Fixed voltage reference (0.6V) Programmable on-chip voltage reference PWM output steering control Enhanced USART module Supports RS-485, RS-232 and LIN2.0 Auto-Baud Detect Master Synchronous Serial Port (MSSP) supports SPI and I2C mode

MEMORIA DE PROGRAMA

SFRs BANK 0

SFRs BANK 1

SFRs BANK 2 y 3

IRP - Bit selects register bank. It is used for indirect addressing. 1 - Banks 2 and 3 are active (memory locations 100h-1FFh) 0 - Banks 0 and 1 are active (memory locations 00h-FFh) RP1,RP0 - Bits select register bank. They are used for direct addressing.

RP1 0 0 1 1

RP0 0 1 0 1

Active Bank Bank0 Bank1 Bank2 Bank3

TO - Time-out bit. 1 - After power-on, after executing the CLRWDT instruction which resets the watch-dog timer or the SLEEP instruction which sets the microcontroller into low-consumption mode. 0 - After watch-dog timer time-out has occurred. PD - Power-down bit. 1 - After power-on or after executing the CLRWDT instruction which resets the watchdog timer. 0 - After executing the SLEEP instruction which sets the microcontroller into low-consumption mode. Z - Zero bit 1 - The result of an arithmetic or logic operation is zero. 0 - The result of an arithmetic or logic operation is different from zero. DC - Digit carry/borrow bit is changed during addition and subtraction if an overflow or a borrow of the result occurs. 1 - A carry-out from the 4th low-order bit of the result has occurred. 0 - No carry-out from the 4th low-order bit of the result has occurred. C - Carry/Borrow bit is changed during addition and subtraction if an overflow or a borrow of the result occurs, i.e. if the result is greater than 255 or less than 0. 1 - A carry-out from the most significant bit (MSB) of the result has occurred. 0 - No carry-out from the most significant bit (MSB) of the result has occurred.

RBPU - Port B Pull up Enable bit. 1 - PortB pull-ups are disabled. 0 - PortB pull-ups are enabled

INTEDG - Interrupt Edge Select bit. 1 - Interrupt on rising edge of RB0/INT pin. 0 - Interrupt on falling edge of RB0/INT pin.

T0CS - TMR0 Clock Source Select bit. 1 - Transition on TOCKI pin. 0 - Internal instruction cycle clock (Fosc/4).

T0SE - TMR0 Source Edge Select bit selects pulse edge (rising or falling) counted by the timer TMR0 through the RA4/T0CKI pin. 1 - Increment on high-to-low transition on TOCKI pin. 0 - Increment on low-to-high transition on TOCKI pin.

PSA - Prescaler Assignment bit assigns prescaler (only one exists) to the timer or watchdog timer. 1 - Prescaler is assigned to the WDT. 0 - Prescaler is assigned to the TMR0.

PS2 0 0 0 0 1 1 1

PS1 0 0 1 1 0 1 1

PS0 0 1 0 1 1 0 1

TMR0 1:2 1:4 1:8 1:16 1:64 1:128 1:256

WDT 1:1 1:2 1:4 1:8 1:32 1:64 1:128

INTERRUPCIONES

INTERRUPCIONES

INTERRUPCIONES

PCL Y PCLATH

RA1 = AN1 (determined by bit ANS1 of the ANSEL register); RA2 = AN2 (determined by bit ANS2 of the ANSEL register); RA3 = AN3 (determined by bit ANS3 of the ANSEL register); and RA0 = AN0 (determined by bit ANS0 of the ANSEL register); RA5 = AN4 (determined by bit ANS4 of the ANSEL register).

REGISTROS ANSEL Y ANSELH

DIAGRAMA DE BLOQUES DE RA0

DIAGRAMA DE BLOQUES DE RA1

TIMER TMR0
The timer TMR0 has a wide range of application in practice. Very few programs dont use it in some way. It is very convenient and easy to use for writing programs or subroutines for generating pulses of arbitrary duration, time measurement or counting external pulses (events) with almost no limitations. The timer TMR0 module is an 8-bit timer/counter with the following features: 8-bit timer/counter; 8-bit prescaler (shared with Watchdog timer); Programmable internal or external clock source; Interrupt on overflow; and Programmable external clock edge selection.

PS2 RBPU - PORTB Pull-up enable bit 0 - PORTB pull-up resistors are disabled. 1 - PORTB pins can be connected to pull-up resistors. INTEDG - Interrupt Edge Select bit 0 - Interrupt on rising edge of the INT pin (0-1). 1 - Interrupt on falling edge of the INT pin (1-0). T0CS - TMR0 Clock Select bit 0 - Pulses are brought to TMR0 timer/counter input through the RA4 pin. 1 - Timer uses internal cycle clock (Fosc/4). 0 0 0 0 1 1 1 1

PS1 0 0 1 1 0 0 1 1

PS0 0 1 0 1 0 1 0 1

TMR0 1:2 1:4 1:8 1:16 1:32 1:64 1:128 1:256

WDT 1:1 1:2 1:4 1:8 1:16 1:32 1:64 1:128

T0SE - TMR0 Source Edge Select bit 0 - Increment on high-to-low transition on the TMR0 pin. 1 - Increment on low-to-high transition on the TMR0 pin. PSA - Prescaler Assignment bit 0 - Prescaler is assigned to the WDT. 1 - Prescaler is assigned to the TMR0 timer/counter. PS2, PS1, PS0 - Prescaler Rate Select bit Prescaler rate is adjusted by combining these bits. As seen in the table, the same combination of bits gives different prescaler rate for the timer/counter and watch-dog timer, respectively.

Timer TMR1 Timer TMR1 module is a 16-bit timer/counter, which means that it consists of two registers (TMR1L and TMR1H). It can count up 65.535 pulses in a single cycle, i.e. before the counting starts from zero.

TIMER1 en modo Timer

TIMER1 usando el oscilador

TIMER1 en modo contador

REGISTRO T1CON

Timer TMR2 Timer TMR2 module is an 8-bit timer which operates in a very specific way.

T2CON Register

MODULO ADC

MODULO ADC

The module is under the control of the bits of four registers:


ADRESH - Contains high byte of conversion result; ADRESL - Contains low byte of conversion result; ADCON0 - Control register 0; and ADCON1 - Control register 1

ADRESH and ADRESL Registers


When converting an analog value into a digital one, the result of the 10-bit A/D conversion will be stored in these two registers. In order to deal with this value easier, it can appear in two formats- left justified and right justified. The ADFM bit of the ADCON1 register determines the format of conversion result.

In the event that A/D converter is not used, these registers may be used as general-purpose registers.

A/D Acquisition Requirements


For the ADC to meet its specified accuracy, it is necessary to provide a certain time delay between selecting specific analog input and measurement itself. This time is called "acquisition time" and mainly depends on the source impedance. There is an equation used for accurately calculating this time, which in the worst case amounts to approximately 20uS. Briefly, after selecting (or changing) the analog input and before starting conversion it is necessary to provide at least 20uS time delay to enable the ACD maximal conversion accuracy.

ADC Clock Period


Time needed to complete a one-bit conversion is defined as TAD. The required TAD must be at least 1,6 uS. One full 10-bit A/D conversion is a bit longer than expected and amounts to 11 TAD periods. However, since both the conversion clock frequency and source are determined by software, one of the available combination of bits ADCS1 and ADCS0 should be selected before voltage measurement on some analog input starts. These bits are stored in the ADCON0 register.

How to Use A/D Converter?


In order to enable the A/D converter to run without problems as well as to avoid unexpected results, it is necessary to consider the following: A/D converter does not differ between digital and analog voltages. In order to avoid errors in measurement or chip damage, the pins should be configured as analog inputs before conversion starts. The bits used for this purpose are stored in the TRIS and ANSELH registers; When the port with analog inputs marked as CH0-CH13 is read, the corresponding bits will be driven to logic zero (0); and Roughly speaking, voltage measurement in the converter is based on comparing input voltage with internal scale which has 1024 marks (210=1024). The lowest scale mark stands for the Vrefvoltage, whilst the highest mark stands for the Vref+ voltage.

ADFM - A/D Result Format Select bit 1 - Conversion result right justified. Six most significant bits of the ADRESLH are not used; and 0 - Conversion result left justified. Six least significant bits of the ADRESL are not used. VCFG1 - Voltage Reference bit selects negative voltage reference source needed for A/D converter operating. 1 - Negative voltage reference is applied on the Vref- pin; and 0 - Voltage power supply Vss is used as negative voltage reference source. VCFG0 - Voltage Reference bit selects positive voltage reference source needed for A/D converter operating. 1 - Positive voltage reference is applied on the Vref+ pin; and 0 - Voltage power supply Vdd is used as positive voltage reference source.

In order to measure voltage on an input pin by A/D converter the following should be done:
Step 1 - Configuring port: Write logic one (1) to the corresponding bit of the TRIS register to configure it as input; and Write logic one (1) to the corresponding bit of the ANSEL register to configure it as analog input. Step 2 - Configuring ADC module: Configure voltage reference in the ADCON1 register; Select ADC conversion clock in the ADCON0 register; Select one of input channels CH0-CH13 of the ADCON0 register; Select data format using the ADFM bit of the ADCON1 register; and Enable A/D converter by setting the ADON bit of the ADCON0 register. Step 3 - Configuring ADC interrupt (optionally): Clear the ADIF bit; and Set the ADIE, PEIE and GIE bits.

Step 4 - Wait for the required acquisition time (approximately 20uS) to pass. Step 5 - Start conversion by setting the GO/DONE bit of the ADCON0 register. Step 6 - Wait for ADC conversion to complete. It is necessary to check in program loop whether the GO/DONE pin is cleared or wait for an A/D interrupt (must be previously enabled).

Step 7 - Read ADC results:


Read the ADRESH and ADRESL registers.

Pantalla LCD
La Pantalla LCD es uno de los perifricos ms empleados para la presentacin de mensajes, variables y casi cualquier informacin proveniente de un microcontrolador. Gracias a su flexibilidad, buena visibilidad y precio reducido se ha introducido de manera determinante en el mercado.

Las pantallas LCD que incluyen un controlador interno y dedicado como el HITACHI 44780 pueden: Presentar caracteres ASCII y griegos. Recibir y mostrar caracteres personalizados. Desplazar los caracteres (scroll) tanto a la derecha como a la izquierda. Cambiar el aspecto y el movimiento del cursor. Direccionar de manera simple la posicin de visualizacin de los caracteres. Los terminales de conexin de las pantallas LCD de caracteres han sido estandarizados, siendo generalmente compatibles pin a pin con la siguiente tabla.

La informacin que se enva a la pantalla LCD puede interpretarse de dos maneras: como un comando, cuando se coloca al terminal denominado RS en nivel bajo. Y como un carcter, cuando el terminal RS est en nivel alto. Un comando es un dato numrico de 8 bits que le indica al controlador HITACHI 44780 o compatible, que debe realizar una cierta operacin.

Comandos para LCD

Diagrama de flujo para inicializacion de LCD

Conexion 4 bits

Conexion 8 bits

Conexion LCD-PIC 4 bits sin usar LCD_busy

RUTINAS BASICAS PARA MANEJO DE LCD

LCD_E

Genera un pulso de 1S por PORTB,2 patita 6 (Enable) del LCD. Si se usa una velocidad de micro diferente de 4MHz habr que ajustar este tiempo.

Lcd.lib
LCD_BUSY Chequea si el LCD esta ocupado (BUSY) y retorna de la rutina cuando ya no lo este.

Lcd_4bits.inc
LCD_REG Pone al LCD en modo de recibir comandos , espera a que no este ocupado y va a LCD_E.

LCD_DATOS

Pone el LCD en modo datos y manda el byte presente en W que ser mostrado en pantalla.

LCD_INI

Inicializacion del modulo LCD segun los tiempo marcados por el fabricante. Bus de 8 bits, 2 lineas de visualizacion y caracteres de 5 x 7 puntos.

LCD_PORT

Configura los puertos del PIC para ser usados con el LCD.

LCD en lenguaje C
El compilador C incluye un archivo (driver) que permite trabajar con displays LCD. El archivo es LCD.C y debe llamarse con la directiva #include. Este archivo contiene varias funciones ya definidas.
Lcd_init();

LCD.C

EEPROM
The Data EEPROM and Flash program memory are readable and writable during normal operation (full VDD range). These memories are not directly mapped in theregister file space. Instead, they are indirectly addressed through the Special Function Registers (SFRs). There are six SFRs used to access these memories: EECON1 EECON2 EEDAT EEDATH EEADR EEADRH (bit 4 onPIC16F886/PIC16F887 only)

When interfacing the data memory block, EEDAT holds the 8-bit data for read/write, and EEADR holds the address of the EEDAT location being accessed. These devices have 256 bytes of data EEPROM with an address range from 0h to 0FFh.

When accessing the program memory block of the PIC16F886/PIC16F887 devices, the EEDAT and EEDATH registers form a 2-byte word that holds the 14-bit data for read/write, and the EEADR and EEADRH registers form a 2-byte word that holds the 12-bit address of the EEPROM location being read. The PIC16F882 devices have 2K words of program EEPROM with an address range from 0h to 07FFh. The PIC16F883/PIC16F884 devices have 4K words of program EEPROM with an address range from 0h to 0FFFh. The program memory allows one-word reads.
The EEPROM data memory allows byte read and write. A byte write automatically erases the location and writes the new data (erase before write).

EEADR and EEADRH Registers The EEADR and EEADRH registers can address up to a maximum of 256 bytes of data EEPROM or up to a maximum of 8K words of program EEPROM. When selecting a program address value, the MSB of the address is written to the EEADRH register and the LSB is written to the EEADR register. When selecting a data address value, only the LSB of the address is written to the EEADR register. EECON1 AND EECON2 REGISTERS EECON1 is the control register for EE memory accesses. Control bit EEPGD determines if the access will be a program or data memory access. When clear, as it is when reset, any subsequent operations will operate on the data memory. When set, any subsequent operations will operate on the program memory. Program memory can only be read. Control bits RD and WR initiate read and write, respectively. These bits cannot be cleared, only set, in software. They are cleared in hardware at completion of the read or write operation. The inability to clear the WR bit in software prevents the accidental, premature termination of a write operation.

The WREN bit, when set, will allow a write operation to data EEPROM. On powerup, the WREN bit is clear.
The WRERR bit is set when a write operation is interrupted by a MCLR or a WDT Time-out Reset during normal operation. In these situations, following Reset, the user can check the WRERR bit and rewrite the location. Interrupt flag bit EEIF of the PIR2 register is set when write is complete. It must be cleared in the software. EECON2 is not a physical register. Reading EECON2 will read all 0s. The EECON2 register is used exclusively in the data EEPROM write sequence.

To read a data memory location, the user must write the address to the EEADR register, clear the EEPGD control bit of the EECON1 register, and then set control bit RD. The data is available at the very next cycle, in the EEDAT register; therefore, it can be read in the next instruction. EEDAT will hold this value until another read or until it is written to by the user (during a write operation).

WRITING TO THE DATA EEPROM MEMORY

To write an EEPROM data location, the user must first write the address to the EEADR register and the data to the EEDAT register. Then the user must follow a specific sequence to initiate the write for each byte.
The write will not initiate if the above sequence is not followed exactly (write 55h to EECON2, write AAh to EECON2, then set WR bit) for each byte. Interrupts should be disabled during this code segment.

Additionally, the WREN bit in EECON1 must be set to enable write. This mechanism prevents accidental writes to data EEPROM due to errant (unexpected) code execution (i.e., lost programs). The user should keep the WREN bit clear at all times, except when updating EEPROM. The WREN bit is not cleared by hardware.

After a write sequence has been initiated, clearing the WREN bit will not affect this write cycle. The WR bit will be inhibited from being set unless the WREN bit is set. At the completion of the write cycle, the WR bit is cleared in hardware and the EE Write Complete Interrupt Flag bit (EEIF) is set. The user can either enable this interrupt or poll this bit. EEIF must be cleared by software.

MODULO EUSART

COMUNICACION ASINCRONA

Briefly, each data is transferred in the following way: In idle state, data line has high logic level (1); Each data transmission starts with START bit which is always a zero (0); Each data is 8- or 9-bit wide (LSB bit is first transferred); and Each data transmission ends with STOP bit which always has logic level which is always a one (1).

EUSART Asynchronous Transmitter

TXSTA Register

In order to enable data transmission via EUSART module, it is necessary to configure it to operate as a transmitter. In other words, it is necessary to define the state of the following bits: TXEN = 1 - EUSART transmitter is enabled by setting this bit of the TXSTA register; SYNC = 0 - EUSART is configured to operate in asynchronous mode by clearing this bit of the TXSTA register; and SPEN = 1 - By setting this bit of the RCSTA register, EUSART is enabled and the TX/CK pin is automatically configured as output. If this bit is simultaneously used for some analog function, it must be disabled by clearing the corresponding bit of the ANSEL register.

EUSART Asynchronous Receiver

Similar to the activation of EUSART transmitter, in order to enable the receiver it is necessary to define the following bits:
CREN = 1 - EUSART receiver is enabled by setting this bit of the RCSTA register; SYNC = 0 - EUSART is configured to operate in asynchronous mode by clearing this bit stored in the TXSTA register; and SPEN = 1 - By setting this bit of the RCSTA register, EUSART is enabled and the RX/DT pin is automatically configured as input. If this bit is simultaneously used for some analog function, it must be disabled by clearing the corresponding bit of the ANSEL register.

When this first and necessary step is accomplished and START bit is detected, data is transferred to the shift register RSR through the RX pin. When the STOP bit has been received, the following occurs:

Data is automatically transferred to the RCREG register (if empty);


The flag bit RCIF is set and an interrupt, if enabled by the RCIE bit of the PIE1 register, occurs. Similar to transmitter, the flag bit is cleared by software only, i.e. by reading the RCREG register. Bear in mind that this is a two character FIFO memory (first-in, first-out) which allows reception of two characters simultaneously; If the RCREG register is occupied (contains two bytes) and the shift register detects new STOP bit, the overflow bit OERR will be set. In this case, a new coming data is lost, and the OEER bit must be cleared by software. It is done by clearing and resetting the CREN bit. Note: it is not possible to receive new data as far as the OERR bit is set; If the STOP bit is zero (0), the FERR bit of the RCSTAregister detecting receive error will be set; and To receive 9-bit data it is necessary to set the RX9 bit of the RCSTA register.

Receive Error Detection


There are two types of errors which the microcontroller can automatically detect. he first one is called Framing error and occurs when the receiver does not detect the STOP bit at the expected time. Such error is indicated via the FERR bit of the RCSTA register. If this bit is set, it means that the last received data may be incorrect. It is important to know several things: A Framing error does not generate an interrupt by itself; If this bit is set, the last received data has an error; A framing error (bit set) does not prevent reception of new data; The FERR bit is cleared by reading received data, which means that check must be done before data reading; and The FERR bit cannot be cleared by software. If needed, it can be cleared by clearing the SPEN bit of the RCSTA register. It will simultaneously cause reset of the whole EUSART system.

Receive Error Detection


Another type of error is called Overrun Error. The receive FIFO can hold two characters. An overrun error will be generated if the third character is received. Simply, there is no space for another one byte and an error is unavoidable! When this happens the OERR bit of the RCSTA register is set. The consequences are the following:

Data already stored in the FIFO registers (two bytes) can be normally read; No additional data will be received until the OERR bit is cleared; and This bit is not directly accessed. To clear it, it is necessary to clear the CREN bit of the RCSTA register or to reset the whole EUSART system by clearing the SPEN bit of the RCSTA register.

Receiving 9-bit Data

Address Detection

EUSART Baud Rate Generator (BRG)

Sending data via asynchronous EUSART communication: 1.The desired baud rate should be set by using bits BRGH (TXSTA register) and BRG16 (BAUDCTL register) and registers SPBRGH and SPBRG; 2.The SYNC bit (TXSTA register) should be cleared and the SPEN bit should be set (RCSTA register) in order to enable serial port; 3.On 9-bit data transmission, the TX9 bit of the TXSTA register should be set; 4.Data transmission is enabled by setting bit TXEN of the TXSTA register. Bit TXIF of the PIR1 register is automatically set; 5.If needed the bit TXEN causes an interrupt, the GIE and PEIE bits of the INTCON register should be set; 6.On 9-bit data transmission, value of the ninth bit should be written to the TX9D bit of the TXSTA register; and 7.Transmission starts by writing 8-bit data to the TXREG register.

Receiving data via asynchronous EUSART communication: 1.Baud Rate should be set by using bits BRGH (TXSTA register) and BRG16 (BAUDCTL register) and registers SPBRGH and SPBRG; 2.The SYNC bit (TXSTA register) should be cleared and the SPEN bit should be set (RCSTA register) in order to enable serial port; 3.If it is necessary the data receive causes an interrupt, both the RCIE bit of the PIE1 register and bits GIE and PEIE of the INTCON register should be set; 4.On 9-bit data receive, the RX9 bit of the RCSTA register should be set; 5.Data receive should be enabled by setting the CREN bit of the RCSTA register; 6.The RCSTA register should be read to get information on possible errors which have occurred during transmission. On 9-bit data receive, the ninth bit will be stored in this register; and 7.Received 8-bit data stored in the RCREG register should be read.

You might also like