Professional Documents
Culture Documents
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).
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
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.
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.
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.
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.
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.
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.
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.
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.
Microchip dispone de cuatro familias de microcontroladores de 8 bits para adaptarse a las necesidades de la mayora de los clientes potenciales.
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
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
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.
Family
ROM [Kbytes]
RAM [bytes]
Pins
A/D Inputs
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
0-3
-
PIC18FXXX
4 - 128
256 - 3936
18 - 80
32 - 48
4 - 16
10 or 12
0-3
0-5
PIC18FXXJXX
8 - 128
40 - 48
10 - 16
10
2-5
PIC18FXXKXX
8 - 64
768 - 3936
28 - 44
64
10 - 13
10
PIC16F887
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
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
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).
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
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.
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
In the event that A/D converter is not used, these registers may be used as general-purpose registers.
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).
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.
Conexion 4 bits
Conexion 8 bits
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).
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).
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.
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 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.
Address Detection
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.