You are on page 1of 316

Curso de Microcontroladores PIC Avanzados

Jesus M. Hern andez Mangas 26 de agosto de 2008

M. Hern Copyright c Jesus andez Mangas, 2006, 2008 Profesor Titular de Electronica en la Universidad de Valladolid total o parcial de este libro, ni su No est a permitida la reproduccion de ninguna forma o por tratamiento inform atico, ni la transmision cualquier medio, ya sea electronico, mec anico, por fotocopia, por registro u otros m etodos, sin el permiso previo y por escrito de los titulares del Copyright.

Indice general
Prologo Planicacion 9 11

I THEORICUM
1. Microcontrolador PIC16F87x de caracter 1.1. Enumeracion sticas . . . . . . . 1.1.1. Prestaciones . . . . . . . . . . . . . . 1.1.2. Perif ericos integrados . . . . . . . . 1.2. Modelos y caracter sticas particulares . . . 1.3. Patillaje . . . . . . . . . . . . . . . . . . . . . 1.4. Arquitectura interna . . . . . . . . . . . . . 1.4.1. Modelos 16F874 y 16F877 . . . . . . 1.4.2. Modelos 16F873 y 16F876 . . . . . . de la memoria . . . . . . . . . 1.5. Organizacion 1.5.1. Memoria de programa . . . . . . . . 1.5.2. Memoria de datos . . . . . . . . . . 1.5.3. Registros de proposito espec co . . 1.5.4. Contador de programa . . . . . . . . 1.5.5. Direccionamiento directo/ indirecto 2. Puertos de Entrada/Salida 2.1. Puerto A . . . . . . . . . . . 2.1.1. Caracter sticas . . . . 2.1.2. Registros asociados . 2.1.3. Pines asociados . . . 2.1.4. Esquemas hardware 2.1.5. Ejemplo . . . . . . . 2.2. Puerto B . . . . . . . . . . . 2.2.1. Caracter sticas . . . . 2.2.2. Registros asociados . 2.2.3. Pines asociados . . . 2.2.4. Esquemas hardware 2.3. Puerto C . . . . . . . . . . . 2.3.1. Caracter sticas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

15
17 17 17 18 19 19 23 23 24 25 25 26 26 33 33 35 35 35 36 36 37 38 39 39 39 39 40 42 42

4 2.3.2. Registros asociados . . . . . . . . . 2.3.3. Pines asociados . . . . . . . . . . . 2.3.4. Esquemas hardware . . . . . . . . 2.4. Puerto D . . . . . . . . . . . . . . . . . . . 2.4.1. Caracter sticas . . . . . . . . . . . . 2.4.2. Registros asociados . . . . . . . . . 2.4.3. Pines asociados . . . . . . . . . . . 2.4.4. Esquemas hardware . . . . . . . . 2.5. Puerto E . . . . . . . . . . . . . . . . . . . 2.5.1. Caracter sticas . . . . . . . . . . . . 2.5.2. Registros asociados . . . . . . . . . 2.5.3. Pines asociados . . . . . . . . . . . 2.5.4. Esquemas hardware . . . . . . . . 2.6. Puerto Paralelo Esclavo . . . . . . . . . . . 2.6.1. Caracter sticas . . . . . . . . . . . . 2.6.2. Registros asociados . . . . . . . . . 2.6.3. Registro TRISE . . . . . . . . . . . 2.6.4. Esquema hardware y cronogramas 2.6.5. Ejemplo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

INDICE GENERAL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 42 43 45 45 45 45 46 47 47 47 47 48 49 49 50 50 51 52 53 53 53 54 54 55 57 57 57 57 58 59 59 60 61 61 61 62 63 63 63 64 66 67 67

3. Temporizadores 3.1. Temporizador TMR0 . . . . . . . . . . . . . . . . . . . . . . . . 3.1.1. Caracter sticas . . . . . . . . . . . . . . . . . . . . . . . . 3.1.2. Esquema hardware . . . . . . . . . . . . . . . . . . . . . 3.1.3. Registros . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.1.4. Ejemplos . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.2. Temporizador TMR1 . . . . . . . . . . . . . . . . . . . . . . . . 3.2.1. Caracter sticas . . . . . . . . . . . . . . . . . . . . . . . . 3.2.2. Esquema hardware . . . . . . . . . . . . . . . . . . . . . 3.2.3. Registros . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.2.4. Funcionamiento como temporizador . . . . . . . . . . . 3.2.5. Funcionamiento como contador . . . . . . . . . . . . . 3.2.6. Funcionamiento como contador con oscilador externo 3.2.7. Reinicio del Temporizador 1 . . . . . . . . . . . . . . . . 3.3. Temporizador TMR2 . . . . . . . . . . . . . . . . . . . . . . . . 3.3.1. Caracter sticas . . . . . . . . . . . . . . . . . . . . . . . . 3.3.2. Esquema hardware . . . . . . . . . . . . . . . . . . . . . 3.3.3. Registros . . . . . . . . . . . . . . . . . . . . . . . . . . . 4. Conversor Analogico/Digital 4.1. Caracter sticas . . . . . . . . . . . . . . 4.2. Esquema . . . . . . . . . . . . . . . . . 4.3. Registros asociados . . . . . . . . . . . y adquisicion de datos 4.4. Conguracion 4.5. Resumen de registros . . . . . . . . . . 4.6. Ejemplo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

INDICE GENERAL 5. Memorias EEPROM y FLASH 5.1. Caracter sticas . . . . . . . . . . . . . . . . . 5.2. Registros . . . . . . . . . . . . . . . . . . . . 5.3. Escritura de la memoria EEPROM de datos 5.4. Lectura de la memoria EEPROM de datos . 5.5. Escritura de la memoria Flash de programa 5.6. Lectura de la memoria Flash de programa . de la memoria . . . . . . . . . . 5.7. Proteccion

5 69 69 69 71 71 71 72 72 75 75 76 76 76 77 79 81 85 85 85 87 89 91 93 93 95 95 95 95 96 96 97 98 100 102 105 105 106 106 108 113 113 114 115

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

6. Modulos CCP 6.1. Caracter sticas . . . . . . . . . . . . . . . . . . . . . 6.1.1. Modulo CCP1 . . . . . . . . . . . . . . . . . 6.1.2. Modulo CCP2 . . . . . . . . . . . . . . . . . 6.2. Registros . . . . . . . . . . . . . . . . . . . . . . . . 6.3. Modo Captura . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.4. Modo Comparacion por Anchura de Pulsos) 6.5. Modo PWM (Modulacion 7. Modulo USART 7.1. Caracter sticas . . . . . . . . . . . . . 7.2. Registros . . . . . . . . . . . . . . . . 7.3. Generador de baudios . . . . . . . . . . . . 7.4. Modo as ncrono: transmision . . . . . . 7.5. Modo as ncrono: recepcion 7.6. Modo s ncrono maestro: transmision . 7.7. Modo s ncrono maestro: recepcion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

8. Modulo MSSP . . . . . . . . . . . . . . . . . . . . 8.1. Introduccion 8.2. Modulo MSSP: protocolo SPI . . . . . . . . . . 8.2.1. Caracter sticas . . . . . . . . . . . . . . . 8.2.2. Esquema hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.2.3. Conguracion 8.2.4. Modo SPI maestro . . . . . . . . . . . . 8.2.5. Modo SPI esclavo . . . . . . . . . . . . . en SPI 8.2.6. Ejemplo transmision/recepci on 8.2.7. Registros . . . . . . . . . . . . . . . . . . 8.3. Modulo MSSP: protocolo I2C . . . . . . . . . . 8.3.1. Caracter sticas . . . . . . . . . . . . . . . 8.3.2. Funcionamiento . . . . . . . . . . . . . . 8.3.3. Modo I2C esclavo . . . . . . . . . . . . . 8.3.4. Modo I2C maestro . . . . . . . . . . . .

9. Otras caracter sticas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.1. Introduccion del microcontrolador . . . . . . . . . . . . . . . . . . . . . 9.2. Conguracion del oscilador . . . . . . . . . . . . . . . . . . . . . . . . . . 9.3. Conguracion

6 9.4. Reset . . . . . . . . . . . . . . . . . . . . . . . . . 9.5. Interrupciones . . . . . . . . . . . . . . . . . . . 9.6. Temporizador perro guardi an . . . . . . . . . . 9.7. Modo de bajo consumo: SLEEP . . . . . . . . . del codigo 9.8. Proteccion . . . . . . . . . . . . . . . 9.9. Identicacion . . . . . . . . . . . . . . . . . . . serie en el sistema (ICSP) . . . . 9.10. Programacion en circuito de bajo voltaje (LVP) 9.11. Programacion 9.12. Depuracion en circuito . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

INDICE GENERAL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 118 120 121 121 122 122 122 122

10. Otros microcontroladores PIC avanzados 125 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 10.1. Introduccion 10.2. Gu a de productos de Microchip de 8 bits . . . . . . . . . . . . . . . . . . . 134 10.3. Otras familias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150

II PRACTICUM
11. Grabador/ bootloader 11.1. Grabador . . . . . . . . . . . . . . . . . . . . . . . . . 11.1.1. Hardware compatible JDM . . . . . . . . . . 11.1.2. Software ICProg . . . . . . . . . . . . . . . . 11.2. Bootloader . . . . . . . . . . . . . . . . . . . . . . . . 11.2.1. Montaje bootloader para micros de 28 patillas 11.2.2. Montaje bootloader para micros de 40 patillas 11.2.3. Software . . . . . . . . . . . . . . . . . . . . . 12. Software: Proteustm 12.1. Proteus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12.1.1. Introduccion 12.1.2. Primeros pasos con Proteus ISIS . 12.1.3. Primeros pasos con Proteus ARES 12.2. PIC C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12.2.1. Introduccion de Proteustm . . . 12.2.2. Conguracion 12.2.3. Uso en Proteustm . . . . . . . . . . 12.3. MPLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12.3.1. Introduccion 13. Motores Paso a Paso . . 13.1. Introduccion 13.2. Se pide . . . . . 13.3. Cuestiones . . . 13.4. Para nota . . . . 13.5. Hojas de datos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

151
153 153 153 156 157 157 159 161 163 163 163 163 176 183 183 185 186 186 186 189 189 192 192 192 194

INDICE GENERAL 14. Termometro digital . 14.1. Introduccion 14.2. Se pide . . . . 14.3. Cuestiones . . 14.4. Hojas de datos 14.5. Software LCD

7 197 197 198 199 200 202 205 205 205 207 209 209 211 211 212 215 215 216 217 218 221 221 223 223 224 227 227 228 230 231

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

15. Generacion de audio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15.1. Introduccion 15.2. Se pide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15.3. Cuestiones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16. Motores de corriente continua . . . . . . . . 16.1. Introduccion 16.2. Se pide . . . . . . . . . . . 16.3. Cuestiones . . . . . . . . . 16.4. Hojas de datos . . . . . . . 17. Frecuenc metro/tacometro . . . . . 17.1. Introduccion 17.2. Se pide . . . . . . . . 17.3. Cuestiones . . . . . . 17.4. Hojas de datos . . . . 18. Robot Rastreador . 18.1. Introduccion 18.2. Se pide . . . . 18.3. Cuestiones . . 18.4. Hojas de datos 19. Comunicaciones . 19.1. Introduccion 19.2. Se pide . . . . 19.3. Cuestiones . . 19.4. Hojas de datos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

20. LCD Gr aco 233 20.1. Introduccion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233 20.2. Se pide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235 20.3. Cuestiones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235 21. Conexion al mundo USB 237 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237 21.1. Introduccion

INDICE GENERAL

III SOLUCIONES

239

22. Motores paso a paso 241 22.1. Solucion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241 22.1.1. Se pide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241 22.1.2. Cuestiones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247 23. Termometro digital 249 23.1. Solucion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 23.1.1. Se pide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 23.1.2. Cuestiones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 24. Generacion de audio 257 24.1. Solucion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257 24.1.1. Se pide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257 24.1.2. Cuestiones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264 25. Motores de corriente continua 25.1. Solucion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25.1.1. Se pide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25.1.2. Cuestiones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26. Frecuenc metro/tacometro 26.1. Solucion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26.1.1. Se pide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26.1.2. Cuestiones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265 265 265 268 269 269 269 271

27. Robot Rastreador 273 27.1. Solucion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 27.1.1. Se pide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 27.1.2. Cuestiones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 28. Comunicaciones 277 28.1. Solucion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 28.1.1. Se pide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 28.1.2. Cuestiones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282 29. LCD Gr aco 283 29.1. Solucion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283 29.1.1. Se pide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283 29.1.2. Cuestiones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289

IV Ap endices

291

A. Ficheros cabecera 293 A.1. Fichero de cabecera en ensamblador: P16F877.inc . . . . . . . . . . . . . 293 A.2. Fichero de cabecera en lenguaje C: pic.h . . . . . . . . . . . . . . . . . . . 298

INDICE GENERAL B. Bancos de registros C. Juego de instrucciones Indice alfab etico Indice de listados Bibliograf a

9 305 309 309 312 313

10

INDICE GENERAL

Prologo
Proposito
de este libro ha sido durante anos un anhelo del autor, que bien por La realizacion no pudo llevarse a cabo. El lector comprenfalta de tiempo o por falta de nanciacion, der a, a la vista de este volumen, que ambas circunstancias se han dado a la vez, o si no al menos la segunda, ya que como uno puede adivinar el tiempo se puede comprar. nimo seguido al redactar este libro en castellano (o espanol, como se preera), El a no ha sido otro que servir de referencia a los estudiantes del curso titulado Microcontroladores PIC: 2a Parte e Introducci on a Proteus, que ha sido nanciado por la Junta y el Fondo Social Europeo, y que est de Castilla y Leon a dirigido al profesorado de reas de Equipos Electronicos ensenanzas medias de las a y Sistemas Electronicos, para que lo puedan emplear en su docta ensenanza, sin olvidarme por supuesto, de todo el venideros pasar alumnado que en anos a por mi aula en sus estudios de Ingenier a en Electronica. Dado que los ingenieros en su trabajo van a utilizar obligatoriamente referencias inglebibliogr acas escritas en ingl es, se ha cre do conveniente mantener la notacion sa en la mayor a de las siglas y en algunas descripciones de banderas (ags) de los registros empleados.

Agradecimientos
a todas aquellas personas que de una u El autor quiere agradecer la colaboracion de este proyecto. otra manera han ayudado en la realizacion El agradecimiento se hace extensivo a las administraciones que, como la Junta de y la Union Europea, nancian este tipo de actividades para ampliar los Castilla y Leon conocimientos del profesorado y proporcionar algo de bibliograf a en castellano, que tanto se echa en falta en las ensenanzas t ecnicas.

Valladolid, 26 de agosto de 2008, Manuel Hern Dr. Jesus andez Mangas

11

12

INDICE GENERAL

Planicacion del curso


El curso se desarrollar a siguiendo el siguiente plan1 :
Fecha 9/09/2008 9/09/2008 10/09/2008 11/09/2008 12/09/2008 15/09/2008 16/09/2008 17/09/2008 18/09/2008 19/09/2008 Teor a Tema 1 - Microcontrolador PIC16F87x Tema 2 - Puertos de Entrada / Salida Tema 3 - Temporizadores Tema 4 - Conversor Analogico/ Digital Tema 5 - Memorias EEPROM y FLASH Tema 6 - Modulos CCP Tema 7 - Modulo USART Tema 8 - Modulo MSSP Tema 9 - Otras caracter sticas Tema 10- Otros microcontroladores .. Pr actica Tema 11 - Grabador/bootloader Tema 12 - Software Proteus Tema 13 - Motores paso a paso Tema 14 - Termometro digital de audio Tema 15 - Generacion Tema 16 - Motores de continua Tema 17 - Frecuenc metro/ tacometro Tema 18 - Robot rastreador Tema 19 - Comunicaciones Tema 19 - Comunicaciones

horaria ser La distribucion a de aproximadamente 2 horas para la teor a (depender a del tema) y de 4 horas para cada pr actica. Todas las pr acticas est an resueltas y se llegar an a ver funcionando al nal de cada sesion. En total son 60 horas distribuidas en bloques de 6/7 horas durante 9 d as. Espero que aprendan y les resulte entretenido.

la respuesta e inter Este plan es exible y variar a segun es del alumnado.

13

14

INDICE GENERAL

Parte I THEORICUM

15

Cap tulo 1 Microcontrolador PIC16F87x


Es mejor tener la boca cerrada y parecer estupido, que abrirla y disipar toda duda. Mark Twain

1.1. Enumeracion de caracter sticas


La familia de microcontroladores de Microchip PIC16F87x est a compuesta por 4 modelos diferentes denominados: PIC16F873, PIC16F874, PIC16F876 y PIC16F877.

1.1.1. Prestaciones
35 instrucciones (compatibles con el juego de instrucciones de toda la familia PIC16). dura un ciclo de instruccion (4 ciclos de reloj) a excepcion de las Cada instruccion que involucran saltos (2 ciclos de instruccion). 200 ns. Velocidad: 20 MHz (T = 50 ns), ciclo de instruccion: Hasta 8k x 14 memoria de programa Flash. Hasta 368 x 8 memoria de datos RAM, vol atil. Hasta 256 x 8 memoria de datos EEPROM, no vol atil. diferentes (segun modelo). Hasta 14 fuentes de interrupcion Pila hardware de 8 niveles. Direccionamiento directo, indirecto y relativo. Power-on reset (POR). Reset de arranque. Power-up Timer (PWRT): temporizador de arranque y Oscillator Startup Timer (OST): temporizador de arranque del oscilador. Watchdog Timer (WDT): temporizador perro guardi an, con red RC integrada. 17

18 del codigo Proteccion programable. SLEEP. Modo de bajo consumo con la instruccion Tipo de oscilador seleccionable. est Diseno atico de baja potencia y alta velocidad.

Enumeraci on de caracter sticas

Programable en el sistema (ICSP: In-Circuit Serial Programming). con voltaje bajo (LVP: Low Voltage Programming). Modo de programacion en circuito. In-Circuit Debugging (ICD): depuracion Posibilidad de leer/escribir en la memoria de programa: posibilidad de implementar un programa cargador de arranque (bootloader). de alimentacion variable entre 2.0 V y 5.5 V. Tension E/S de alta corriente (m aximo 25 mA). Bajo consumo: < 2mA @ 5V, 4 MHz < 1uA en modo SLEEP.

1.1.2. Perif ericos integrados


Temporizador/contador TMR0, de 8 bits con pre-escala de 8 bits. Temporizador/contador TMR1, de 16 bits con pre-escala. Funciona en modo SLEEP v a cristal externo. Temporizador/contador TMR2, de 8 bits con registro periodo de 8 bits, pre-escala y post-escala. Dos modulos CCP: Captura/Comparacion/PWM (Pulse Width Modulation: Mod por Anchura de Pulsos). ulacion 12.5 ns). Captura de 16 bits (m axima resolucion: de 16 bits (m 200 ns). Comparacion axima resolucion: 10 bits). PWM (m axima resolucion: Conversor Analogico/Digital de 10 bits multicanal (5 u 8 dependiendo del modelo). Puerto serie s ncrono (MSSP: Master Synchronous Serial Port). Compatible SPI (Serial Peripheral Interface) en modo maestro. Compatible I2C (Inter-Integrated Circuit) en modos maestro y esclavo.

Cap tulo 1. Microcontrolador PIC16F87x

19

Receptor/Transmisor Serie As ncrono/S ncrono Universal (USART) tambi en lla de direcciones de 9 bits. mado Serial Communications Interface (SCI) con deteccion Puerto paralelo esclavo (PSP: Parallel Slave Port) de 8 bits con control externo a trav es de senales /RD, /WR y /CS. de alimentacion por debajo de un Brown-out reset (BOR): reset al bajar la tension umbral (4 V).

1.2. Modelos y caracter sticas particulares


Las diferencias entre los modelos se resumen en la siguiente tabla:
Key Features PICmicro Mid-Range Reference Manual (DS33023) Operating Frequency Resets (and Delays) FLASH Program Memory (14-bit words) Data Memory (bytes) EEPROM Data Memory Interrupts I/O Ports Timers Capture/Compare/PWM modules Serial Communications Parallel Communications 10-bit Analog-to-Digital Module Instruction Set PIC16F873 DC - 20 MHz POR, BOR (PWRT, OST) 4K 192 128 13 Ports A,B,C 3 2 MSSP, USART 5 input channels 35 Instructions PIC16F874 DC - 20 MHz POR, BOR (PWRT, OST) 4K 192 128 14 Ports A,B,C,D,E 3 2 MSSP, USART PSP 8 input channels 35 Instructions PIC16F876 DC - 20 MHz POR, BOR (PWRT, OST) 8K 368 256 13 Ports A,B,C 3 2 MSSP, USART 5 input channels 35 Instructions PIC16F877 DC - 20 MHz POR, BOR (PWRT, OST) 8K 368 256 14 Ports A,B,C,D,E 3 2 MSSP, USART PSP 8 input channels 35 Instructions

A (ej.: PIC16F877A). Segun el fabExisten estos mismos modelos en su revision empleado y quiz ricante no hay ninguna diferencia salvo el m etodo de grabacion as sin importancia en sus caracter alguna variacion sticas el ectricas. Tambi en existen los modelos LF (ej.: PIC16LF877A) de menor consumo y que pueden de hasta 2.0 voltios, frente a los 4.0 voltios de los funcionar a tensiones de alimentacion modelos normales.

1.3. Patillaje
PIC16F873 y PIC16F876 Tienen un encapsulado de 28 patillas como se puede ver en la gura:

20
DIP, SOIC
MCLR/VPP/THV RA0/AN0 RA1/AN1 RA2/AN2/VREFRA3/AN3/VREF+ RA4/T0CKI RA5/AN4/SS VSS OSC1/CLKIN OSC2/CLKOUT RC0/T1OSO/T1CKI RC1/T1OSI/CCP2 RC2/CCP1 RC3/SCK/SCL 1 2 3 4 5 6 7 8 9 10 11 12 13 14 28 27 26 25 24 23 22 21 20 19 18 17 16 15 RB7/PGD RB6/PGC RB5 RB4 RB3/PGM RB2 RB1 RB0/INT VDD VSS RC7/RX/DT RC6/TX/CK RC5/SDO RC4/SDI/SDA

Patillaje

PIC16F874 y PIC16F877 Tienen un encapsulado de 40 patillas como se puede ver en la gura:

PDIP
MCLR/VPP/THV RA0/AN0 RA1/AN1 RA2/AN2/VREFRA3/AN3/VREF+ RA4/T0CKI RA5/AN4/SS RE0/RD/AN5 RE1/WR/AN6 RE2/CS/AN7 VDD VSS OSC1/CLKIN OSC2/CLKOUT RC0/T1OSO/T1CKI RC1/T1OSI/CCP2 RC2/CCP1 RC3/SCK/SCL RD0/PSP0 RD1/PSP1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 RB7/PGD RB6/PGC RB5 RB4 RB3/PGM RB2 RB1 RB0/INT VDD VSS RD7/PSP7 RD6/PSP6 RD5/PSP5 RD4/PSP4 RC7/RX/DT RC6/TX/CK RC5/SDO RC4/SDI/SDA RD3/PSP3 RD2/PSP2

Descripcion del patillaje En los siguientes esquemas se describe el patillaje de estos microcontroladores:

PIC16F877/874

PIC16F876/873

Cap tulo 1. Microcontrolador PIC16F87x


DIP Pin# 13 14 PLCC Pin# 14 15 QFP Pin# 30 31 I/O/P Type I O Buffer Type ST/CMOS(4)

21

Pin Name OSC1/CLKIN OSC2/CLKOUT

Description Oscillator crystal input/external clock source input. Oscillator crystal output. Connects to crystal or resonator in crystal oscillator mode. In RC mode, OSC2 pin outputs CLKOUT which has 1/4 the frequency of OSC1, and denotes the instruction cycle rate. Master clear (reset) input or programming voltage input or high voltage test mode control. This pin is an active low reset to the device. PORTA is a bi-directional I/O port. RA0 can also be analog input0 RA1 can also be analog input1 RA2 can also be analog input2 or negative analog reference voltage RA3 can also be analog input3 or positive analog reference voltage RA4 can also be the clock input to the Timer0 timer/ counter. Output is open drain type. RA5 can also be analog input4 or the slave select for the synchronous serial port. PORTB is a bi-directional I/O port. PORTB can be software programmed for internal weak pull-up on all inputs.

MCLR/VPP/THV

18

I/P

ST

RA0/AN0 RA1/AN1 RA2/AN2/VREFRA3/AN3/VREF+ RA4/T0CKI RA5/SS/AN4

2 3 4 5 6 7

3 4 5 6 7 8

19 20 21 22 23 24

I/O I/O I/O I/O I/O I/O

TTL TTL TTL TTL ST TTL

RB0/INT RB1 RB2 RB3/PGM RB4 RB5 RB6/PGC RB7/PGD

33 34 35 36 37 38 39 40

36 37 38 39 41 42 43 44

8 9 10 11 14 15 16 17

I/O I/O I/O I/O I/O I/O I/O I/O

TTL/ST(1) TTL TTL TTL TTL TTL TTL/ST(2) TTL/ST(2)

RB0 can also be the external interrupt pin.

RB3 can also be the low voltage programming input Interrupt on change pin. Interrupt on change pin. Interrupt on change pin or In-Circuit Debugger pin. Serial programming clock. Interrupt on change pin or In-Circuit Debugger pin. Serial programming data. PORTC is a bi-directional I/O port.

RC0/T1OSO/T1CKI RC1/T1OSI/CCP2 RC2/CCP1 RC3/SCK/SCL RC4/SDI/SDA RC5/SDO RC6/TX/CK RC7/RX/DT Legend: Note 1: 2: 3: 4: I = input

15 16 17 18 23 24 25 26

16 18 19 20 25 26 27 29

32 35 36 37 42 43 44 1

I/O I/O I/O I/O I/O I/O I/O I/O

ST ST ST ST ST ST ST ST

RC0 can also be the Timer1 oscillator output or a Timer1 clock input. RC1 can also be the Timer1 oscillator input or Capture2 input/Compare2 output/PWM2 output. RC2 can also be the Capture1 input/Compare1 output/ PWM1 output. RC3 can also be the synchronous serial clock input/output for both SPI and I2C modes. RC4 can also be the SPI Data In (SPI mode) or data I/O (I2C mode). RC5 can also be the SPI Data Out (SPI mode). RC6 can also be the USART Asynchronous Transmit or Synchronous Clock. RC7 can also be the USART Asynchronous Receive or Synchronous Data.

O = output I/O = input/output P = power = Not used TTL = TTL input ST = Schmitt Trigger input This buffer is a Schmitt Trigger input when configured as an external interrupt. This buffer is a Schmitt Trigger input when used in serial programming mode. This buffer is a Schmitt Trigger input when configured as general purpose I/O and a TTL input when used in the Parallel Slave Port mode (for interfacing to a microprocessor bus). This buffer is a Schmitt Trigger input when configured in RC oscillator mode and a CMOS input otherwise.

22
DIP Pin# PLCC Pin# QFP Pin# I/O/P Type Buffer Type

Patillaje

Pin Name

Description PORTD is a bi-directional I/O port or parallel slave port when interfacing to a microprocessor bus.

RD0/PSP0 RD1/PSP1 RD2/PSP2 RD3/PSP3 RD4/PSP4 RD5/PSP5 RD6/PSP6 RD7/PSP7

19 20 21 22 27 28 29 30

21 22 23 24 30 31 32 33

38 39 40 41 2 3 4 5

I/O I/O I/O I/O I/O I/O I/O I/O

ST/TTL(3) ST/TTL(3) ST/TTL(3) ST/TTL(3) ST/TTL(3) ST/TTL(3) ST/TTL(3) ST/TTL(3) PORTE is a bi-directional I/O port. ST/TTL(3) ST/TTL(3) ST/TTL(3) RE0 can also be read control for the parallel slave port, or analog input5. RE1 can also be write control for the parallel slave port, or analog input6. RE2 can also be select control for the parallel slave port, or analog input7. Ground reference for logic and I/O pins. Positive supply for logic and I/O pins. These pins are not internally connected. These pins should be left unconnected.

RE0/RD/AN5 RE1/WR/AN6 RE2/CS/AN7 VSS VDD NC Legend: Note 1: 2: 3: 4: I = input

8 9 10 12,31 11,32

9 10 11 13,34 12,35 1,17,28, 40

25 26 27 6,29 7,28 12,13, 33,34

I/O I/O I/O P P

O = output I/O = input/output P = power = Not used TTL = TTL input ST = Schmitt Trigger input This buffer is a Schmitt Trigger input when configured as an external interrupt. This buffer is a Schmitt Trigger input when used in serial programming mode. This buffer is a Schmitt Trigger input when configured as general purpose I/O and a TTL input when used in the Parallel Slave Port mode (for interfacing to a microprocessor bus). This buffer is a Schmitt Trigger input when configured in RC oscillator mode and a CMOS input otherwise.

Cap tulo 1. Microcontrolador PIC16F87x

23

1.4. Arquitectura interna


1.4.1. Modelos 16F874 y 16F877
Device PIC16F874 PIC16F877 Program FLASH 4K 8K Data Memory 192 Bytes 368 Bytes
13 FLASH Program Memory 8 Level Stack (13-bit) Program Bus 14 Instruction reg Direct Addr 7 Program Counter

Data EEPROM 128 Bytes 256 Bytes


Data Bus 8 PORTA RA0/AN0 RA1/AN1 RA2/AN2/VREFRA3/AN3/VREF+ RA4/T0CKI RA5/AN4/SS PORTB RB0/INT RB1 RB2 RB3/PGM RB4 RB5 RB6/PGC RB7/PGD RC0/T1OSO/T1CKI RC1/T1OSI/CCP2 RC2/CCP1 RC3/SCK/SCL RC4/SDI/SDA RC5/SDO RC6/TX/CK RC7/RX/DT PORTD W reg RD7/PSP7:RD0/PSP0

RAM File Registers

RAM Addr (1)

Addr MUX 8 Indirect Addr

FSR reg STATUS reg 8 3 PORTC

Power-up Timer Instruction Decode & Control Timing Generation OSC1/CLKIN OSC2/CLKOUT Oscillator Start-up Timer Power-on Reset Watchdog Timer Brown-out Reset In-Circuit Debugger Low-Voltage Programming 8

MUX

ALU

Parallel Slave Port

PORTE RE0/AN5/RD RE1/AN6/WR

MCLR

VDD, VSS

RE2/AN7/CS

Timer0

Timer1

Timer2

10-bit A/D

Data EEPROM

CCP1,2

Synchronous Serial Port

USART

24

Arquitectura interna

1.4.2. Modelos 16F873 y 16F876


Device PIC16F873 PIC16F876 Program FLASH 4K 8K Data Memory 192 Bytes 368 Bytes
13 Program Counter FLASH Program Memory 8 Level Stack (13-bit) Program Bus 14 Instruction reg Direct Addr 7

Data EEPROM 128 Bytes 256 Bytes


Data Bus 8 PORTA RA0/AN0 RA1/AN1 RA2/AN2/VREFRA3/AN3/VREF+ RA4/T0CKI RA5/AN4/SS PORTB RB0/INT RB1 RB2 RB3/PGM RB4 RB5 RB6/PGC RB7/PGD RC0/T1OSO/T1CKI RC1/T1OSI/CCP2 RC2/CCP1 RC3/SCK/SCL RC4/SDI/SDA RC5/SDO RC6/TX/CK RC7/RX/DT

RAM File Registers

RAM Addr (1)

Addr MUX 8 Indirect Addr

FSR reg STATUS reg 8 3 PORTC

Power-up Timer Instruction Decode & Control Timing Generation OSC1/CLKIN OSC2/CLKOUT Oscillator Start-up Timer Power-on Reset Watchdog Timer Brown-out Reset In-Circuit Debugger Low-Voltage Programming 8

MUX

ALU

W reg

MCLR

VDD, VSS

Timer0

Timer1

Timer2

10-bit A/D

Data EEPROM

CCP1,2

Synchronous Serial Port

USART

Cap tulo 1. Microcontrolador PIC16F87x

25

1.5. Organizacion de la memoria


La memoria se divide en memoria de programa y memoria de datos ya que esta familia de microcontroladores implementan una arquitectura Harvard.

1.5.1. Memoria de programa


Se direcciona con el contador de programa que tiene 13 bits. En el microcontrolador PIC16F877/876 la memoria es de 8k x 14 bit. En el microcontrolador PIC17F874/873 la memoria es de 4k x 14 bit. en la posicion 0 de la memoria de El microcontrolador comienza la ejecucion programa. se salta a la posicion 4 de la memoria de Cuando se produce una interrupcion programa. Dispone de una pila hardware de 8 niveles para los retornos de las subrutinas interrupciones exclusivamente. o p La memoria de programa est a dividida en bloques o aginas de 2k x14 bits. Esto CALL). ser a importante cuando usemos las instrucciones de salto (GOTO o
PC<12:0>

CALL, RETURN RETFIE, RETLW

13

Stack Level 1 Stack Level 2

Stack Level 8

Reset Vector

0000h

Interrupt Vector

0004h 0005h

Page 0 07FFh 0800h Page 1 On-Chip Program Memory Page 2 17FFh 1800h Page 3 1FFFh 0FFFh 1000h

26

Organizaci on de la memoria

1.5.2. Memoria de datos


La memoria de datos est a dividida en dos bloques: uno implementado en RAM y y otro bloque independiente implementado en memoque describimos a continuacion ria EEPROM que se ver a m as adelante. La memoria RAM de datos tiene las siguientes caracter sticas: En el microcontrolador PIC16F877/876 la RAM es de 368 bytes. En el microcontrolador PIC16F874/873 la RAM es de 192 bytes. Est a dividida en 4 bancos de 128 posiciones. Hay que seleccionar el banco accesible mediante los bits STATUS.RP1:RP0. En las primeras 32 posiciones de la RAM se encuentran mapeados los registros de proposito espec co (SFR: Special Function Registers). El resto ser an posiciones para los registros de proposito general (GPR: General Purpose Registers).

1.5.3. Registros de proposito espec co


se muestra un esquema general: A continuacion

Cap tulo 1. Microcontrolador PIC16F87x


File Address Indirect addr.(*) TMR0 PCL STATUS FSR PORTA PORTB PORTC PORTD (1) PORTE (1) PCLATH INTCON PIR1 PIR2 TMR1L TMR1H T1CON TMR2 T2CON SSPBUF SSPCON CCPR1L CCPR1H CCP1CON RCSTA TXREG RCREG CCPR2L CCPR2H CCP2CON ADRESH ADCON0 00h 01h 02h 03h 04h 05h 06h 07h 08h 09h 0Ah 0Bh 0Ch 0Dh 0Eh 0Fh 10h 11h 12h 13h 14h 15h 16h 17h 18h 19h 1Ah 1Bh 1Ch 1Dh 1Eh 1Fh 20h Indirect addr.(*) 80h OPTION_REG 81h PCL 82h STATUS 83h FSR 84h TRISA 85h TRISB 86h TRISC 87h TRISD (1) 88h TRISE (1) 89h PCLATH 8Ah INTCON 8Bh PIE1 8Ch PIE2 8Dh PCON 8Eh 8Fh 90h 91h SSPCON2 PR2 92h SSPADD 93h SSPSTAT 94h 95h 96h 97h 98h TXSTA 99h SPBRG 9Ah 9Bh 9Ch 9Dh ADRESL 9Eh 9Fh ADCON1 A0h General Purpose Register 80 Bytes accesses 70h-7Fh 7Fh Bank 0 Bank 1 Indirect addr.(*) 100h 101h TMR0 102h PCL 103h STATUS 104h FSR 105h 106h PORTB 107h 108h 109h 10Ah PCLATH 10Bh INTCON 10Ch EEDATA EEADR 10Dh 10Eh EEDATH 10Fh EEADRH 110h 111h 112h 113h 114h 115h 116h General 117h Purpose 118h Register 119h 16 Bytes 11Ah 11Bh 11Ch 11Dh 11Eh 11Fh 120h Indirect addr.(*) OPTION_REG PCL STATUS FSR TRISB 180h 181h 182h 183h 184h 185h 186h 187h 188h 189h 18Ah 18Bh 18Ch 18Dh 18Eh 18Fh 190h 191h 192h 193h 194h 195h 196h 197h 198h 199h 19Ah 19Bh 19Ch 19Dh 19Eh 19Fh 1A0h General Purpose Register 80 Bytes accesses 70h - 7Fh Bank 3

27

PCLATH INTCON EECON1 EECON2 Reserved(2) Reserved(2)

General Purpose Register 16 Bytes

General Purpose Register 96 Bytes

EFh F0h FFh

General Purpose Register 80 Bytes accesses 70h-7Fh Bank 2

16Fh 170h 17Fh

1EFh 1F0h 1FFh

Unimplemented data memory locations, read as 0. * Not a physical register. Note 1: These registers are not implemented on 28-pin devices. 2: These registers are reserved, maintain these registers clear.

28 Descripcion de algunos registros

Organizaci on de la memoria

STATUS. Presente en todos los bancos. Registro de estado y control.

STATUS
Bit 7 6 5 4 3 2 1 Bit 0

IRP

RP1

RP0

/TO

/PD

DC

de banco para direccionamiento indirecto. IRP Seleccion 0: Selecciona bancos 0 y 1. 1: Selecciona bancos 2 y 3. de banco con direccionamiento directo. RP1:RP0 Seleccion 00: 01: 10: 11: Banco 0. Banco 1. Banco 2. Banco 3.

/TO Indica un desbordamiento del temporizador del perro guardi an. 0: Desbordamiento (timeout) del perro guardi an. SLEEP. de las instrucciones CLRWDT o 1: Despu es de un arranque normal, o la ejecucion /PD Indica el paso al modo de bajo consumo (power down). SLEEP. 0: Ejecutada una instruccion de CLRWDT. 1: Despu es de un arranque o la ejecucion Z Cero. aritm 0: El resultado de la ultima instruccion etica o logica no fue cero. aritm 1: El resultado de la ultima instruccion etica o logica fue cero. DC Acarreo de d gito o semiacarreo. 0: No hubo acarreo. 1: Acarreo hacia el bit 4. aritm C Acarreo o la que me llevo despu es de la ultima operacion etica o logica. 0: No hubo acarreo. 1: Acarreo hacia el bit 8. OPTION_REG. Presente en los bancos 1 y 3. Registro de opciones.

OPTION REG
Bit 7 6 5 4 3 2 1 Bit 0

/RBPU

INTEDG

T0CS

T0SE

PSA

PS2

PS1

PS0

de las resistencias internas de pull-up del PORTB. /RBPU Bit de habilitacion 0: Activado. 1: Desactivado. del anco del pin RB0/INT. INTEDG Seleccion 0: Flanco de bajada. 1: Flanco de subida. de la fuente de reloj para el temporizador 0. T0CS Seleccion

Cap tulo 1. Microcontrolador PIC16F87x


interno. Equivale a 4 ciclos de reloj del microcontrolador. 0: Ciclo de instruccion en la patilla RA4/T0CKI. 1: Transicion de anco para la fuente externa del temporizador 0. T0SE Seleccion 0: Se incrementar a en el anco de subida de RA4/T0CKI. 1: Se incrementar a en el anco de bajada de RA4/T0CKI. del divisor de frecuencia. PSA Asignacion 0: Pre-escala asignada al temporizador TMR0. 1: Divisor asignado al perro guardi an (WDT) como post-escala. PS2:PS0 Divisor de frecuencia. Bits 000 001 010 011 100 101 110 111 PSA=0 (TMR0) 1:2 1:4 1:8 1:16 1:32 1:64 1:128 1:256 PSA=1 (WDT) 1:1 1:2 1:4 1:8 1:16 1:32 1:64 1:128

29

de interINTCON. Presente en todos los bancos. Registro de control y noticacion rupciones. INTCON
Bit 7 6 5 4 3 2 1 Bit 0

GIE

PEIE

T0IE

INTE

RBIE

T0IF

INTF

RBIF

global de las interrupciones. GIE Habilitacion 0: Deshabilita. 1: Habilita. de las interrupciones de los perif PEIE Habilitacion ericos, a trav es de los registros PIR1 y PIR2. 0: Deshabilita. 1: Habilita. de la interrupcion debida al temporizador TMR0. T0IE Habilitacion 0: Deshabilita. 1: Habilita. de la interrupcion debida a la patilla RB0/INT. INTE Habilitacion 0: Deshabilita. 1: Habilita. de la interrupcion debida al cambio en la entrada en las patillas RB4, RB5, RBIE Habilitacion RB6, RB7. 0: Deshabilita. 1: Habilita. T0IF Notica el desbordamiento del temporizador TMR0. nada. 0: No paso TMR0. Hay que borrarlo por software. 1: Se desbordo

30

Organizaci on de la memoria
el anco seleccionado en la patilla RB0/INT. INTF Notica que ocurrio nada. 0: No paso 1: Detectado anco programado en RB0/INT. Hay que borrarlo por software. RBIF Detectado un cambio en la entrada en las patillas RB4, RB5, RB6, RB7. nada. 0: No paso 1: Cambio detectado. Hay que borrarlo por software. Para que sea efectivo antes hay que leer el puerto B. PIE1. Presente en el banco 1. Registro de interrupciones de los perif ericos.

PIE1
Bit 7 6 5 4 3 2 1 Bit 0

PSPIE

ADIE

RCIE

TXIE

SSPIE

CCP1IE

TMR2IE

TMR1IE

de la interrupcion por lectura o escritura en el puerto paralelo esclavo (modu PSPIE Habilitacion lo PSP). 0: Deshabilita. 1: Habilita. de las interrupcion del conversor AD. ADIE Habilitacion 0: Deshabilita. 1: Habilita. de la interrupcion debida a la recepcion del modulo RCIE Habilitacion USART. 0: Deshabilita. 1: Habilita. de la interrupcion debida a la transmision del modulo TXIE Habilitacion USART. 0: Deshabilita. 1: Habilita. de la interrupcion debida al modulo SSPIE Habilitacion MSSP. 0: Deshabilita. 1: Habilita. de la interrupcion debida al modulo CCP1IE Habilitacion CCP1. 0: Deshabilita. 1: Habilita. de la interrupcion debida al alcance del periodo (PR2) por el temporizador TMR2IE Habilitacion TMR2. 0: Deshabilita. 1: Habilita. de la interrupcion debida al desbordamiento del temporizador TMR1. TMR1IE Habilitacion 0: Deshabilita. 1: Habilita.

de las interrupciones de los PIR1. Presente en el banco 0. Registro de noticacion perif ericos. Son bits pegajosos: deben ponerse de nuevo a cero por software.

Cap tulo 1. Microcontrolador PIC16F87x PIR1


Bit 7 6 5 4 3 2 1

31

Bit 0

PSPIF

ADIF

RCIF

TXIF

SSPIF

CCP1IF

TMR2IF

TMR1IF

de lectura o escritura en el puerto paralelo esclavo (modulo PSPIF Noticacion PSP). nada. 0: No paso o se leyo del modulo 1: Se escribio PSP. de la nalizacion de una conversion del modulo ADIF Noticacion AD. nada. 0: No paso completada. 1: Conversion de la recepcion de un dato por el modulo RCIF Noticacion USART. nada. 0: No paso est 1: El bufer de recepcion a lleno en el modulo USART. de una transmision realizada en el modulo TXIF Noticacion USART. nada. 0: No paso est 1: El bufer de transmision a vac o. de evento ocurrido en el modulo SSPIF Noticacion MSSP. nada. 0: No paso algo: 1: Ocurrio o recepcion nalizada. SPI Transmision o recepcion nalizada. I2C Esclavo Transmision o recepcion nalizada. I2C Maestro Transmision start realizada. I2C Maestro Condicion stop realizada. I2C Maestro Condicion restart realizada. I2C Maestro Condicion I2C Maestro Secuencia ACK realizada. una condicion start cuando el modulo I2C Maestro Ocurrio estaba ocioso (arbitraje de bus multimaestro). una condicion stop cuando el modulo I2C Maestro Ocurrio estaba ocioso (arbitraje de bus multimaestro). de suceso del modulo CCP1IF Noticacion CCP1. nada. 0: No ocurrio una captura o una comparacion en el modulo 1: Ocurrio CCP1. de que TMR2 alcanzo PR2. TMR2IF Noticacion nada. 0: No paso 1: Fin de cuenta. del desbordamiento de TMR1. TMR1IF Noticacion nada. 0: No paso 1: Desbordamiento de TMR1. PIE2. Presente en el banco 1. Registro de interrupciones de los perif ericos.

PIE2
Bit 7 6 5 4 3 2 1 Bit 0

EEIE

BCLIE

CCP2IE

32

Organizaci on de la memoria
debida a la nalizacion de la escritura en la memoria EEPROM (de EEIE Habilita la interrupcion datos o de programa). no permitida. 0: Interrupcion permitida. 1: Interrupcion debida a una colision en el bus I2C (modo maestro). BCLIE Habilita la interrupcion no permitida. 0: Interrupcion permitida. 1: Interrupcion debida al modulo CCP2IE Habilita la interrupcion CCP2. no permitida. 0: Interrupcion permitida. 1: Interrupcion

de las interrupciones de los PIR2. Presente en el banco 0. Registro de noticacion perif ericos. PIR2
Bit 7 6 5 4 3 2 1 Bit 0

EEIF

BCLIF

CCP2IF

de que la escritura en la memoria EEPROM (de datos o de programa) ha nalEEIF Noticacion izado. incompleta. En curso. 0: Operacion nalizada. 1: Operacion en el bus I2C (modo maestro). BCLIF Colision 0: Todo bien. una colision en el bus I2C. 1: Ocurrio la operacion (modos captura o comparacion). CCP2IF El modulo CCP2 completo en curso o no iniciada. 0: Operacion nalizada. 1: Operacion PCON. Presente en el banco 1. Registro de estado del arranque del microcontro-

lador. PCON
Bit 7 6 5 4 3 2 1 Bit 0

/POR

/BOR

/POR Estado del reset de arranque. un arranque del sistema (POR: Power-on reset). Se debe poner a uno por soft0: Ocurrio ware para detectarlo. nada. 1: No ocurrio de alimentacion (BOR: Brown-Out /BOR Senaliza un rearranque del micro por ca da de la tension Reset). el reset. 0: Ocurrio 1: No ocurrio.

Cap tulo 1. Microcontrolador PIC16F87x

33

1.5.4. Contador de programa


El contador de programa PC es de 13 bits y no es accesible directamente. Est a compuesto de: Registro PCL: parte baja de PC. Registro PCH: parte alta de PC. No es accesible directamente, si no que se puede cuanmodicar a trav es del registro PCLATH que se copia en PCH al escribir en PCL o GOTO o CALL. do se ejecuta una instruccion Esquema
PCH 12 PC 5 PCLATH<4:0> 8 8 7 PCL 0 Instruction with PCL as Destination ALU

PCLATH PCH 12 PC 2 PCLATH<4:3> 11 Opcode <10:0> PCLATH 11 10 8 7 PCL 0 GOTO,CALL

Ejemplo
1 2 3 4 5 6 7 8 9 10 11 12 13 14

ORG BCF BSF CALL

0x500 PCLATH,4 PCLATH,3 SUB1_P1

; Selecciona la pagina 1 de FLASH (800h-FFFh) ; Llama a la subrutina ; pagina 1 (800h-FFFh) ; pagina 1 (800h-FFFh) ; subrutina llamada ; pagina 1 (800h-FFFh) ; retorno de la subrutina ; hacia la pagina 0 (000h-7FFh)

: : ORG 0x900 SUB1_P1 : : : RETURN

1.5.5. Direccionamiento directo/ indirecto


a la que se accede a trav El registro FSR contiene la direccion es del registro INDF. Esto es INDF=[FSR].

34 Esquema

Organizaci on de la memoria

El funcionamiento es diferente cuando el direccionamiento es directo de cuando el direccionamiento es indirecto:


Direct Addressing RP1:RP0 6 from opcode 0 IRP Indirect Addressing 7 FSR register 0

bank select

location select 00 00h 01 80h 10 100h 11 180h

bank select

location select

Data Memory(1)

7Fh Bank 0

FFh Bank 1

17Fh Bank 2

1FFh Bank 3

Ejemplo de direccionamiento indirecto El ejemplo muestra como poner a cero un bloque de datos en RAM desde la posi 300 hasta la 400: cion
1 2 3 4 5 6 7 8 9 10

NEXT

FIN

bsf movlw movwf clrf incf movlw subwf btfss goto bcf

STATUS,IRP 300 FSR INDF FSR,F 400 FSR,W STATUS,Z NEXT STATUS,IRP

; ; inicializa el puntero FSR = 300 ; [FSR] = INDF = 0 ; incrementa FSR ; W = FSR-400 ; fin? ; si no continua borrando ;

Cap tulo 2 Puertos de Entrada/Salida


Es mejor encender una luz que maldecir la oscuridad Proverbio a rabe

2.1. Puerto A
El puerto A est a compuesto por las patillas RA0, RA1, RA2, RA3, RA4 y RA5, luego consta de tan solo 6 pines.

2.1.1. Caracter sticas


Puede funcionar como entrada/salida digital: RA0, RA1, RA2, RA3, RA4 y RA5. Para ello: TRISA indicar a el sentido de cada patilla, siendo salida cuando el bit correspondiente vale 0 y entrada cuando vale 1. ADCON1 = 00000110b para congurar todos los pines como de entrada/salida digital. La patilla RA4 tiene un comportamiento especial ya que: Cuando funciona como entrada, es de tipo Schmitt Trigger y puede asociarse al temporizador TMR0 como entrada externa. Cuando funciona como salida es de drenador abierto, luego necesitar a una resistencia de pull-up para poner los unos logicos. Puede funcionar como entrada analogica : RA0, RA1, RA2, RA3, RA5. Se ver a en el tema dedicado al conversor AD.

35

36

Puerto A

2.1.2. Registros asociados


TABLE 3-2:
Address 05h 85h 9Fh

SUMMARY OF REGISTERS ASSOCIATED WITH PORTA


Name Bit 7 Bit 6 Bit 5 RA5 Bit 4 RA4 Bit 3 RA3 Bit 2 RA2 Bit 1 RA1 Bit 0 RA0 Value on: Value on all POR, other BOR resets
--0x 0000 --0u 0000 --11 1111 --11 1111

PORTA TRISA

PORTA Data Direction Register

ADCON1 ADFM

PCFG3 PCFG2 PCFG1 PCFG0 --0- 0000 --0- 0000

Legend: x = unknown, u = unchanged, - = unimplemented locations read as '0'. Shaded cells are not used by PORTA.

2.1.3. Pines asociados


entrada analogica. RA0/AN0 Entrada/salida digital o Bufer tipo TTL. entrada analogica. RA1/AN1 Entrada/salida digital o Bufer tipo TTL. entrada analogica tension de referencia RA2/AN2/VREF- Entrada/salida digital o o inferior para el conversor AD. Bufer tipo TTL. entrada analogica tension de referencia RA3/AN3/VREF+ Entrada/salida digital o o superior para el conversor AD. Bufer tipo TTL. entrada de reloj externa para el temporizador RA4/T0CKI Entrada/salida digital o TMR0. La salida es de drenador abierto. Bufer tipo ST. entrada analogica entrada de seleccion de RA5/SS/AN4 Entrada/salida digital o o esclavo para el puerto de comunicaciones serie s ncrono. Bufer tipo TTL.

Cap tulo 2. Puertos de Entrada/Salida

37

2.1.4. Esquemas hardware


Patillas RA0..RA3,RA5
Data Bus D Q VDD CK Q P

WR Port

Data Latch D WR TRIS Q N I/O pin(1)

CK

TRIS Latch

VSS Analog Input Mode

RD TRIS

TTL Input Buffer D

EN

RD PORT

To A/D Converter

Note 1: I/O pins have protection diodes to VDD and VSS.

38 Patilla RA4
Data Bus WR PORT D Q Q N Data Latch D WR TRIS Q Q VSS Schmitt Trigger Input Buffer

Puerto A

CK

I/O pin(1)

CK

TRIS Latch

RD TRIS Q D EN EN RD PORT

TMR0 clock input

Note 1: I/O pin has protection diodes to VSS only.

2.1.5. Ejemplo
En ensamblador
1 2 3 4 5 6 7 8 9 10

BCF BCF CLRF BSF MOVLW MOVWF MOVLW MOVWF

STATUS, RP0 ; STATUS, RP1 ; Banco 0 de registros PORTA ; Inicializa el PORTA borrandolo STATUS, RP0 ; Banco 1 0x06 ; Configura los pines ADCON1 ; como entradas digitales 0xCF ; TRISA ; Pone RA<3:0> como entradas ; RA<5:4> como salidas ; TRISA<7:6> no se usan

En lenguaje C
1 2 3 4 5

PORTA = 0; ADCON1 = 0x06; TRISA = 0xCF;

// // // // //

Borra PORTA PORTA digital RA<3:0> entradas RA<5:4> salidas RA<7:6> no se usan

Cap tulo 2. Puertos de Entrada/Salida

39

2.2. Puerto B
El puerto B est a compuesto por las patillas RB0, RB1, RB2, RB3, RB4, RB5, RB6 y RB7.

2.2.1. Caracter sticas


Puede funcionar como entrada/salida digital. Para ello: TRISB indicar a el sentido de cada patilla, siendo salida cuando el bit correspondiente vale 0 y entrada cuando vale 1. Dispone de una resistencia de pull-up de entrada programable en cada pin. Se activa globalmente para todo el PORTB (para las patillas que sean entradas) mediante OPTION_REG.NOT_RBPU = 0. del Los pines RB3/PGM, RB6/PGC y RB7/PGD permiten la reprogramacion dispositivo: modo LVP (Low Voltage Programming) que se comentar a m as adelante.

2.2.2. Registros asociados


Address 06h, 106h 86h, 186h 81h, 181h Legend: Name PORTB TRISB OPTION_REG = unknown, Bit 7 RB7 RBPU Bit 6 RB6 INTEDG Bit 5 RB5 T0CS Bit 4 RB4 T0SE Bit 3 RB3 PSA Bit 2 RB2 PS2 Bit 1 RB1 PS1 Bit 0 RB0 PS0 Value on: POR, BOR Value on all other resets

xxxx xxxx uuuu uuuu 1111 1111 1111 1111 1111 1111 1111 1111

PORTB Data Direction Register = unchanged. Shaded cells are not used by PORTB.

2.2.3. Pines asociados


entrada de interrupciones externas. Tiene una reRB0/INT Entrada/salida digital o ST (entrada de sistencia de pull-up de entrada programable. Bufer tipo TTL o interrupciones). RB1 Entrada/salida digital. Tiene una resistencia de pull-up de entrada programable. Bufer tipo TTL. RB2 Entrada/salida digital. Tiene una resistencia de pull-up de entrada programable. Bufer tipo TTL. de la programacion en modo RB3/PGM Entrada/salida digital o patilla de activacion LVP. Tiene una resistencia de pull-up de entrada programable. Bufer tipo TTL. al cambiar la entrada). Tiene una reRB4 Entrada/salida digital (genera interrupcion sistencia de pull-up de entrada programable. Bufer tipo TTL. al cambiar la entrada). Tiene una reRB5 Entrada/salida digital (genera interrupcion sistencia de pull-up de entrada programable. Bufer tipo TTL.

40

Puerto B

al cambiar la entrada) o senal RB6/PGC Entrada/salida digital (genera interrupcion patilla para de reloj cuando se programa el dispositivo (ya sea modo LVP o no) o en circuito (ICD) .Tiene una resistencia de pull-up de entrada prola depuracion ST (en programacion). gramable. Bufer tipo TTL o al cambiar la entrada) o senal RB7/PGD Entrada/salida digital (genera interrupcion patilla de datos cuando se programa el dispositivo (ya sea modo LVP o no) o en circuito (ICD) .Tiene una resistencia de pull-up de entrada para la depuracion ST (en programacion). programable. Bufer tipo TTL o

2.2.4. Esquemas hardware


Patillas RB0..RB3
VDD RBPU(2) Data Latch D Q CK TRIS Latch D Q WR TRIS CK I/O pin(1) weak P pull-up

Data Bus WR Port

TTL Input Buffer

RD TRIS Q RD Port D EN

RB0/INT RB3/PGM Schmitt Trigger Buffer Note 1: 2: RD Port

I/O pins have diode protection to VDD and VSS. To enable weak pull-ups, set the appropriate TRIS bit(s) and clear the RBPU bit (OPTION_REG<7>).

Cap tulo 2. Puertos de Entrada/Salida Patilla RB4..RB7


VDD RBPU(2) Data Latch D Q CK TRIS Latch D Q WR TRIS CK TTL Input Buffer I/O pin(1) weak P pull-up

41

Data Bus WR Port

ST Buffer

RD TRIS Q RD Port Set RBIF

Latch D EN Q1

From other RB7:RB4 pins

D RD Port EN Q3

RB7:RB6 in serial programming mode Note 1: 2: I/O pins have diode protection to VDD and VSS. To enable weak pull-ups, set the appropriate TRIS bit(s) and clear the RBPU bit (OPTION_REG<7>).

42

Puerto C

2.3. Puerto C
El puerto C est a compuesto por las patillas RC0..RC7.

2.3.1. Caracter sticas


Puede funcionar como entrada/salida digital. Para ello: TRISC indicar a el sentido de cada patilla, siendo salida cuando el bit correspondiente vale 0 y entrada cuando vale 1. Comparten funcionalidad con otros perif ericos pudiendo cambiar el sentido indicado en TRISC si el perif erico correspondiente est a activado.

2.3.2. Registros asociados


Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Value on: POR, BOR
xxxx xxxx 1111 1111

Value on all other resets


uuuu uuuu 1111 1111

07h 87h

PORTC TRISC

RC7

RC6

RC5

RC4

RC3

RC2

RC1

RC0

PORTC Data Direction Register

Legend: x = unknown, u = unchanged.

2.3.3. Pines asociados


salida del oscilador del temporizador RC0/T1OSO/T1CKI Entrada/salida digital o entrada de reloj del TMR1. Bufer TMR1 o tipo ST. entrada del oscilador del temporizador 1 RC1/T1OSI/CCP2 Entrada/salida digital o entrada/salida del modulo o CCP2. Bufer tipo ST. entrada/salida del modulo RC2/CCP1 Entrada/salida digital o CCP1. Bufer tipo ST. senal de reloj en el modulo RC3/SCK/SCL Entrada/salida digital o MSSP de comuni caciones (tanto para el modo I2C como SPI). Bufer tipo ST. entrada de datos en comunicaciones SPI o enRC4/SDI/SDA Entrada/salida digital o trada/salida de datos en modo I2C. Bufer tipo ST. salida de datos en modo SPI. Bufer RC5/SDO Entrada/salida digital o tipo ST. reloj en las transmisiones as RC6/TX/CK Entrada/salida digital o ncronas o s ncronas del modulo USART. entrada de datos en las transmisiones as RC7/RX/DT Entrada/salida digital o ncronas o entrada/salida de datos en las transmisiones s ncronas del modulo USART.

Cap tulo 2. Puertos de Entrada/Salida

43

2.3.4. Esquemas hardware


Patillas RC0..RC2,RC5..RC7
PORT/PERIPHERAL Select(2) Peripheral Data Out Data Bus WR PORT 0 D CK Q 1 Q VDD P

Data Latch WR TRIS D CK Q Q N VSS RD TRIS Peripheral OE(3) RD PORT Peripheral Input Q D EN Schmitt Trigger I/O pin(1)

TRIS Latch

Note 1: I/O pins have diode protection to VDD and VSS. 2: Port/Peripheral select signal selects between port data and peripheral output. 3: Peripheral OE (output enable) is only activated if peripheral select is active.

44 Patillas RC3 y RC4


PORT/PERIPHERAL Select(2) Peripheral Data Out Data Bus WR PORT D CK Q 1 Q VDD P

Puerto C

Data Latch WR TRIS D CK Q Q N Vss RD TRIS Peripheral OE(3) RD PORT SSPl Input 1 CKE SSPSTAT<6> Q D EN 0 Schmitt Trigger with SMBus levels Schmitt Trigger I/O pin(1)

TRIS Latch

Note 1: I/O pins have diode protection to VDD and VSS. 2: Port/Peripheral select signal selects between port data and peripheral output. 3: Peripheral OE (output enable) is only activated if peripheral select is active.

Cap tulo 2. Puertos de Entrada/Salida

45

2.4. Puerto D
est El puerto D est a compuesto por las patillas RD0..RD7. Solo a presente en los modelos PIC16F874 y PIC16F877.

2.4.1. Caracter sticas


Puede funcionar como entrada/salida digital. Para ello: TRISD indicar a el sentido de cada patilla, siendo salida cuando el bit correspondiente vale 0 y entrada cuando vale 1. Cuando funcionan como entradas tienen un bufer tipo Schmitt Trigger (ST). Puede ser congurado como un puerto paralelo esclavo (PSP), en cuyo caso todas las entradas tienen un bufer tipo TTL.

2.4.2. Registros asociados


Address 08h 88h 89h Name PORTD TRISD TRISE Bit 7 RD7 IBF Bit 6 RD6 OBF Bit 5 RD5 IBOV Bit 4 RD4 PSPMODE Bit 3 RD3 Bit 2 RD2 Bit 1 RD1 Bit 0 RD0 Value on: POR, BOR xxxx xxxx 1111 1111 PORTE Data Direction Bits 0000 -111 Value on all other resets uuuu uuuu 1111 1111 0000 -111

PORTD Data Direction Register

Legend: x = unknown, u = unchanged, - = unimplemented read as 0. Shaded cells are not used by PORTD.

2.4.3. Pines asociados


bit 0 del puerto paralelo esclavo. RD0/PSP0 Entrada/salida digital o bit 1 del puerto paralelo esclavo. RD1/PSP1 Entrada/salida digital o bit 2 del puerto paralelo esclavo. RD2/PSP2 Entrada/salida digital o bit 3 del puerto paralelo esclavo. RD3/PSP3 Entrada/salida digital o bit 4 del puerto paralelo esclavo. RD4/PSP4 Entrada/salida digital o bit 5 del puerto paralelo esclavo. RD5/PSP5 Entrada/salida digital o bit 6 del puerto paralelo esclavo. RD6/PSP6 Entrada/salida digital o bit 7 del puerto paralelo esclavo. RD7/PSP7 Entrada/salida digital o

46

Puerto D

2.4.4. Esquemas hardware


Patillas RD0..RB7
Data Bus WR PORT D Q I/O pin(1) CK Data Latch D WR TRIS Q Schmitt Trigger Input Buffer

CK TRIS Latch

RD TRIS Q D EN EN RD PORT Note 1: I/O pins have protection diodes to VDD and VSS.

Cap tulo 2. Puertos de Entrada/Salida

47

2.5. Puerto E
est El puerto E est a compuesto por las patillas RE0, RE1 y RE2. Solo a presente en los modelos PIC16F874 y PIC16F877.

2.5.1. Caracter sticas


Puede funcionar como entrada/salida digital. Para ello: TRISE indicar a el sentido de cada patilla (bits 0, 1 y 2), siendo salida cuando el bit correspondiente vale 0 y entrada cuando vale 1. Puede ser congurado como un puerto paralelo esclavo (PSP), en cuyo caso todas las entradas tienen un bufer tipo TTL. Puede funcionar como entradas analogicas .

2.5.2. Registros asociados


TABLE 3-10:
Addr 09h 89h 9Fh Legend: Name PORTE TRISE ADCON1

SUMMARY OF REGISTERS ASSOCIATED WITH PORTE


Bit 7 IBF ADFM Bit 6 OBF Bit 5 IBOV Bit 4 PSPMODE Bit 3 PCFG3 Bit 2 RE2 PCFG2 Bit 1 RE1 PCFG1 Bit 0 RE0 PCFG0 Value on: POR, BOR ---- -xxx 0000 -111 --0- 0000 Value on all other resets ---- -uuu 0000 -111 --0- 0000

PORTE Data Direction Bits

= unknown,

= unchanged,

= unimplemented read as '0'. Shaded cells are not used by PORTE.

2.5.3. Pines asociados


entrada de control de lectura del puerto paraleRE0/RD/AN5 Entrada/salida digital o entrada analogica. lo esclavo o entrada de control de escritura del puerto parRE1/WR/AN6 Entrada/salida digital o entrada analogica. alelo esclavo o entrada de control de seleccion (Chip Select) del RE2/CS/AN7 Entrada/salida digital o entrada analogica. puerto paralelo esclavo o

48

Puerto E

2.5.4. Esquemas hardware


Patillas RE0..RE2
Data Bus WR PORT D Q I/O pin(1) CK Data Latch D WR TRIS Q Schmitt Trigger input buffer

CK TRIS Latch

RD TRIS Q D EN EN RD PORT Note 1: I/O pins have protection diodes to VDD and VSS.

Cap tulo 2. Puertos de Entrada/Salida

49

2.6. Puerto Paralelo Esclavo


est Est a asociado al puerto D y al puerto E de entrada/salida. Solo a presente en los modelos PIC16F874 y PIC16F877 de 40 patillas.

2.6.1. Caracter sticas


Para activarlo hay que hacer: TRISE.PSPMODE = 1 lo que har a que el puerto D sea bidireccional independientemente de lo que marque TRISD. ADCON1.PCFG3:PCFG0 deben permitir que RE2..RE0 sean digitales. Para enviar un dato al exterior: Se pone el dato en PORTD. Se espera a que sea le do. Esto lo har a un dispositivo externo usando las patillas de entrada RE0/RD, RE2/CS siguiendo el cronograma que aparece m as adelante. Cuando haya sido le do, el bit TRISE.OBF = 1. El bit PIR1.PSPIF se pondr a a uno para noticarlo y si los bits PIE1.PSPIE = 1, INTCON.GIE = 1 y INTCON.PEIE = 1 se producir a una interrupcion. Para recibir un dato: Cuando el dispositivo externo escriba un dato empleando el protocolo descrito en el cronograma que aparece m as adelante usando las patillas RE1/WR, RE2/CS, el bit TRISE.IBF se pondr a a uno para indicar que hay un dato pendiente de lectura. A la vez el bit PIR1.PSPIF se pondr a a uno para noticarlo y si los bits PIE1.PSPIE = 1, INTCON.GIE = 1 y INTCON.PEIE = 1 se producir a una inter rupcion. Despu es de la lectura del dato el bit TRISE.IBF pasar a a valer cero, no as el bit PIR1.PSPIF que es un bit pegajoso que es necesario poner a cero por software. Si antes de la lectura del dato, el dispositivo externo escribe otro dato, sobrescribiendo el primer dato se activar a el bit TRISE.IBOV = 1 para indicarlo.

50

Puerto Paralelo Esclavo

2.6.2. Registros asociados


TABLE 3-11:
Address 08h 09h 89h 0Ch 8Ch 9Fh

REGISTERS ASSOCIATED WITH PARALLEL SLAVE PORT


Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Value on: POR, BOR xxxx xxxx RE2 RE1 RE0 ---- -xxx 0000 -111 Value on all other resets uuuu uuuu ---- -uuu 0000 -111 0000 0000 0000 0000 --0- 0000

Name PORTD PORTE TRISE PIR1 PIE1 ADCON1

Port data latch when written: Port pins when read IBF OBF IBOV RCIF RCIE PSPMODE TXIF TXIE SSPIF SSPIE PCFG3 PORTE Data Direction Bits CCP1IF TMR2IF PCFG2 PCFG1

PSPIF ADIF PSPIE ADIE ADFM

TMR1IF 0000 0000 PCFG0 --0- 0000

CCP1IE TMR2IE TMR1IE 0000 0000

Legend: x = unknown, u = unchanged, - = unimplemented read as '0'. Shaded cells are not used by the Parallel Slave Port.

2.6.3. Registro TRISE


TRISE
Bit 7 6 5 4 3 2 1 Bit 0

IBF

OBF

IBOV

PSPMODE -

IBF Bufer de entrada del puerto paralelo lleno. dato. 0: No se ha recibido ningun 1: Se ha recibido un dato y est a pendiente su lectura. OBF Bufer de salida del puerto paralelo vac o. 0: El bufer de salida se ha le do. Podemos poner otro dato. no se ha le 1: El bufer de salida aun do. de una sobreescritura en el bufer IBOV Deteccion de entrada del puerto paralelo. 0: No ha habido sobreescritura. 1: Se ha escrito en el bufer de entrada un dato antes de haber le do el dato anterior. del modulo PSPMODE Seleccion de Puerto Paralelo Esclavo. 0: Modo de entrada/salida de proposito general en los puertos D y E. 1: Modo Puerto Paralelo Esclavo en los puertos D y E.

Cap tulo 2. Puertos de Entrada/Salida

51

2.6.4. Esquema hardware y cronogramas


Esquema hardware
Data Bus D WR PORT Q RDx pin TTL Q RD PORT One bit of PORTD Set interrupt flag PSPIF (PIR1<7>) D EN EN

CK

Read

TTL

RD

Chip Select TTL Write TTL

CS

WR

Note: I/O pin has protection diodes to VDD and VSS.

Cronograma de escritura
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4

CS WR RD PORTD<7:0> IBF OBF PSPIF

52 Cronograma de lectura
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4

Puerto Paralelo Esclavo

Q1

Q2

Q3

Q4

CS WR RD PORTD<7:0> IBF OBF PSPIF

2.6.5. Ejemplo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

; Activacion del modulo bsf bcf movlw movwf bsf bcf STATUS,RP0 STATUS,RP1 0x06 ADCON1 TRISE,PSPMODE STATUS,RP0 ; Banco 1 ; Puertos A y E digitales ; Activo el modulo PSP ; Banco 0 de registros

; Envio de datos movlw movwf bsf _no_leido btfsc goto bcf 00001111b PORTD STATUS,RP0 TRISE,OBF _no_leido STATUS, RP0 ; Pongo el dato a ser leido ; Banco 1 ; Espera hasta que se lea ; Banco 0

; Recepcion de datos bsf _no_escrito btfss goto bcf movfw STATUS,RP0 TRISE,IBF _no_escrito STATUS, RP0 PORTD ; Banco 1 ; Espera hasta que se escriba ; Banco 0 ; Lee el dato en W

Cap tulo 3 Temporizadores


En tres tiempos se divide la vida: en presente, pasado y futuro. De e stos, el presente es brev simo; el futuro, dudoso; y el pasado, cierto. S eneca

3.1. Temporizador TMR0


3.1.1. Caracter sticas
Se trata de un temporizador/contador de 8 bits. La fuente de eventos puede ser interna o externa: Si OPTION_REG.T0CS = 0 actuar a como temporizador. Si OPTION_REG.T0CS = 1 actuar a como contador de eventos externos recibidos a trav es de la patilla RA4/T0CKI. En este caso se puede seleccionar el anco, de subida OPTION_REG.T0SE = 0 o de bajada OPTION_REG.T0SE = 1. Dispone de una pre-escala programable de 8 bits que se selecciona mediante OPTION_REG.PSA = 0. De lo contrario estar a asociada al perro guardi an. Con OPTION_REG.PS2:PS0 se selecciona el divisor de frecuencia variando desde 1:2 cuando valen 000b a 1:256 cuando valen 111b (ver registro OPTION_REG m as adelante). al desbordarse (de 255 a 0). Para ello es necesario que Produce una interrupcion estas est en activadas: global de interrupciones. INTCON.GIE = 1, habilitacion de la interrupcion asociada a TMR0. INTCON.T0IE = 1, habilitacion El ag INTCON.T0IF, senalizar a (valiendo 1) que se ha producido el desbordamien to y si est an activados los ags correspondientes se producir a la interrupcion. o si queremos detecHay que ponerlo a cero despu es de atender la interrupcion, tar un nuevo desbordamiento. 53

54

Temporizador TMR0 La escritura en el registro TMR0 que lleva la cuenta, anade un retraso de 2 ciclos y borra la cuenta del divisor de frecuencia. de instruccion se conseguir La temporizacion a aplicando la ecuacion: T = 4 Tosc (Cuenta Escala + 2) donde el valor 256 Cuenta se escribir a en el registro TMR0 y el valor Escala se pondr a con los bits OPTION_REG.PS2:PS0.

3.1.2. Esquema hardware


CLKOUT (= FOSC/4) Data Bus 8 1 0 M U X SYNC 2 Cycles TMR0 reg

0 RA4/T0CKI Pin 1 T0SE

M U X

T0CS

PSA PRESCALER

Set Flag Bit T0IF on Overflow

0 M U X

8-bit Prescaler 8 8 - to - 1MUX PS2:PS0

Watchdog Timer

PSA 0 MUX 1 PSA

WDT Enable bit

WDT Time-out

3.1.3. Registros
TMR0, banco 0. (Timer 0 Register) Registro Temporizador numero 0.
OPTION_REG, banco 1. Registro de opciones, algunas del temporizador 0

OPTION REG
Bit 7 6 5 4 3 2 1 Bit 0

/RBPU

INTEDG

T0CS

T0SE

PSA

PS2

PS1

PS0

de las resistencias internas de pull-up del PORTB. /RBPU Bit de habilitacion 0: Activadas. 1: Desactivadas. del anco del pin RB0/INT INTEDG Seleccion 0: Flanco de bajada. 1: Flanco de subida.

Cap tulo 3. Temporizadores


de la fuente de reloj para el temporizador TMR0. T0CS Seleccion interno. Equivale a 4 ciclos de reloj del microcontrolador. 0: Ciclo de instruccion en la patilla RA4/T0CKI. 1: Transicion de anco para la fuente externa del temporizador TMR0. T0SE Seleccion 0: Se incrementar a en el anco de subida de RA4/T0CKI. 1: Se incrementar a en el anco de bajada de RA4/T0CKI. del divisor de frecuencia. PSA Asignacion 0: Pre-escala asignada al temporizador TMR0. 1: Divisor asignado al perro guardi an (WDT) como post-escala. de frecuencia. PS2:PS0 Division Bits 000 001 010 011 100 101 110 111 PSA=0 (TMR0) 1:2 1:4 1:8 1:16 1:32 1:64 1:128 1:256 PSA=1 (WDT) 1:1 1:2 1:4 1:8 1:16 1:32 1:64 1:128

55

Resumen de los registros asociados


TABLE 5-1:
Address 01h,101h 0Bh,8Bh, 10Bh,18Bh 81h,181h

REGISTERS ASSOCIATED WITH TIMER0


Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Value on: POR, BOR xxxx xxxx INTE T0SE RBIE PSA T0IF PS2 INTF PS1 RBIF PS0 0000 000x 1111 1111 Value on all other resets uuuu uuuu 0000 000u 1111 1111

TMR0 INTCON

Timer0 modules register GIE PEIE T0IE T0CS

OPTION_REG RBPU INTEDG

Legend: x = unknown, u = unchanged, - = unimplemented locations read as '0'. Shaded cells are not used by Timer0.

3.1.4. Ejemplos
Si por ejemplo nos dicen que el microcontrolador funciona a 20 MHz y que queremos temporizar 0,5 milisegundos, tendremos que: 0, 5 103 = 4 1 (Cuenta Escala + 2) 20 106

Poniendo la Escala = 64 y despejando saldr a Cuenta = 39. En realidad se tempo qu rizar a T = 0,4996 103 segundos, que para segun e aplicaciones ser a sucientemente preciso o no.
1 2 3 4 5 6 7 8 9

bcf bsf movlw movwf bcf movlw movwf

STATUS,RP1 STATUS,RP0 10000101b OPTION_REG STATUS,RP0 256-39 TMR0

; Banco 1 ; ; ; ; PSA = 0 Preescala para el TMR0 PS2:PS0 = 101 Preescala = 64 T0CS = 0 Reloj interno Banco 0

; TMR0 = 256-39

56
10 11 12 13

Temporizador TMR0

_espera btfss goto

INTCON,T0IF _espera

; Espera a que pasen los 0.5 milisegundos

Mismo ejemplo escrito en lenguaje C.


1 2 3 4 5 6 7 8

PSA = 0; PS2 = 1; PS1 = 0; PS0 = 1; T0CS = 0; TMR0 = 256-39; while(!T0IF);

// Preescala = 64

// Espera

Cap tulo 3. Temporizadores

57

3.2. Temporizador TMR1


3.2.1. Caracter sticas
Es un temporizador/contador de 16 bits formado por los registros TMR1H:TMR1L de 8 bits. Se activa con T1CON.TMR1ON = 1. Puede seleccionar una fuente de reloj interna (T1CON.TMR1CS = 0) o externa (T1CON.TMR1CS = 1) de interrupciones al desbordarse el contador, es decir, al Permite la generacion pasar de 655350. Para ello es necesario que: global de interrupciones. INTCON.GIE = 1, habilitacion local. INTCON.PEIE = 1 y PIE1.TMR1IE = 1, habilitacion Cuando se produzca el desbordamiento el ag PIR1.TMR1IF = 1 para senalizarlo. Este bit hay que borrarlo despu es para detectar el siguiente desbordamiento. Si una interrupcion hay que borrarlo para que no se vuelva a producir. se atendio

3.2.2. Esquema hardware


Set flag bit TMR1IF on Overflow TMR1H 0 1 TMR1ON on/off T1OSC RC0/T1OSO/T1CKI T1OSCEN FOSC/4 Enable Internal Oscillator(1) Clock
(2)

TMR1 TMR1L

Synchronized clock input

T1SYNC Synchronize det Q Clock

1 Prescaler 1, 2, 4, 8 0 2 T1CKPS1:T1CKPS0 TMR1CS

RC1/T1OSI/CCP2

(2)

Note 1: When the T1OSCEN bit is cleared, the inverter is turned off. This eliminates power drain. 2: For the PIC16F873/876, the Schmitt Trigger is not implemented in external clock mode.

3.2.3. Registros
TMR1H, banco 0 (Timer 1 High Part Register) Parte alta del registro temporizador

numero 1.
TMR1L, banco 0 (Timer 1 Low Part Register) Parte baja del registro temporizador

numero 1.

58
T1CON Registro de control del temporizador 1

Temporizador TMR1

T1CON
Bit 7 6 5 4 3 2 1 Bit 0

T1CKPS1 T1CKPS0 T1OSCEN /T1SYNC TMR1CS

TMR1ON

de pre-escala del reloj del temporizador 1. T1CKPS1:T1CKPS0 Bits de seleccion 00: 01: 10: 11: Divisor de frecuencia a 1:1 Divisor de frecuencia a 1:2 Divisor de frecuencia a 1:4 Divisor de frecuencia a 1:8

del Oscilador Externo de TMR1. T1OSCEN Bit de Control de Habilitacion 0: Oscilador desactivado. 1: Oscilador activado. de la entrada de reloj externa de TMR1. /T1SYNC Control de la sincronizacion * Si TMR1CS=1 (reloj externo). 0: Sincroniza la entrada de reloj externa. 1: No sincroniza la entrada de reloj externa. * Si TMR1CS=0 (reloj interno). Se ignora. de la fuente de reloj del TMR1. TMR1CS Seleccion 0: Reloj interno (Fosc /4). 1: Reloj externo desde RC0/T1OSO/T1CKI con anco de subida. del TMR1. TMR1ON Activacion 0: Para el temporizador 1. 1: Habilita el temporizador 1.

Resumen de registros
Address Name Bit 7 GIE Bit 6 PEIE Bit 5 T0IE Bit 4 INTE Bit 3 RBIE Bit 2 T0IF Bit 1 INTF Bit 0 RBIF Value on: POR, BOR Value on all other resets

0Bh,8Bh, INTCON 10Bh, 18Bh 0Ch 8Ch 0Eh 0Fh 10h PIR1 PIE1 TMR1L

0000 000x 0000 000u

PSPIF(1) PSPIE(1)

ADIF ADIE

RCIF RCIE

TXIF TXIE

SSPIF SSPIE

CCP1IF CCP1IE

TMR2IF TMR2IE

TMR1IF TMR1IE

0000 0000 0000 0000 0000 0000 0000 0000 xxxx xxxx uuuu uuuu xxxx xxxx uuuu uuuu

Holding register for the Least Significant Byte of the 16-bit TMR1 register

TMR1H Holding register for the Most Significant Byte of the 16-bit TMR1 register T1CON

T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON --00 0000 --uu uuuu

3.2.4. Funcionamiento como temporizador


Para ello es necesario que: T1CON.TMR1CS = 0, con lo que se contar an ciclos de instruccion. no es tenido en En este caso el bit T1CON.NOT_T1SYNC de control de sincronizacion cuenta.

Cap tulo 3. Temporizadores

59

3.2.5. Funcionamiento como contador


Para ello es necesario que el bit T1CON.TMR1CS = 1, con lo que se incrementar a con el anco de subida, aunque primero es necesario al menos un anco de bajada. Contador sincronizado Esto se consigue haciendo que T1CON.NOT_T1SYNC = 0, con lo que el contador estar a sincronizado con el reloj interno despu es de la escala. Dependiendo del valor de T1CON.T1OSCEN tenemos dos posibilidades:
T1CON.T1OSCEN = 0, con lo que contar a pulsos de la patilla RC0/T1OSO/T1CKI. T1CON.T1OSCEN = 1, con lo que contar a pulsos de la patilla RC1/T1OSI/CCP2.

Adem as en modo SLEEP no se incrementa TMR1 aunque s la pre-escala. Contador as ncrono Este caso se dar a si T1CON.NOT_T1SYNC = 1. En modo SLEEP tambi en se incrementar a TMR1. Las lecturas correctas no est an garantizadas en este modo. Se realizan dos lecturas secuenciales de 8 bits y entre una y otra se puede haber modicado el valor de la cuenta. En las escrituras se recomienda parar el contador, de lo contrario el resultado es impredecible. No se debe usar, en modo as ncrono, como base de tiempos para el modulo de y PWM (CCP). captura/comparacion

3.2.6. Funcionamiento como contador con oscilador externo


Se necesita que:
T1CON.T1OSCEN = 1 lo active, con lo que las patillas RC1/T1OSI y RC0/T1OSO esperan un cristal externo.

Se ignora TRISC<1:0>. Continua oscilando en modo SLEEP. Admite cristales en modo LP (bajo consumo) de hasta 200 kHz. Est a pensado para poner osciladores de 32 kHz y contar segundos. Es necesario asegurar, por software, el retardo de arranque del oscilador.

60

Temporizador TMR1

3.2.7. Reinicio del Temporizador 1


Dispone de un reset interno que: Se genera desde alguno de los modulos CCP. CCP2CON.CCP2M3:CCP2M0 = 1011b Los bits CCP1CON.CCP1M3:CCP1M0 = 1011b o TMR1 debe funcionar como temporizador o contador s ncrono. Los registros CCPRxH:CCPRxL pasan a ser registros periodo del temporizador.

Cap tulo 3. Temporizadores

61

3.3. Temporizador TMR2


3.3.1. Caracter sticas
Temporizador de 8 bits con pre-escala y post-escala. (Fosc /4). Se activa con T2CON.TMR2ON = 1 Cuenta ciclos de instruccion 1:16 mediante T2CON.T2CKPS1:T2CKPS0. Pre-escala seleccionable entre 1:1, 1:4 o Dispone de un registro periodo PR2. El registro TMR2 se incrementa partiendo de cero hasta alcanzar PR2. La salida del temporizador TMR2 pasa por una post-escala programable: 1:1 ... 1:16 (T2CON.TOUTPS3:TOUTPS0) antes de generar una interrupcion. Genera interrupciones si: global. INTCON.GIE = 1, habilitacion local. INTCON.PEIE=1 y PIE1.TMR2IE = 1, habilitacion el periodo. Hay que Cuando el campo PIR1.TMR2IF = 1, indica que se alcanzo borrarlo despu es. Pre-escala y post-escala. Se borran si: Ocurre una escritura en el registro TMR2. Ocurre una escritura en T2CON Se ha iniciado como consecuencia de un reset al arrancar (POR), una acti del reset (/MCLR), un reset por desbordamiento del perro guardi vacion an de alimentacion (BOR). (WDT) o un reset por ca da de tension La salida de TMR2 alimenta el modulo MSSP (Master Synchronous Serial Port) y puede opcionalmente usarse como generador de baudios.

3.3.2. Esquema hardware


Sets flag bit TMR2IF TMR2 output (1) Reset Postscaler 1:1 to 1:16 4 T2OUTPS3: T2OUTPS0 Prescaler 1:1, 1:4, 1:16 2 T2CKPS1: T2CKPS0

TMR2 reg Comparator

FOSC/4

EQ

PR2 reg

Note 1: TMR2 register output can be software selected by the SSP module as a baud clock.

62

Temporizador TMR2

3.3.3. Registros
TMR2, banco 0 (Timer 2 Register). Registro contador. PR2, banco 1 (Period Register for Timer 2). Registro periodo. T2CON, banco 0. Registro de control del temporizador 2

T2CON
Bit 7 6 5 4 3 2 1 Bit 0

TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON

T2CKPS1 T2CKPS0

de la post-escala de salida del temporizador 2. TOUTPS3:TOUTPS0 Bits de seleccion 0000: 0001: 0010: ....: 1111: Divisor de frecuencia a 1:1 Divisor de frecuencia a 1:2 Divisor de frecuencia a 1:3 Divisor de frecuencia a 1:16

del temporizador 2. TMR2ON Bit de control de habilitacion 0: Temporizador desactivado. 1: Temporizador activado. de la pre-escala del temporizador 2. T2CKPS1:T2CKPS0 Bits de seleccion 00: Divisor de frecuencia a 1:1 01: Divisor de frecuencia a 1:4 1x: Divisor de frecuencia a 1:16

Resumen de registros
Address Name Bit 7 GIE PSPIF(1) PSPIE(1) Bit 6 PEIE ADIF ADIE Bit 5 T0IE RCIF RCIE Bit 4 INTE TXIF TXIE Bit 3 RBIE SSPIF SSPIE Bit 2 T0IF CCP1IF CCP1IE Bit 1 INTF TMR2IF TMR2IE Bit 0 RBIF TMR1IF TMR1IE Value on: POR, BOR Value on all other resets

0Bh,8Bh, INTCON 10Bh,18Bh 0Ch 8Ch 11h 12h 92h PIR1 PIE1 TMR2 T2CON PR2

0000 000x 0000 000u 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000

Timer2 modules register TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON T2CKPS1

T2CKPS0 -000 0000 -000 0000 1111 1111 1111 1111

Timer2 Period Register

Cap tulo 4 Conversor Analogico/Digital


El que nada duda nada sabe Proverbio griego

4.1. Caracter sticas


El conversor analogico/digital presente en la familia PIC 16F87x presenta las siguientes caracter sticas: Entradas analogicas multiplexadas. Internamente dispone de un unico conver sor A/D pero incorpora un multiplexor analogico con un numero de entradas dependiente del modelo. 16F877/874: tiene 8 entradas (patillas RA0,RA1,RA2,RA3,RA5,RE0,RE1 y RE2). 16F876/873: tiene 5 entradas (patillas RA0,RA1,RA2,RA3,RA5). Conversor A/D de 10 bits. Son seleccionables por software: Referencias de tension. m RA3/VREF+). Tension axima (VDD o m RA2/VREF-). Tension nima (VSS o Es capaz de funcionar en modo bajo consumo (SLEEP) gracias a un oscilador RC interno.

4.2. Esquema
El esquema hardware asociado junto con los campos que controlan su funcionamiento puede verse en la gura siguiente:

63

64
CHS2:CHS0

Registros asociados

111 110 101 100 VAIN (Input voltage) 011 010 A/D Converter 001

RE2/AN7(1) RE1/AN6(1) RE0/AN5(1) RA5/AN4 RA3/AN3/VREF+ RA2/AN2/VREFRA1/AN1

VDD VREF+ (Reference voltage) PCFG3:PCFG0

000 RA0/AN0

VREF(Reference voltage) VSS PCFG3:PCFG0 Note 1: Not available on 28-pin devices.

4.3. Registros asociados


Para el control del conversor estos microcontroladores disponen de cuatro registros, que son: A/D. ADRESH, banco 0 (A/D Result High). Es la parte alta de la conversion A/D. ADRESL, banco 1 (A/D Result Low). Es la parte baja de la conversion La justiEstos dos registros contienen los 10 bits resultado de la conversion. a la izquierda o a la derecha se selecciona con el campo ADCON1.ADFM segun cacion se ve en la gura:

Cap tulo 4. Conversor Anal ogico/Digital

65

10-Bit Result ADFM = 1 ADFM = 0

7 0000 00

2107

0765 0000 00

ADRESH

ADRESL

ADRESH

ADRESL

10-bit Result Right Justified

10-bit Result Left Justified

ADCON0, banco 0 (A/D Control Register 0) Registro de control AD numero 0. ADCON0


Bit 7 6 5 4 3 2 1 Bit 0

ADCS1

ADCS0

CHS2

CHS1

CHS0

GO/DONE -

ADON

del reloj para la conversion AD. ADCS1:ADCS0 Bits de seleccion 00: 01: 10: 11: 000: 001: 010: 011: 100: 101: 110: 111: Fosc /2 Fosc /8 Fosc /32 FRC . Reloj derivado de un oscilador RC. Canal 0, (RA0/AN0) Canal 1, (RA1/AN1) Canal 2, (RA2/AN2) Canal 3, (RA3/AN3) Canal 4, (RA5/AN4) Canal 5, (RE0/AN5) Canal 6, (RE1/AN6) Canal 7, (RE2/AN7)

del canal analogico CHS2:CHS0 Bits de seleccion a convertir.

Siempre que ADON=1: GO/DONE Estado de la conversion. nalizada. Se pone autom 0: Conversion aticamente a cero al terminar la conversion. en curso. Poner a uno este bit inicia la conversion. 1: Conversion del conversor AD. ADON Activacion 0: Modulo desconectado. No consume corriente. 1: Modulo operativo.

ADCON1, banco 1 (A/D Control Register 1) Registro de control AD numero 1. ADCON1


Bit 7 6 5 4 3 2 1 Bit 0

ADFM

PCFG3

PCFG2

PCFG1

PCFG0

66
del valor de 10 bis. ADFM Formato de justicacion

Conguraci on y adquisici on de datos

a la izquierda. Los 6 bits menos signicativos de ADRESL valdr 0: Justicacion an 0. a la derecha. Los 6 bits m 1: Justicacion as signicativos de ADRESH valdr an 0. del conversor. Segun la gura: PCFG3:PCFG0 Bits de conguracion
PCFG3: PCFG0 0000 0001 0010 0011 0100 0101 011x 1000 1001 1010 1011 1100 1101 1110 1111 AN7(1) RE2 A A D D D D D A D D D D D D D AN6(1) RE1 A A D D D D D A D D D D D D D AN5(1) RE0 A A D D D D D A A A A D D D D AN4 RA5 A A A A D D D A A A A A D D D AN3 RA3 A VREF+ A VREF+ A VREF+ D VREF+ A VREF+ VREF+ VREF+ VREF+ D VREF+ AN2 RA2 A A A A D D D VREFA A VREFVREFVREFD VREFAN1 RA1 A A A A A A D A A A A A A D D AN0 RA0 A A A A A A D A A A A A A A A VREF+ VDD RA3 VDD RA3 VDD RA3 VDD RA3 VDD RA3 RA3 RA3 RA3 VDD RA3 VREFVSS VSS VSS VSS VSS VSS VSS RA2 VSS VSS RA2 RA2 RA2 VSS RA2 CHAN / Refs(2) 8/0 7/1 5/0 4/1 3/0 2/1 0/0 6/2 6/0 5/1 4/2 3/2 2/2 1/0 1/2

A = Analog input D = Digital I/O

4.4. Conguracion y adquisicion de datos


del modulo Para la correcta conguracion conversor AD es necesario que: Las patillas a utilizar est en conguradas como entradas. Para ello deberemos modicar los bits necesarios de los registros TRISA y TRISE. Denamos qu e pines ser an analogicos y cuales digitales a la vez que debemos denir las tensiones de referencia a emplear (ADCON1). Debemos activar el modulo y seleccionar el canal de entrada (ADCON0). Si pretendemos emplear las interrupciones deberemos congurarlas como sigue: Borrando PIR1.ADIF. Activando INTCON.GIE, INTCON.PEIE y PIE1.ADIE. mediante ADCON0.GO_DONE = 1. Ordenar la adquisicion que tarda 10 TAD (el tiempo de conEsperar a que se complete la adquisicion version de cada bit depende de la frecuencia de reloj de conversion programada y de la frecuencia de funcionamiento del microcontrolador). O bien, comprobando si ADCON0.GO_DONE = 0 de nalizacion con PIR1.ADIF. O bien, esperando la noticacion

Cap tulo 4. Conversor Anal ogico/Digital Finalmente tendremos que leer el resultado de la pareja ADRESH:ADRESL. Y borrar PIR1.ADIF si fuera necesario. es preciso esperar un m Antes de una nueva adquisicion nimo de 2 TAD . Adem as habr a que tener en cuenta que: La impedancia m axima de la fuente analogica es de 10k .

67

del reloj de conversion (ADCON0.ADCS1:ADCS0). Se requiere un m La seleccion nimo de 1.6 seg.


TABLE 11-1: T vs. MAXIMUM DEVICE OPERATING FREQUENCIES (STANDARD DEVICES (C))
AD Clock Source (TAD) Operation 2TOSC 8TOSC 32TOSC RC(1, 2, 3) ADCS1:ADCS0 00 01 10 11 Maximum Device Frequency Max. 1.25 MHz 5 MHz 20 MHz Note 1

Note 1: The RC source has a typical TAD time of 4 s but can vary between 2-6 s. 2: When the device frequencies are greater than 1 MHz, the RC A/D conversion clock source is only recommended for sleep operation. 3: For extended voltage devices (LC), please refer to the Electrical Specifications section.

Es capaz de funcionar en modo SLEEP si la fuente de reloj usada es RC. Esto digital. Se despertar evita el ruido de conmutacion a al terminar la conversion (interrupciones activadas).

4.5. Resumen de registros


TABLE 11-2:
Addr
0Bh 0Ch 8Ch 1Eh 9Eh 1Fh 9Fh 85h 05h 89h
(1)

REGISTERS/BITS ASSOCIATED WITH A/D


Bit 7
GIE PSPIF(1) PSPIE(1)

Name
INTCON PIR1 PIE1 ADRESH ADRESL ADCON0 ADCON1 TRISA PORTA TRISE PORTE

Bit 6
PEIE ADIF ADIE

Bit 5
T0IE RCIF RCIE

Bit 4
INTE TXIF TXIE

Bit 3
RBIE SSPIF SSPIE

Bit 2
T0IF CCP1IF CCP1IE

Bit 1
INTF TMR2IF TMR2IE

Bit 0
RBIF TMR1IF TMR1IE

POR, BOR
0000 000x 0000 0000 0000 0000 xxxx xxxx xxxx xxxx

MCLR, WDT
0000 000u 0000 0000 0000 0000 uuuu uuuu uuuu uuuu 0000 00-0 --0- 0000 --11 1111 --0u 0000 0000 -111 ---- -uuu

A/D Result Register High Byte A/D Result Register Low Byte ADCS1 ADFM IBF ADCS0 OBF CHS2 CHS1 CHS0 PCFG3 GO/DONE PCFG2 PCFG1 ADON PCFG0

0000 00-0 --0- 0000 --11 1111 --0x 0000 0000 -111

PORTA Data Direction Register PORTA Data Latch when written: PORTA pins when read IBOV PSPMODE PORTE Data Direction Bits RE2 RE1 RE0

09h(1) Legend: Note 1:

---- -xxx

x = unknown, u = unchanged, - = unimplemented read as '0'. Shaded cells are not used for A/D conversion. These registers/bits are not available on the 28-pin devices.

4.6. Ejemplo
En lenguaje C:

68 Listado 4.1: EX/AD.c


#include <pic.h> void main() { TRISA = TRISB = TRISC = ADCON1=

Ejemplo

0xFF; 0x00; 0x00; 0x00;

// // // // // // // // // // //

Todo entradas Todo salidas Todo salidas PORTA entradas analogicas 11000001b Configura Conversor AD ADCS[1:0] = 11 Oscilador interno RC de 2 a 6 useg. CHS[2:0] = 000 Canal 0 RA0/AN0 GO/DONE = 0 Fin conversion = 0 No usado ADON = 1 Conversor AD habilitado // Borro indicador de fin de conversion // Inicia la conversion // (cuidado con el nombre, es diferente al ensambl.)

10

ADCON0 =0xC1;

15

20

while(1) { ADIF = 0; ADGO = 1;

while(ADIF == 0); // Espera a convertir


25

PORTB = ADRESL; PORTC = ADRESH; }; }

// Saca por los puertos

Cap tulo 5 Memoria EEPROM de datos y Memoria FLASH de programa


Todo el mundo se queja de su memoria, pero nadie de su inteligencia Fran cois de la Rochefoucauld

5.1. Caracter sticas


Las memorias EEPROM de datos y FLASH de programa son accesibles a trav es de 6 registros: EECON1, EECON2, EEDATA, EEDATH, EEADR y EEADRH. La memoria de datos EEPROM Se accede byte a byte (m aximo 256 posiciones) con los registros EEADR y EEDATA activando el proceso con los registros de control EECON1 y EECON2. El tiempo de escritura se controla con un oscilador RC interno. El tiempo de escritura depender a del voltaje y de la temperatura y puede variar en cada chip. La memoria de programa FLASH Es un proceso borra-escribe y mientras dura la escritura no se ejecutan instruc funcionando. Las interrupciones se atienciones aunque los perif ericos continuan den al nalizar la escritura. de memoria. Los registros EEDATH:EEDATA almacenan los 14 bits de cada posicion de 13 bits accedida para lectura o escritura. EEADRH:EEADR indican la direccion Los bits no usados permanecen a cero.

5.2. Registros
partes alta y baja respectivaEEADRH y EEADR. Banco 2. Registros de direccion, mente. 69

70

Registros
EEDATH y EEDATA. Banco 2. Registros de datos, partes alta y baja respectivamente. EECON1, situado en el banco 3: EECON1
Bit 7 6 5 4 3 2 1 Bit 0

EEPGD

WRERR

WREN

WR

RD

de EEPROM de datos o Flash de programa. EEPGD Bit de seleccion 0: Accede a la memoria de datos. 1: Accede a la memoria de programa. WRERR Bit de error en la escritura. correctamente. 0: La escritura termino de escritura termino prematuramente. 1: La operacion de escritura. WREN Habilitacion 0: Proh be la escritura. 1: Permite la escritura. WR Bit de control de la escritura. 0: Ciclo de escritura completo. 1: Inicia un ciclo de escritura. Vuelve a cero al nalizar la escritura. RD Bit de control de la lectura. 0: No inicia el proceso de lectura. l solo. 1: Inicia el proceso de lectura. Vuelve a cero e EECON2, situado en el banco 3. No es un registro f sico. Se usa en la secuencia de escritura.

Registros asociados
Address Name Bit 7
GIE

Bit 6
PEIE

Bit 5
T0IE

Bit 4
INTE

Bit 3
RBIE

Bit 2
T0IF

Bit 1
INTF

Bit 0
RBIF

Value on: POR, BOR


0000 000x xxxx xxxx

Value on all other resets


0000 000u uuuu uuuu uuuu uuuu uuuu uuuu uuuu uuuu x--- u000

0Bh, 8Bh, INTCON 10Bh, 18Bh 10Dh 10Fh 10Ch 10Eh 18Ch 18Dh 8Dh 0Dh EEADR EEADRH EEDATA EEDATH EECON1 EECON2 PIE2 PIR2

EEPROM address register EEPROM address high

xxxx xxxx xxxx xxxx

EEPROM data resister EEPGD EEPROM data resister high WRERR WREN WR RD

xxxx xxxx x--- x000

EEPROM control resister2 (not a physical resister) (1) (1) EEIE EEIF BCLIE BCLIF CCP2IE CCP2IF -r-0 0--0 -r-0 0--0 -r-0 0--0 -r-0 0--0

x = unknown, u = unchanged, r = reserved, - = unimplemented read as 0. Shaded cells are not used during FLASH/ EEPROM access. Note 1: These bits are reserved; always maintain these bits clear.

Legend:

Cap tulo 5. Memorias EEPROM y FLASH

71

5.3. Escritura de la memoria EEPROM de datos


BSF BCF MOVLW MOVWF MOVLW MOVWF BSF BCF BSF BCF MOVLW MOVWF MOVLW MOVWF BSF BSF SLEEP BCF STATUS, RP1 STATUS, RP0 DATA_EE_ADDR EEADR DATA_EE_DATA EEDATA STATUS, RP0 EECON1, EEPGD EECON1, WREN INTCON, GIE 55h EECON2 AAh EECON2 EECON1, WR INTCON, GIE EECON1, WREN ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; Banco 2 Direccion de memoria de datos Dato a escribir Banco 3 Apunta a la EEPROM de datos Habilita la escritura Desactiva las interrupciones Secuencia requerida Secuencia requerida Ordena la escritura Activa las interrupciones Se duerme y espera a que termine Desactiva la escritura

5.4. Lectura de la memoria EEPROM de datos


BSF BCF MOVLW MOVWF BSF BCF BSF BCF MOVF STATUS, RP1 STATUS, RP0 DATA_EE_ADDR EEADR STATUS, RP0 EECON1, EEPGD EECON1, RD STATUS, RP0 EEDATA, W ; ; ; ; ; ; ; ; ; Banco 2 Direccion a leer Banco 3 Apunta a la EEPROM Ordena la lectura Banco 2 W = EEDATA

5.5. Escritura de la memoria Flash de programa


BSF BCF MOVLW MOVWF MOVLW MOVWF MOVLW MOVWF MOVLW MOVWF BSF BSF BSF BCF MOVLW MOVWF MOVLW MOVWF BSF NOP STATUS, STATUS, ADDRH EEADRH ADDRL EEADR DATAH EEDATH DATAL EEDATA STATUS, EECON1, EECON1, INTCON, 55h EECON2 AAh EECON2 EECON1, RP1 RP0 ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; Banco 2 Parte alta de la direccion Parte baja de la direccion Parte alta del dato a escribir Parte baja del dato a escribir Banco 3 Apunta a la memoria de programa Habilita la escritura Desactiva las interrupciones Escribe 55h en EECON2 Escribe AAh en EECON2 Ordena la escritura Estas dos instrucciones son ignoradas

RP0 EEPGD WREN GIE

WR

72
NOP ; ; ; ; ; ; ;

Lectura de la memoria Flash de programa


por el microcontrolador Detiene la ejecucion y espera a que se termine la escritura Despues continua con la tercera instruccion Habilita las interrupciones Desactiva la escritura

BSF BCF

INTCON, GIE EECON1, WREN

Solo puede ser escrita si es un bloque de memoria no protegido y el bit de congu WRT = 1. racion

5.6. Lectura de la memoria Flash de programa


BSF BCF MOVLW MOVWF MOVLW MOVWF BSF BSF BSF NOP NOP BCF MOVF MOVF STATUS, STATUS, ADDRH EEADRH ADDRL EEADR STATUS, EECON1, EECON1, RP1 RP0 ; ; ; ; ; ; ; ; ; ; ; ; ; ; Banco 2 Parte alta de la direccion a leer

RP0 EEPGD RD

Parte baja de la direccion Banco 3 Apunta a la memoria de programa Ordena la lectura y tarda dos ciclos Banco 2 W = parte baja W = parte alta del dato leido

STATUS, RP0 EEDATA, W EEDATH, W

5.7. Proteccion de la memoria


Memoria EEPROM de datos Se protege con EECON1.WR = 0 (durante PowerUp y Brown-out) Memoria Flash de programa WRT = 0 evita escrituras no deseadas debido a un malfunEl bit de conguracion cionamiento del micro. WRT y CP1:0 se puede seleccionar el modo de Mediante los bits de conguracion como se puede apreciar en la siguiente tabla: proteccion

Cap tulo 5. Memorias EEPROM y FLASH


TABLE 4-1: READ/WRITE STATE OF INTERNAL FLASH PROGRAM MEMORY
Memory Location CP1 0 0 0 0 0 1 1 1 1 1 1 CP0 0 1 1 1 1 0 0 0 0 1 1 WRT x 0 0 1 1 0 0 1 1 0 1 All program memory Unprotected areas Protected areas Unprotected areas Protected areas Unprotected areas Protected areas Unprotected areas Protected areas All program memory All program memory Internal Read Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Internal Write No No No Yes No No No Yes No No Yes ICSP Read ICSP Write No Yes No Yes No Yes No Yes No Yes Yes No No No No No No No No No Yes Yes Configuration Bits

73

ser Esto signica que las zonas con proteccion an, dependiendo del modelo y de los bis de proteccion: CP1:CP0 00 01 10 11 PIC16F877/874 0000h 1FFFh 1000h 1FFFh 1F00h 1FFFh Ninguna PIC16F876/873 0000h 0FFFh 0800h 0FFFh 0F00h 0FFFh Ninguna

Cuando se programa en lenguaje C existen unas macros que nos ayundan a esto y que son:
#include <pic.h> // ... EEPROM_WRITE(addr, value); value = EEPROM_READ(addr); FLASH_WRITE(addr, value); value = FLASH_READ(addr);

Para denir el contenido de la memoria EEPROM de datos desde el propio programa en lenguaje C se emplea la siguiente macro:
#include <pic.h> // ... // La macro define el contenido de la EEPROM de 8 en 8 bytes __EEPROM_DATA(0,1,2,3,4,5,6,7); // La primera a partir de la dir. 0 __EEPROM_DATA(0,1,2,3,4,5,6,7); // Estos iran a partir de la dir. 8 // .. etc.

74

Protecci on de la memoria

Cap tulo 6 Modulos CCP: Captura/Comparacion y PWM


El genio se compone del dos por ciento de talento y del noventa y ocho por ciento de perseverante aplicaci on. Ludwig van Beethoven

6.1. Caracter sticas


La familia de microcontroladores 16F87x dispone de dos modulos multifuncionales y PWM (Pulse Width Modulation). de Captura/Comparacion Cada modulo CCP contiene un registro de 16 bits que puede operar como: Registro de Captura. Registro de Comparacion. por Anchura de Pulsos) maeRegistro ciclo de trabajo para PWM (Modulacion stro/esclavo. se ve en la gura: asoci andose al temporizador TMR1 o al temporizador TMR2 segun
CCP Mode
Capture Compare PWM

Timer Resource
Timer1 Timer1 Timer2

Sin embargo, existen algunas limitaciones en cuanto a las interacciones entre los dos modulos:
TABLE 8-2: INTERACTION OF TWO CCP MODULES
Interaction
Same TMR1 time-base. The compare should be configured for the special event trigger, which clears TMR1. The compare(s) should be configured for the special event trigger, which clears TMR1. The PWMs will have the same frequency and update rate (TMR2 interrupt). None. None.

CCPx Mode CCPy Mode


Capture Capture Compare PWM PWM PWM Capture Compare Compare PWM Capture Compare

75

76

Registros

6.1.1. Modulo CCP1


Est a compuesto de dos registros de 8 bits llamados CCPR1H y CCPR1L. Se controla con el registro CCP1CON. Es capaz de reiniciar TMR1 al comparar y coincidir.

6.1.2. Modulo CCP2


Est a compuesto de dos registros de 8 bits llamados CCPR2H y CCPR2L. Se controla con el registro CCP2CON. Es capaz de reiniciar TMR1 al comparar y coincidir, y adem as disparar el funcionamiento del conversor A/D.

6.2. Registros
CCPR1H y CCPR1L, banco 0. Registros de cuenta parte alta y parte baja del modulo CCP1. CCPR2H y CCPR2L, banco 0. Registros de cuenta parte alta y parte baja del modulo CCP2. CCP1CON y CCP2CON, banco 0. Registro de control de los modulos CCP1 y CCP2 respectivamente CCPxCON
Bit 7 6 5 4 3 2 1 Bit 0

CCPxX

CCPxY

CCPxM3

CCPxM2

CCPxM1

CCPxM0

CCPxX:CCPxY Bits menos signicativos en modo PWM. PWM. Los ocho Son los dos bits menos signicativos del ciclo de trabajo en la modulacion bits m as signicativos estar an en CCPRxL. del modo de funcionamiento del modulo CCPxM3:CCPxM0 Bits de seleccion CCPx. Desactiva el modulo CCPx. Modo captura cada anco de bajada. Modo captura cada anco de subida. Modo captura cada cuarto anco de subida. Modo captura cada decimosexto anco de subida. salida a uno al coincidir. Se hace (CCPxIF = 1). Modo comparacion, salida a cero al coincidir. Se hace (CCPxIF = 1). Modo comparacion, genera interrupcion software al coincidir. Se hace (CCPxIF = 1). Modo comparacion, La patilla RC2/CCP1 o RC1/CCP2 no cambia. dispara un evento especial. Se hace (CCPxIF = 1). La patilla 1011: Modo comparacion, RC2/CCP1 o RC1/CCP2 no cambia. * CCP1 reinicia TMR1. A/D (si est * CCP2 reinicia TMR1 y arranca la conversion a habilitado el modulo conversor A/D). 11xx: Modo PWM. 0000: 0100: 0101: 0110: 0111: 1000: 1001: 1010:

Cap tulo 6. M odulos CCP Registros asociados a la captura, comparacion y al temporizador TMR1
TABLE 8-3:
Address

77

REGISTERS ASSOCIATED WITH CAPTURE, COMPARE, AND TIMER1


Bit 7
GIE PSPIF(1) PSPIE
(1)

Name

Bit 6
PEIE ADIF ADIE

Bit 5
T0IE RCIF RCIE

Bit 4
INTE TXIF TXIE

Bit 3
RBIE SSPIF SSPIE

Bit 2
T0IF CCP1IF CCP1IE

Bit 1
INTF TMR2IF TMR2IE

Bit 0
RBIF

Value on: POR, BOR

Value on all other resets

0Bh,8Bh, INTCON 10Bh,18Bh 0Ch 0Dh 8Ch 8Dh 87h 0Eh 0Fh 10h 15h 16h 17h 1Bh 1Ch 1Dh PIR1 PIR2 PIE1 PIE2 TRISC TMR1L TMR1H T1CON CCPR1L CCPR1H CCP1CON CCPR2L CCPR2H CCP2CON

0000 000x 0000 000u

TMR1IF 0000 0000 0000 0000 CCP2IF ---- ---0 ---- ---0 TMR1IE 0000 0000 0000 0000 CCP2IE ---- ---0 ---- ---0 1111 1111 1111 1111 xxxx xxxx uuuu uuuu xxxx xxxx uuuu uuuu

PORTC Data Direction Register Holding register for the Least Significant Byte of the 16-bit TMR1 register Holding register for the Most Significant Byte of the 16-bit TMR1 register

T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON --00 0000 --uu uuuu xxxx xxxx uuuu uuuu xxxx xxxx uuuu uuuu CCP1M3 CCP1M2 CCP1M1 CCP1M0 --00 0000 --00 0000 xxxx xxxx uuuu uuuu xxxx xxxx uuuu uuuu CCP2M3 CCP2M2 CCP2M1 CCP2M0 --00 0000 --00 0000

Capture/Compare/PWM register1 (LSB) Capture/Compare/PWM register1 (MSB) CCP1X CCP1Y

Capture/Compare/PWM register2 (LSB) Capture/Compare/PWM register2 (MSB) CCP2X CCP2Y

Registros asociados a la modulacion por anchura de pulsos (PWM) y al temporizador TMR2


Address Name Bit 7 GIE PSPIF(1) PSPIE(1) Bit 6 PEIE ADIF ADIE Bit 5 T0IE RCIF RCIE Bit 4 INTE TXIF TXIE Bit 3 RBIE SSPIF SSPIE Bit 2 T0IF CCP1IF CCP1IE Bit 1 INTF TMR2IF TMR2IE Bit 0 RBIF Value on: POR, BOR Value on all other resets

0Bh,8Bh, INTCON 10Bh,18Bh 0Ch 0Dh 8Ch 8Dh 87h 11h 92h 12h 15h 16h 17h 1Bh 1Ch 1Dh Legend: PIR1 PIR2 PIE1 PIE2 TRISC TMR2 PR2 T2CON CCPR1L CCPR1H CCP1CON CCPR2L CCPR2H CCP2CON = unknown,

0000 000x 0000 000u

TMR1IF 0000 0000 0000 0000 CCP2IF ---- ---0 ---- ---0 TMR1IE 0000 0000 0000 0000 CCP2IE ---- ---0 ---- ---0 1111 1111 1111 1111 0000 0000 0000 0000 1111 1111 1111 1111

PORTC Data Direction Register Timer2 modules register Timer2 modules period register

TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON T2CKPS1 T2CKPS0 -000 0000 -000 0000 xxxx xxxx uuuu uuuu xxxx xxxx uuuu uuuu CCP1M3 CCP1M2 CCP1M1 CCP1M0 --00 0000 --00 0000 xxxx xxxx uuuu uuuu xxxx xxxx uuuu uuuu CCP2M3 CCP2M2 CCP2M1 CCP2M0 --00 0000 --00 0000

Capture/Compare/PWM register1 (LSB) Capture/Compare/PWM register1 (MSB) CCP1X CCP1Y

Capture/Compare/PWM register2 (LSB) Capture/Compare/PWM register2 (MSB) CCP2X CCP2Y

= unchanged,

= unimplemented read as '0'. Shaded cells are not used by PWM and Timer2.

6.3. Modo Captura


Consiste en capturar el valor del temporizador TMR1 en CCPR1H:CCPR1L cuando ocurre en la patilla RC2/CCP1 o RC1/CCP2 un evento:

78 Cada anco de bajada. Cada anco de subida. Cada 4 ancos de subida. Cada 16 ancos de subida.

Modo Captura

La patilla RC2/CCP1 o RC1/CCP2 debe ser congurada como entrada.


Prescaler 1, 4, 16 RC2/CCP1 Pin and edge detect Set flag bit CCP1IF (PIR1<2>)

CCPR1H Capture Enable TMR1H CCP1CON<3:0> Qs

CCPR1L

TMR1L

TMR1 debe funcionar en modo temporizador o contador s ncrono. Produce interrupciones si: global de interrupciones. INTCON.GIE = 1, habilitacion de interrupciones para perif INTCON.PEIE = 1, habilitacion ericos. PIE2.CCP2IE = 1, habilitacion local PIE1.CCP1IE = 1 o El campo PIR1.CCP1IF = 1 o PIR2.CCP2IF = 1 senalizar a el suceso. Hay que borrarlo despu es tanto si las interrupciones est an activadas (para indicar que fue atendida) como si no. Para cambiar la pre-escala es importante parar el modo captura. Esto se puede hacer con CCP1CON = 00000000b. Ejemplo Listado 6.1: EX/EX CAPTURA/CAPTURA.C
#include <pic.h> #include "binario.h" void interrupt ISR(void) { TMR1H = 0; TMR1L = 0; // TMR1 = 0 CCP1IF = 0; // Borro la notificaci on } void main() { TRISC2 = 1; CCP1IE = 1; PEIE = 1; GIE = 1;

10

// RC2 entrada // Activo las interrupciones

15

Cap tulo 6. M odulos CCP


// Desactivo TMR1, div. frec=1:1 // osc. ext. desactivado, reloj interno // Cada paso es 1 microsegundo CCP1CON = B00000101; // Captura cada flanco de subida TMR1H = 0; TMR1L = 0; // TMR1 = 0 TMR1ON = 1; // Activa el TMR1 while(1); // Bucle sin fin // Visualizaremos CCPR1H:CCPR1L y deber a // coincidir con el periodo de la se nal // del generador T1CON = 0;

79

20

25

30

6.4. Modo Comparacion


Consiste en comparar TMR1H:TMR1L con CCPR1H:CCPR1L (idem con el modulo CCP2). la RC1/CCP2 pasara a: Cuando haya coincidencia la patilla RC2/CCP1 o Valer 1. Valer 0. No cambia, pero se genera una interrupcion. se programar La accion a con CCP1CON.CCP1M3:CCP1M0.

80 RC1/CCP2 debe ser congurado como salida. RC2/CCP1 o


Special event trigger will: reset Timer1, but not set interrupt flag bit TMR1IF (PIR1<0>), and set bit GO/DONE (ADCON0<2>). Special Event Trigger Set flag bit CCP1IF (PIR1<2>) CCPR1H CCPR1L Q S Output Logic match RC2/CCP1 R Pin TRISC<2> Output Enable CCP1CON<3:0> Mode Select Comparator TMR1H TMR1L

Modo Comparaci on

TMR1 debe funcionar en modo temporizador o contador s ncrono. Produce interrupciones si se selecciona CCP1CON.CCP1M3:CCP1M0 = 1010b o CCP2CON.CCP2M3:CCP2M0 = 1010b y: global de interrupciones, INTCON.GIE = 1, habilitacion de interrupciones de los perif INTCON.PEIE = 1, habilitacion ericos, PIE2.CCP2IE = 1, habilitacion local. PIE1.CCP1IE = 1 o PIR2.CCP2IF = 1, senalizar El campo PIR1.CCP1IF = 1 o a el evento. Hay que borrarlo despu es. El modo de evento especial se selecciona con: CCP1CON.CCP1M3:CCP1M0 = 1011b y consiste en: Reinicia TMR1 (CCPR1H:CCPR1L o CCPR2H:CCPR2L funcionar an como un registro periodo). Y si est an funcionando los dos? Creo que se queda con el de menor periodo. Comprobar. A/D (si est En CCP2, adem as, iniciar a la conversion a activada). Ejemplo Listado 6.2: EX/EX COMPARACION/COMPARA.C
#include <pic.h> #include "binario.h" void interrupt ISR(void) { if(RC2) RC2 = 0; else RC2 = 1; TMR1H = 0; TMR1L = 0; // TMR1 = 0 CCP1IF = 0; // Borro la notificaci on } void main() {

10

Cap tulo 6. M odulos CCP


15

81

TRISC2 CCP1IE PEIE GIE T1CON

= = = =

0; 1; 1; 1;

// RC2 salida // Activo las interrupciones

20

25

// Desactivo TMR1, div. frec=1:1 // osc. ext. desactivado, reloj interno // Cada paso es 1 microsegundo CCP1CON = B00001010; // Comparaci on. CCP1 no cambia CCPR1H = (3000>>8); CCPR1L = (3000&0xFF); // 3000 microsegundos TMR1ON = 1; // Activa el TMR1 while(1); } // Bucle sin fin

= 0;

30

6.5. Modo PWM (Modulacion por Anchura de Pulsos)


PWM con 10 bits de resolucion. Produce una senal

Periodo=PR2 Ciclo de trabajo=CCPR1L

82

Modo PWM (Modulaci on por Anchura de Pulsos) RC1/CCP2 debe congurarse como salida. EL esquema La patilla RC2/CCP1 o hardware es como sigue:
Duty Cycle Registers CCPR1L CCP1CON<5:4>

CCPR1H (Slave)

Comparator

Q RC2/CCP1

TMR2

(Note 1) S TRISC<2> Clear Timer, CCP1 pin and latch D.C.

Comparator

PR2

Note 1: 8-bit timer is concatenated with 2-bit internal Q clock or 2 bits of the prescaler to create 10-bit time-base.

PWM se calcula: El periodo de la senal TP W M = [P R2 + 1] 4 Tosc P reescalaT imer2 Ejemplo: * Sea Fosc = 4 MHz, luego 4Tosc = 1 microsegundo. * Sea FP W M = 1 kHz, luego TP W M = 1 milisegundo. * Aplicando la ecuacion: 103 = (P R2 + 1) 106 16 sale PR2= 61,5. Si hacemos PR2= 62 tendremos un periodo de 1,008 ms lo que dar a una frecuencia de 992,06 Hz. M as que aceptable. Al cumplir el periodo TMR2 es borrado. la RC1/CCP2 se pone a 1 (si el ciclo trabajo es distinto La patilla RC2/CCP1 o de 0). El ciclo de trabajo CCPR1H (solo lectura)= CCPR1L. El ciclo de trabajo (hasta 10 bits) se especica en CCPR1L (8 bits m as signicativos) y CCP1CON.[CCP1X y CCP1Y] (2 bits menos signicativos) CicloT rabajo = CCP R1L : CCP 1CON < 5 : 4 > Tosc P reescalaT imer2 medido en segundos, siendo CicloT rabajo < P R2. la RC1/CCP2 pasa a 0. Cuando se cumple este intervalo, la patilla RC2/CCP1 o

Cap tulo 6. M odulos CCP


osc ser La resolucion a de log2 ( FF ) bits. PWM

83

Protocolo a seguir: Se escribe el periodo en PR2 (banco 1) y se dene la pre-escala con (T2CON.T2CKPS1:T2CKPS0). Se escribe el ciclo de trabajo en CCPR1L y CCP1CON.CCP1X:CCP1Y Se congura RC2/CCP1 como pin de salida. Se activa TMR2 con T2CON y se inicia la pre-escala. Se congura el modulo CCP1 para modo PWM. Ejemplo Listado 6.3: EX/EX PWM/PWM.C
#include <pic.h> #include "binario.h" void main() { TRISC2 = 0; TRISC1 = 0;

// RC2 salida // RC1 salida

10

// Queremos una se nal PWM que tenga un periodo de 1 KHz // y el microcontrolador funciana a 4 MHz // luego aplicando la ecuacion sale que PR2 = 62 y que la // pre-escala = 16 PR2 = 62; T2CKPS1 = 1; // Preescala = 1:16

15

20

CCPR1L = 15; // 15/62 => 25 % ciclo de trabajo CCP1X = CCP1Y = 0; // Dos bits menos signif. a cero CCP1M3 = 1; CCP1M2 = 1; // Activo modo PWM TMR2ON = 1; // Activo TMR2 while(1); // Bucle sin fin }

84

Modo PWM (Modulaci on por Anchura de Pulsos)

Cap tulo 7 Modulo USART


La humanidad progresa. Hoy solamente quema mis libros; siglos atr as me hubieran quemado a mi Sigmund Freud

7.1. Caracter sticas


El modulo USART (Universal Synchronous Asynchronous Receiver Transmitter) es un interfaz de comunicaciones serie, tambi en conocido como SCI (Serial Communication Interface). Puede ser congurado como: Modo as ncrono (full duplex). Modo s ncrono maestro (half duplex). Modo s ncrono esclavo (half duplex). Independientemente del modo debemos: Habilitarlo con RCSTA.SPEN = 1. Y dependiendo del modo (TX salida, RX entrada): Congurar TRISC.6 = 0 (pin RC6/TX/CK como salida). TRISC.7 = 1 (pin RC7/RX/DT como entrada).

7.2. Registros
TXREG. En el banco 0. Registro de transmision. RCREG. En el banco 0. Registro de recepcion. TXSTA. En el banco 1. Registro de estado y control para la transmision. TXSTA
Bit 7 6 5 4 3 2 1 Bit 0

CSRC

TX9

TXEN

SYNC

BRGH

TRMT

TX9D

85

86

Registros
de la fuente de reloj. En modo as CSRC Seleccion ncrono no importa. En modo s ncrono: 0: Modo esclavo. El reloj es externo. 1: Modo maestro. El reloj proviene del generador de baudios. del noveno bit. TX9 Activa la transmision de 8 bits. 0: Transmision de 9 bits. 1: Transmision TXEN Activa la transmision. desactivada. 0: Transmision activada. 1: Transmision del modo de funcionamiento. SYNC Seleccion 0: Modo as ncrono. 1: Modo s ncrono. BRGH Selecciona el rango de velocidades altas. Empleado en modo as ncrono. 0: Velocidad baja. 1: Velocidad alta. TRMT Estado del registro de desplazamiento de la transmision. 0: Registro lleno/ocupado. 1: Registro vac o. de 9 bits. Representar TX9D Noveno bit a transmitir si est a activada la transmision a el bit de paridad.

RCSTA. En el banco 0. Registro de estado y control de la recepcion. RCSTA


Bit 7 6 5 4 3 2 1 Bit 0

SPEN

RX9

SREN

CREN

ADDEN

FERR

OERR

RX9D

SPEN Habilita el modulo USART. 0: Desactivado. 1: Activado. del noveno bit. RX9 Activa la recepcion de 8 bits. 0: Recepcion de 9 bits. 1: Recepcion de un unico SREN Activa la recepcion dato. Solamente en modo s ncrono maestro. 0: Desactivada 1: Activada. continua de datos. CREN Activa la recepcion * Modo as ncrono: 0: Desactivado. 1: Activado. * Modo s ncrono: 0: Desactivado. 1: Activado hasta que se ponga de nuevo a cero (m as prioridad que SREN) de direccion. Solo en modo as ADDEN Activa la deteccion ncrono con 9 bits. 0: Desactivado. Todos lo recibido son datos y el noveno bit es la paridad. y carga del bufer cuando el noveno bit 1: Activado. Habilita la interrupcion de recepcion vale 1.

Cap tulo 7. M odulo USART


FERR Error de marcaje. 0: No hay error. 1. 1: El bit de stop no valio OERR Error de sobreescritura. 0: No hay error. otro dato antes de leer el anterior. 1: Se recibio

87

de 9 bits. Representar RX9D Noveno bit recibido si est a activada la recepcion a el bit de paridad. SPBRG. En el banco 1. Es el valor base para el funcionamiento del generador de

baudios.

7.3. Generador de baudios


Funciona en modo as ncrono y s ncrono. Es un temporizador de 8 bits. del generador de pulsos, El registro SPBRG controla el periodo de la temporizacion aunque condicionado por TXSTA.BRGH y TXSTA.SYNC (modo as ncrono o s ncrono) se indica en la gura: seg un TABLE 10-1: BAUD RATE FORMULA
SYNC
0 1

BRGH = 0 (Low Speed) (Asynchronous) Baud Rate = FOSC/(64(X+1)) (Synchronous) Baud Rate = FOSC/(4(X+1))

BRGH = 1 (High Speed) Baud Rate= FOSC/(16(X+1)) NA

X = value in SPBRG (0 to 255)

La escritura en SPBRG reinicia la cuenta. en RC7/RX/DT se muestrea 3 veces durante el ciclo dado por SPBRG y se La senal decide su valor por mayor a. As en el caso de BRGH=1 as ncrono (alta velocidad) tendremos: X= FOSC 1 16 Baudios

88

Generador de baudios

Tabla para el generador de baudios segun la frecuencia. Modo as ncrono lento (BRGH=0)
TABLE 10-3:
BAUD RATE (K) 0.3 1.2 2.4 9.6 19.2 28.8 33.6 57.6 HIGH LOW

BAUD RATES FOR ASYNCHRONOUS MODE (BRGH = 0)


FOSC = 16 MHz % ERROR 0.17 0.17 0.16 0.16 3.55 6.29 8.51 SPBRG value (decimal) 207 103 25 12 8 6 3 255 0 FOSC = 10 MHz % ERROR 0.17 0.17 1.73 1.72 8.51 6.99 9.58 SPBRG value (decimal) 129 64 15 7 4 4 2 255 0 SPBRG value (decimal) 255 129 31 15 9 8 4 255 0

FOSC = 20 MHz % ERROR 1.75 0.17 1.73 1.72 8.51 3.34 8.51 FOSC = 4 MHz BAUD RATE (K) KBAUD 0.3 1.2 2.4 9.6 19.2 28.8 33.6 57.6 HIGH LOW 0.300 1.202 2.404 8.929 20.833 31.250 62.500 0.244 62.500 % ERROR 0 0.17 0.17 6.99 8.51 8.51 8.51 SPBRG value (decimal) 207 51 25 6 2 1 0 255 0

KBAUD 1.221 2.404 9.766 19.531 31.250 34.722 62.500 1.221 312.500

KBAUD 1.202 2.404 9.615 19.231 27.778 35.714 62.500 0.977 250.000

KBAUD 1.202 2.404 9.766 19.531 31.250 31.250 52.083 0.610 156.250

FOSC = 3.6864 MHz % ERROR 0.33 1.33 1.33 2.90 2.90 2.90 SPBRG value (decimal) 185 46 22 5 2 0 255 0

KBAUD 0.301 1.216 2.432 9.322 18.643 55.930 0.218 55.930

Tabla para el generador de baudios segun la frecuencia. Modo as ncrono r apido (BRGH=1)
TABLE 10-4:
BAUD RATE (K) 0.3 1.2 2.4 9.6 19.2 28.8 33.6 57.6 HIGH LOW BAUD RATE (K) KBAUD 0.3 1.2 2.4 9.6 19.2 28.8 33.6 57.6 HIGH LOW 1.202 2.404 9.615 19.231 27.798 35.714 62.500 0.977 250.000

BAUD RATES FOR ASYNCHRONOUS MODE (BRGH = 1)


FOSC = 16 MHz % ERROR 0.16 0.16 2.13 0.79 2.13 SPBRG value (decimal) 103 51 33 29 16 255 0 FOSC = 10 MHz % ERROR 1.71 0.16 1.72 1.36 2.10 1.36 SPBRG value (decimal) 129 64 42 36 20 255 0

FOSC = 20 MHz % ERROR 0.16 0.16 0.94 0.55 3.34 FOSC = 4 MHz % ERROR 0.17 0.17 0.16 0.16 3.55 6.29 8.51 SPBRG value (decimal) 207 103 25 12 8 6 3 255 0

KBAUD 9.615 19.231 29.070 33.784 59.524 4.883 1250.000

KBAUD 9.615 19.231 29.412 33.333 58.824 3.906 1000.000

KBAUD 2.441 9.615 19.531 28.409 32.895 56.818 2.441 625.000

SPBRG value (decimal) 255 64 31 21 18 10 255 0

FOSC = 3.6864 MHz % ERROR 0.25 0.25 1.32 2.90 2.90 4.88 2.90 SPBRG value (decimal) 185 92 22 11 7 6 3 255 0

KBAUD 1.203 2.406 9.727 18.643 27.965 31.960 55.930 0.874 273.722

Cap tulo 7. M odulo USART

89

7.4. Modo as ncrono: transmision


Funcionamiento El dato a transmitir se deposita en TXREG. Cuando se termina de transmitir el dato anterior se traslada autom aticamente al registro de desplazamiento TSR y se indica con PIR1.TXIF (TXREG vac o). Si para recargarlo. PIE1.TXIE = 1 se produce una interrupcion Se extraen de TSR los bits (LSBit..MSBit) al ritmo indicado por el generador de baudios a trav es de RC6/TX. El dato se precede de un bit de inicio (0) y al nal se anade un bit de parada (1). El bit TXSTA.TRMT indica cuando se ha terminado de transmitir el contenido de TSR.
Data Bus TXIF TXIE MSb (8) Interrupt TXEN Baud Rate CLK TRMT SPBRG Baud Rate Generator TX9 TX9D SPEN TXREG register 8 TSR register LSb 0 Pin Buffer and Control RC6/TX/CK pin

Secuencia de operaciones Se debe congurar RC6/TX/CK como salida y RC7/RX/DT como entrada. RCSTA.SPEN = 1 habilitar a el modulo USART.
TXSTA.SYNC = 0 activar a el modo as ncrono.

Si queremos interrupciones (PIE1.TXIE = 1, INTCON.GIE = 1 y INTCON.PEIE = 1). Si queremos trasmitir datos de 9 bits, TXSTA.TX9 = 1. El noveno bit deber a estar en TXSTA.TX9D. Se inicia SPBRG y se congura TXSTA.BRGH para la velocidad deseada. con TXSTA.TXEN = 1. Se activa la transmision El microcontrolador pondr a PIR1.TXIF = 1 para indicar que hay que poner un dato. Pondremos el dato en TXREG (y TXSTA.TX9D, si 9 bits).

90

Modo as ncrono: transmisi on Se transmite el dato y se espera otro (PIR1.TXIF = 1). Se producir a una interrup si est cion an habilitadas.

Cronograma y esquema hardware


Write to TXREG BRG output (shift clock) RC6/TX/CK (pin) TXIF bit (Transmit buffer reg. empty flag) Word 1

Start Bit

Bit 0

Bit 1 Word 1

Bit 7/8

Stop Bit

TRMT bit (Transmit shift reg. empty flag)

Word 1 Transmit Shift Reg

Registros asociados a la transmision


TABLE 10-5:
Address 0Ch 18h 19h 8Ch 98h 99h Name PIR1 RCSTA PIE1 TXSTA

REGISTERS ASSOCIATED WITH ASYNCHRONOUS TRANSMISSION


Bit 7
PSPIF(1) SPEN PSPIE(1) CSRC Bit 6 ADIF RX9 ADIE TX9 Bit 5 RCIF SREN RCIE TXEN Bit 4 TXIF CREN TXIE SYNC Bit 3 SSPIF Bit 2 CCP1IF FERR Bit 1 TMR2IF OERR TMR2IE TRMT Bit 0 Value on: POR, BOR Value on all other Resets 0000 0000 0000 -00x 0000 0000 0000 0000 0000 -010 0000 0000

TMR1IF 0000 0000 RX9D 0000 -00x 0000 0000

TXREG USART Transmit Register SSPIE CCP1IE BRGH TX9D

TMR1IE 0000 0000 0000 -010 0000 0000

SPBRG Baud Rate Generator Register

Legend: x = unknown, - = unimplemented locations read as '0'. Shaded cells are not used for asynchronous transmission. Note 1: Bits PSPIE and PSPIF are reserved on the PIC16F873/876; always maintain these bits clear.

Ejemplo Listado 7.1: EX/EX TX ASINC/TX ASINC.C


#include <pic.h> void main() { unsigned char i=0; TRISC6 = 0; TRISC7 = 1; TXSTA = 0x24;
10

SPBRG RCSTA

= 20; = 0x90;

// // // // // // //

RC6/TX salida RC7/RX entrada 8 bits, asincrono, alta velocidad, transmision activada El micro a 20 MHz, 57600 baudios Activo USART, 8 bits, recepcion continua, no direccion

15

20

while(1) { while(TRMT==0); // Espera a terminar de enviar un dato TXREG = i++; // Envia un dato } }

Cap tulo 7. M odulo USART

91

7.5. Modo as ncrono: recepcion


Funcionamiento Los bits recibidos en RC7/RX/DT se muestrean (a un ritmo de SPBRG x 16) y son introducidos en el registro de desplazamiento RSR al ritmo indicado por SPBRG. Despu es de recibir el bit de stop el dato es copiado en RCREG si est a vac o y se an activadas (PIE1.RCIE = 1, INTCON.PEIE = 1 y indica (PIR1.RCIF = 1). Si est INTCON.GIE = 1) se producir a una interrupcion.
PIR1.RCIF se pondr a a cero cuando se lea el dato de RCREG. RCREG es un registro doble que funciona como un pila FIFO (First In, First Out:

primero en entrar, primero en salir). Si se recibe un tercer dato sin haber le do los anteriores se producir a un error de desbordamiento (RCSTA.OERR = 1) y se inhibir an futuras recepciones hasta que se borre. Si el dato es de 9 bits, se debe leer primero RCSTA.RX9D y despu es RCREG para no perder informacion. Si el dato se recibe incompleto (bit de stop incompleto) se indica con RCSTA.FERR.
x64 Baud Rate CLK CREN SPBRG Baud Rate Generator RC7/RX/DT Pin Buffer and Control Data Recovery RX9 64 or 16 MSb Stop (8) 7 RSR register 1 LSb 0 Start OERR FERR

SPEN

RX9D

RCREG Register

FIFO

8 Interrupt RCIF RCIE Data Bus

Secuencia Se debe congurar el generador de baudios (SPBRG y TXSTA.BRGH). Se debe habilitar el perif erico (RCSTA.SPEN = 1 y TXSTA.SYNC = 0). Si queremos interrupciones, PIE1.RCIE = 1, INTCON.GIE = 1 y INTCON.PEIE = 1. de 9 bits, RCSTA.RX9 = 1 (el noveno bit se recibir Si queremos una recepcion a en RCSTA.RX9D).

92 continua (RCSTA.CREN = 1). Se debe activar la recepcion

Modo as ncrono: recepci on

si est PIR1.RCIF = 1 cuando se reciba un dato y se producir a una interrupcion an activadas. Para comenzar En RCSTA.FERR y RCSTA.OERR se comprueba la correcta recepcion. de nuevo eliminando los errores, poner RCSTA.CREN = 0 y de nuevo a uno. En RCSTA.RX9D estar a el noveno bit (si as lo conguramos). Se lee de RCREG el dato. Cronograma de recepcion as ncrona
RX (pin) Rcv shift reg Rcv buffer reg Read Rcv buffer reg RCREG RCIF (interrupt flag) OERR bit CREN Note: This timing diagram shows three words appearing on the RX input. The RCREG (receive buffer) is read after the third word, causing the OERR (overrun) bit to be set. Start bit bit0 bit1 bit7/8 Stop bit Start bit bit0 bit7/8 Stop bit Start bit bit7/8 Stop bit

WORD 1 RCREG

WORD 2 RCREG

Registros asociados a la recepcion


Value on: POR, BOR 0000 0000 0000 -00x 0000 0000 TXIE SYNC SSPIE CCP1IE BRGH TMR2IE TRMT TMR1IE TX9D 0000 0000 0000 -010 0000 0000 Value on all other Resets 0000 0000 0000 -00x 0000 0000 0000 0000 0000 -010 0000 0000

Address 0Ch 18h 1Ah 8Ch 98h 99h

Name PIR1 RCSTA

Bit 7 PSPIF(1) SPEN PSPIE(1) CSRC

Bit 6 ADIF RX9

Bit 5 RCIF SREN

Bit 4 TXIF CREN

Bit 3 SSPIF

Bit 2 CCP1IF FERR

Bit 1 TMR2IF OERR

Bit 0 TMR1IF RX9D

RCREG USART Receive Register PIE1 TXSTA SPBRG ADIE TX9 RCIE TXEN

Baud Rate Generator Register

Legend: x = unknown, - = unimplemented locations read as '0'. Shaded cells are not used for asynchronous reception. Note 1: Bits PSPIE and PSPIF are reserved on the 28-pin devices; always maintain these bits clear.

Ejemplo Listado 7.2: EX/EX RX ASINC/RX ASINC.c


#include <pic.h> void main() { TRISC7 = 1;

// RC7/RX entrada

Cap tulo 7. M odulo USART


TXSTA SPBRG RCSTA
10

93

= 0x24; = 20; = 0x90;

// 8 bits, asincrono, alta velocidad, // transmision activada // El micro a 20 MHz, 57600 baudios // Activo USART, 8 bits, recepcion // continua, no direccion

15

while(1) { while(RCIF==0); // Espera a recibir un dato TXREG = RCREG; // Reenvia el dato que le llega } }

En el caso de que F=4MHz, y la velocidad hubiera sido de 9600 baudios habr amos usado BRGH=1 y SPBRG=25.

7.6. Modo s ncrono maestro: transmision


half duplex. Es una transmision Se activa con TXSTA.SYNC = 1. Se transmite el reloj maestro (RC6/CK) y los datos en serie (RC7/DT). El modo maestro o esclavo se selecciona con TXSTA.CSRC. La secuencia de operaciones es la misma que en modo as ncrono. Cronograma de transmision en modo s ncrono
RC7/RX/DT pin RC6/TX/CK pin bit0 bit1 bit2 bit6 bit7

Write to TXREG reg

TXIF bit

TRMT bit

TXEN bit

7.7. Modo s ncrono maestro: recepcion


La secuencia de operaciones es la misma que en modo as ncrono.

94 Cronograma de recepcion en modo s ncrono

Modo s ncrono maestro: recepci on

Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4

RC7/RX/DT pin RC6/TX/CK pin Write to bit SREN SREN bit CREN bit RCIF bit (interrupt) Read RXREG 0

bit0

bit1

bit2

bit3

bit4

bit5

bit6

bit7

Note: Timing diagram demonstrates SYNC master mode with bit SREN = '1' and bit BRG = '0'.

Cap tulo 8 Modulo MSSP


Quien no pueda comunicarse consigo mismo tampoco podr a comunicar con sus semejantes Anne Morrow Lindbergh

8.1. Introduccion
El modulo MSSP (Master Synchronous Serial Port) es un interfaz de comunicaciones serie. Puede trabajar en dos modos: Modo SPI (Serial Peripheral Interface). Las patillas asociadas ser an RC3/SCK, RC4/SDI, RC5/SDO y RA5/SS. Modo I2C (Inter-Integrated Circuit). Las patillas asociadas a este modo ser an RC3/SCL y RC4/SDA.

8.2. Modulo MSSP: protocolo SPI


8.2.1. Caracter sticas
de 8 bits full-duplex. Transmision/recepci on Soporta los cuatro modos de funcionamiento del protocolo SPI (ver cronograma m as adelante). En modo maestro se emplean tres pines: Serial Data Out (RC5/SDO). Salida de datos serie. Serial Data In (RC4/SDI). Entrada de datos serie. Serial Clock (RC3/SCK). Reloj serie. Ser a una salida. En modo esclavo se usa adem as Slave Select (RA5/SS) como entrada (activo en (RC3/SCK) ser baja). En este caso la senal a una entrada.

95

96

M odulo MSSP: protocolo SPI

8.2.2. Esquema hardware


El esquema hardware del modulo MSSP cuando est a funcionando en modo SPI es el siguiente:
Internal Data Bus Read SSPBUF reg Write

SSPSR reg SDI bit0 Shift Clock

SDO

SS Control Enable SS Edge Select 2 Clock Select SSPM3:SSPM0 SMP:CKE 4 2 Edge Select SCK

TMR2 output 2 Prescaler 4, 16, 64 TOSC

Data to TX/RX in SSPSR Data direction bit

8.2.3. Conguracion
Se hace a trav es de los registros SSPCON, SSPSTAT y SSPBUF. Hay que elegir entre modo maestro (RC3/SCK de salida) o esclavo (RC3/SCK de entrada). Hay que elegir la polaridad del reloj o lo que es lo mismo el valor del estado ocioso de RC3/SCK. Tambi en tenemos que seleccionar la fase de los datos y el anco del reloj. Por supuesto hay que denir la velocidad del reloj (en modo maestro). en caso de funcionar como esclavo. Y el modo de seleccion Habr a que habilitar el MSSP con SSPCON.SSPEN = 1 Y el sentido de las patillas debe programarse con TRISC.

Cap tulo 8. M odulo MSSP En modo maestro: RC4/SDI de entrada; RC5/SDO y RC3/SCK salidas.

97

En modo esclavo: RC4/SDI, RC3/SCK, y RA5/SS entradas; RC5/SDO salida.

8.2.4. Modo SPI maestro


Caracter sticas y el reloj. El microcontrolador controla la transmision/recepci on Se transmite tan pronto como el registro SSPBUF es escrito. autom La recepcion aticamente rellena el registro SSPBUF. se puede aprovechar la patilla como entrada (se Si no se necesita la recepcion continuar a monitorizando y almacenando en SSPBUF) o como salida. La polaridad se selecciona con SSPCON.CKP. La velocidad de transferencia se puede programar como Fosc /4, Fosc /16, Fosc /64 con la salida TMR2/2. o Cronograma
SCK (CKP = 0, CKE = 0) SCK (CKP = 0, CKE = 1) SCK (CKP = 1, CKE = 0) SCK (CKP = 1, CKE = 1) SDO SDI (SMP = 0) bit7 SDI (SMP = 1) bit7 SSPIF bit0 bit0 bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0

de entrada RC4/SDI se muestrea en el punto medio (SMP=0) o al nal del ciclo La senal (SMP=1). Ejemplo Se muestra un ejemplo escrito en lenguaje C1 .
Se hace notar que en lenguaje C algunos nombres de los campos de los registros pueden variar con respecto al ensamblador. Se puede ver en uno de los ap endices como est an denidos.
1

98

M odulo MSSP: protocolo SPI Listado 8.1: EX/EX TX SPI/TX SPI.c


#include <pic.h> void main() { unsigned char i; TRISC3 = 0; TRISC4 = 1; TRISC5 = 0; // RC3/SCK salida. Modo maestro // RC4/SDI entrada // RC5/SDO salida // // // // // // Activa el modulo MSSP SPI, estado ocioso = 1 Modo SPI maestro, reloj = Fosc/64 Micro a 1 MHz => 15625 bits por segundo => 1953.125 bytes por segundo Dato valido en flanco de subida del reloj

10

SSPEN = 1; CKP = 1; SSPCON = 0x32;


15

STAT_CKE

= 0;

20

25

i = A; while(1) { SSPBUF = i++; while(!SSPIF); SSPIF = 0; } }

// Envio dato // Espero hasta que termine // Lo borro

8.2.5. Modo SPI esclavo


Caracter sticas viene dado externamente a trav El ritmo de transferencia o recepcion es de RC3/SCK. Al recibir el ultimo bit se activa PIR1.SSPIF. Funciona incluso en modo bajo consumo. Cuando se recibe un dato el microcontrolador es despertado. Opcionalmente cuando /SS=0 Cronograma: modo esclavo (CKE=0) Vemos el cronograma en el que se distinguen dos casos dependiendo del valor de
SSPCON.CKP para el caso de SSPSTAT.CKE = 0. (RC3/SCK).

Cap tulo 8. M odulo MSSP


SS (optional)

99

SCK (CKP = 0) SCK (CKP = 1)

SDO SDI (SMP = 0)

bit7

bit6

bit5

bit4

bit3

bit2

bit1

bit0

bit7 SSPIF

bit0

Cronograma: modo esclavo (CKE=1) Ocurre lo mismo para el caso de SSPSTAT.CKE = 1.


SS

SCK (CKP = 0) SCK (CKP = 1)

SDO

bit7

bit6

bit5

bit4

bit3

bit2

bit1

bit0

SDI (SMP = 0) bit7 SSPIF bit0

100

M odulo MSSP: protocolo SPI

8.2.6. Ejemplo transmision/recepci on en SPI


A B C D E F G H J K

SPI MONITOR
DIN DOUT SCK SS TRIG

2
16 15 4

U1
RA7/OSC1/CLKIN RA0/AN0 RA6/OSC2/CLKOUT RA1/AN1 RA2/AN2/CVREF/VREFRA5/MCLR RA3/AN3/C1OUT/VREF+ RA4/AN4/T0CKI/C2OUT RB0/INT/CCP1 RB1/SDI/SDA RB2/SDO/RX/DT RB3/CCP1 RB4/SCK/SCL RB5/SS/TX/CK RB6/AN5/T1OSO/T1CKI RB7/AN6/T1OSI PIC16F88 17 18 1 2 3 6 7 8 9 10 11 12 13

U2
6 5 2 1 SCK SI SO WP CS HOLD 25LC160 3 7

U3
16 15 4 RA7/OSC1/CLKIN RA0/AN0 RA6/OSC2/CLKOUT RA1/AN1 RA2/AN2/CVREF/VREFRA5/MCLR RA3/AN3/C1OUT/VREF+ RA4/AN4/T0CKI/C2OUT RB0/INT/CCP1 RB1/SDI/SDA RB2/SDO/RX/DT RB3/CCP1 RB4/SCK/SCL RB5/SS/TX/CK RB6/AN5/T1OSO/T1CKI RB7/AN6/T1OSI PIC16F88 A B C D E 17 18 1 2 3 6 7 8 9 10 11 12 13

SPI MONITOR 2
DIN DOUT SCK SS TRIG

8
FILE NAME: DESIGN TITLE:

P_spi.dsn

DATE:

Prctica "Comunicacion SPI" 27/04/2008


PAGE:

Hoja principal
BY: Jess M. Hernndez Mangas REV:

1 A
J

of

1
12:07:53

TIME:

Listado 8.2: EX/EX TXRX SPI/P SPI.c


#include <pic.h> #include "binario.h" // Para el PIC16F88 __CONFIG( WDTDIS & INTIO & UNPROTECT & PWRTDIS & CCPRB0 & DEBUGDIS & LVPDIS & BORDIS & MCLRDIS ); // Palabra de configuraci on 0x2007 __CONFIG( FCMDIS & IESODIS ); // Palabra de configuraci on 0x2008 unsigned char SPI_EnviaRecibe(unsigned char c) { SSPBUF = c; // Env a while(!BF); // Espera a que se transmita return SSPBUF; } unsigned char Lee_25LC16(unsigned int dir) { unsigned char c;
20

10

15

25

do { RB0 = 0; SPI_EnviaRecibe(B00000101); c = SPI_EnviaRecibe(0); RB0 = 1; } while(c&0x01); RB0 = 0; SPI_EnviaRecibe(B00000011);

// // // // //

Selecciono la memoria Comando READ STATUS Lee el dato Deselecciono la memoria Mientras valga 1 el bit WIP (WriteInProgress)

30

// Selecciono la memoria // Comando READ

Cap tulo 8. M odulo MSSP


SPI_EnviaRecibe(dir>>8 ); SPI_EnviaRecibe(dir&0xFF); c = SPI_EnviaRecibe(0); RB0 = 1; return c; } // // // // Parte alta de la direcci on Parte baja Lee el dato Deselecciono la memoria

101

35

40

void Escribe_25LC16(unsigned int dir, unsigned char d) { RB0 = 0; // Selecciono la memoria SPI_EnviaRecibe(B00000110); // Comando WRITE ENABLE RB0 = 1; // Para que lo ejecute RB0 = 0; SPI_EnviaRecibe(B00000010); SPI_EnviaRecibe(dir>>8 ); SPI_EnviaRecibe(dir&0xFF); SPI_EnviaRecibe(d); //SPI_EnviaRecibe(B00001000); RB0 = 1; } // Selecciono la memoria // Comando WRITE // Parte alta de la direcci on // Parte baja // Escribe el dato // Comando WRITE DISABLE // Deselecciono la memoria

45

50

55

void Escribe_uC_Slave(unsigned char c) { RB3 = 0; // Selecciona uC_Slave SPI_EnviaRecibe( c ); // Env a dato, descarta lo recibido RB3 = 1; // Deselecciona uC_Slave } void main() { unsigned char t; ANSEL = 0; TRISB0 = 0; TRISB1 = 1; TRISB2 = 0; TRISB4 = 0; TRISB3 = 0; TRISA = 0; RB4 = 0; RB0 = 1; RB3 = 1; SSPCON = B00100010; // // // // // // // // // // // // // // // // // // // // // // // // // // Configuro el PORTA como digital RB0 control memoria salida RB1/SDI input RB2/SDO output RB4/SCK output RB3 control uC slave salida Todo el puerto A es de salida CKP = 0 Deselecciona la memoria Deselecciona el uC slave Control del modulo SSP WCOL 0 No collision SSPOV 0 No overflow SSPEN 1 Enables SSP CKP 0 Transmit on rising edge of SCK SSPM<3:0> 0010 SPI Master, clk = OSC/64 => (4 MHz)/64 = Estado del m odulo SSP SMP 0 Input data sampled at middle CKE 0 Data on falling edge of SCK (CKP=0) D/A 0 -i2c onlyP 0 -i2c onlyS 0 -i2c onlyR/W 0 -i2c onlyUA 0 -i2c onlyBF 0 Ocupado -read only-

60

65

70

75

80

SSPSTAT = B00000000;

85

90

Escribe_25LC16( 0, 0x33 );

102
t = Lee_25LC16( 0 ); PORTA = t;
95

M odulo MSSP: protocolo SPI

Escribe_uC_Slave( 0x44 ); while(1); }

Listado 8.3: EX/EX TXRX SPI/P SPI Slave.c


1

#include <pic.h> #include "binario.h" // Para el PIC16F88 __CONFIG( WDTDIS & INTIO & UNPROTECT & PWRTDIS & CCPRB0 & DEBUGDIS & LVPDIS & BORDIS & MCLRDIS ); // Palabra de configuraci on 0x2007 __CONFIG( FCMDIS & IESODIS ); // Palabra de configuraci on 0x2008 void main() { ANSEL = 0; // 76543210 TRISB = B00111011; //TRISB1 = 1; //TRISB2 = 0; //TRISB4 = 1; //TRISB5 = 1; RBPU = 1; TRISA = 0; SSPBUF = 0x22; SSPCON = B00100101;

11

// Configuro el PORTA como digital // // // // // // // // // // // // // // // // // // // // // // RB1/SDI input RB2/SDO output RB4/SCK input RB5//SS input (slave mode) Pull-ups desactivados Puerto A son salidas Control del modulo SSP WCOL 0 No collision SSPOV 0 No overflow SSPEN 1 Disables SSP CKP 0 Transmit on rising edge of SCK SSPM<3:0> 0101 SPI Slave, SCK active Estado del m odulo SSP SMP 0 Input data sampled at middle CKE 0 Data on falling edge of SCK (CKP=0) D/A 0 -i2c onlyP 0 -i2c onlyS 0 -i2c onlyR/W 0 -i2c onlyUA 0 -i2c onlyBF 0 Ocupado -read only-

16

21

26

SSPSTAT = B00000000;
31

36

41

46

while(1) { if(BF) { PORTA = SSPBUF; } } }

// Dato recibido // Lo saco fuera

8.2.7. Registros
y recepcion. SSPBUF. En el banco 0. Registro de transmision

Cap tulo 8. M odulo MSSP SSPCON. En el banco 0. Registro de control de la comunicacion. SSPCON
Bit 7 6 5 4 3 2 1

103

Bit 0

WCOL

SSPOV

SSPEN

CKP

SSPM3

SSPM2

SSPM1

SSPM0

de colision en la escritura en modo I2C. WCOL Deteccion * Modo maestro 0: No hay colision. 1: Se ha intentado una escritura en SSPBUF y las condiciones I2C no eran v alidas. * Modo esclavo 0: No hay colision. 1: SSPBUF se ha escrito y el dato anterior no se hab a transmitido. SSPOV Indicador de desbordamiento en la recepcion. * Modo SPI 0: No hubo sobreesccritura (overow). un nuevo dato que sobreescribio un dato anterior. Se debe borrar por 1: Se recibio software. * Modo I2C 0: No hubo overow. un nuevo dato que sobreescribio un dato anterior. Se debe borrar por 1: Se recibio software. SSPEN Activa el modulo MSSP. 0: Modulo desactivado. 1: Modulo activado. de la polaridad del reloj. CKP Seleccion * Modo SPI 0: El estado ocioso del reloj es un uno logico. 1: El estado ocioso del reloj es un cero logico. * Modo I2C esclavo. No usado en I2C maestro. de reloj externa a cero. Obliga al maestro a esperar. 0: Mantiene la senal 1: Deja libre el reloj externo. SSPM3:SSPM0 Selecciona el modo de funcionamiento del modulo MSSP. 0000: 0001: 0010: 0011: 0100: 0101: 0110: 0111: 1000: 1001,1010: 1011: 1100, 1101: 1110: 1111: Modo SPI maestro, reloj = Fosc /4. Modo SPI maestro, reloj = Fosc /16. Modo SPI maestro, reloj = Fosc /64. Modo SPI maestro, reloj = (salida del temporizador TRM2)/2. con patilla RA5/SS activado. Modo SPI esclavo, reloj = RC3/SCK. Control de seleccion con patilla RA5/SS desactiModo SPI esclavo, reloj = RC3/SCK. Control de seleccion vado. La patilla se puede usar como de proposito general. de 7 bits. Modo I2C esclavo, direccion de 10 bits. Modo I2C esclavo, direccion Modo I2C maestro, reloj = Fosc /(4(SSPADD+1)). Reservados. Modo I2C maestro, controlado por el rmware. Reservados. de Modo I2C maestro, controlado por el rmware. Direcciones de 7 bit con habilitacion interrupciones en los bit de start y stop. de Modo I2C maestro, controlado por el rmware.Direcciones de 10 bit con habilitacion interrupciones en los bit de start y stop.

104

M odulo MSSP: protocolo SPI SSPSTAT. En el banco 1. Registro de estado del modulo MSSP. SSPSTAT
Bit 7 6 5 4 3 2 1 Bit 0

SMP

CKE

D/A

R/W

UA

BF

SMP Control del modo de muestreo de los bits recibidos. * Modo SPI maestro. En modo SPI esclavo debe permanecer a cero. 0: Dato muestreado en el punto medio. 1: Dato muestreado al nal. * Modo I2C. del control del ritmo de subida (slew rate) para el modo de 400 kHz. 0: Habilitacion del control de ritmo de subida para los modos de 100 kHz y 1: Deshabilitacion 1MHz. del anco de reloj. CKE Seleccion * Modo SPI maestro. En modo SPI esclavo debe permanecer a cero. CKP=0 . se produce al cambiar el reloj del estado ocioso al estado activo. 0: La transmision se produce al cambiar el reloj del estado activo al estado ocioso. 1: La transmision CKP=1 . en el anco de subida de RC3/SCK. 0: Transmision en el anco de bajada de RC3/SCK. 1: Transmision * Modo I2C. 0: Niveles de entrada compatibles con el protocolo SMBUS2 . 1: Niveles de entrada compatibles con el protocolo I2C. o dato recibido. D/A Solo para modo I2C. Indica direccion 0: El ultimo byte recibido fue una direccion. 1: El ultimo byte recibido fue un dato. P Bit de Stop. Solo modo I2C. la condicion de stop. 0: No se detecto de stop. 1: Se ha detectado la condicion S Bit de Start. Solo modo I2C. la condicion de start. 0: No se detecto de start. 1: Se ha detectado la condicion R/W Escritura o lectura. Solo modo I2C. * Modo esclavo. 0: Escritura. 1: Lectura. * Modo maestro. 0: No se transmite nada. en progreso. 1: Transmision Solo modo I2C de 10 bits. UA Actualiza direccion. no necesita ser actualizada. 0: La direccion en el registro SSPADD. 1: El usuario debe actualizar la direccion BF Bufer lleno. 1995. Trabaja con voltaje jo. Tiene una Protocolo muy similar al I2C, pero de Intel y otros del ano de los frecuencia de funcionamiento m nima de 10 kHz. Dispone de un tiempo m aximo para la seleccion http://www.smbus.org/specs/ esclavos. Incluye otras caracter sticas menores. M as informacion:
2

Cap tulo 8. M odulo MSSP

105

(modos SPI e I2C). * Recepcion no completa. SSPBUF vac 0: Recepcion o. completa. SSPBUF lleno. 1: Recepcion (solo modo I2C). * Transmision completa (no incluye /ACK ni la condicion de stop). SSPBUF vac 0: Transmision o. en curso. SSPBUF lleno. 1: Transmision

Registros TABLE asociados 9-1 REGISTERS ASSOCIATED WITH SPI OPERATION


Address
0Bh, 8Bh, 10Bh,18Bh 0Ch 8Ch 13h 14h 94h

Name
INTCON PIR1 PIE1 SSPBUF SSPCON SSPSTAT

Bit 7
GIE PSPIF(1) PSPIE(1)

Bit 6
PEIE ADIF ADIE

Bit 5
T0IE RCIF RCIE

Bit 4
INTE TXIF TXIE

Bit 3
RBIE SSPIF SSPIE

Bit 2
T0IF CCP1IF CCP1IE

Bit 1
INTF TMR2IF TMR2IE

Bit 0
RBIF TMR1IF TMR1IE

POR, BOR
0000 000x 0000 0000 0000 0000 xxxx xxxx

MCLR, WDT
0000 000u 0000 0000 0000 0000 uuuu uuuu 0000 0000 0000 0000

Synchronous Serial Port Receive Buffer/Transmit Register WCOL SMP SSPOV CKE SSPEN D/A CKP P SSPM3 S SSPM2 R/W SSPM1 UA SSPM0 BF

0000 0000 0000 0000

Legend: x = unknown, u = unchanged, - = unimplemented read as '0'. Shaded cells are not used by the SSP in SPI mode.

Note 1: These bits are reserved on the 28-pin devices; always maintain these bits clear.

8.3. Modulo MSSP: protocolo I2C


8.3.1. Caracter sticas
esclavo. Funciona en modo maestro o Permite el direccionamiento de 7 bits o de 10 bits. Atiende a la llamada general (dir = 00000000b). Funciona a 100 kHz, a 400 kHz y a 1 MHz. La patilla RC3/SCL es el reloj (bidireccional). La patilla RC4/SDA son los datos (bidireccional). Se activa el modulo con SSPCON.SSPEN = 1.
TRISC debe congurar RC3/SCL y RC4/SDA como entradas.

Se controla con 5 registros: SSPCON, registro de control del modulo MSSP. SSPCON2, registro de control numero 2 del modulo MSSP. SSPSTAT, registro de estado del modulo MSSP. SSPBUF, bufer de recepcion/env o. SSPADD, registro de direccion.

106 Modos de operacion: de 7 bits). I2C esclavo (direccion de 10 bits). I2C esclavo (direccion I2C maestro, Fi2c = Fosc /(4(SSPADD+1)).

M odulo MSSP: protocolo I2C

8.3.2. Funcionamiento
SSPSTAT.CKE = 0, congurar a niveles compatibles I2C. SSPSTAT.CKE = 1, congurar a niveles el ectricos compatibles SMBus (Intel 1995).

de start. SSPSTAT.S indicar a la condicion de stop. SSPSTAT.P indicar a la condicion dato o direccion. SSPSTAT.D_A indicar a si se recibio a 10 bits de la direccion. SSPSTAT.UA indicar a si el dato es la extension

8.3.3. Modo I2C esclavo


Funcionamiento start. Se detectar a la condicion contenida en SSPADD. Se leer a el primer dato y se comparar a con la direccion ACK excepto si Si hay coincidencia se generar a la senal SSPSTAT.BF = 1 que indicar a ocupado. SSPCON.SSPOV = 1 que indicar a SSPBUF desbordado. El dato se recibe bit a bit en el registro SSPSR y una vez completo se transere a SSPBUF y se indica con PIR1.SSPIF.

Cap tulo 8. M odulo MSSP Esquema hardware


Internal Data Bus Read SSPBUF reg Shift Clock SSPSR reg SDA MSb LSb Write

107

SCL

Match detect

Addr Match

SSPADD reg Start and Stop bit detect Set, Reset S, P bits (SSPSTAT reg)

Bits de estado
Status Bits as Data Transfer is Received BF
0 1 1 0

SSPOV
0 0 1 1

SSPSR SSPBUF
Yes No No Yes

Generate ACK Pulse


Yes No No No

Set bit SSPIF (SSP Interrupt occurs if enabled)


Yes Yes Yes Yes

Note 1: Shaded cells show the conditions where the user software did not properly clear the overflow condition.

Cronograma de recepcion (direccion de 7 bits)


Receiving Address SDA A7 A6 A5 A4 A3 A2 A1 1 2 3 4 5 6 7 8 9 R/W=0 ACK Not Receiving Data Receiving Data ACK ACK D7 D6 D5 D4 D3 D2 D1 D0 D7 D6 D5 D4 D3 D2 D1 D0 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 P

SCL SSPIF

Bus Master terminates transfer Cleared in software SSPBUF register is read

BF (SSPSTAT<0>)

SSPOV (SSPCON<6>) Bit SSPOV is set because the SSPBUF register is still full. ACK is not sent.

108 Cronograma de transmision (direccion de 7 bits)


FIGURE 9-7:
SDA

M odulo MSSP: protocolo I2C

I C WAVEFORMS FOR TRANSMISSION (7-BIT ADDRESS)


Receiving Address A7 A6 A5 A4 A3 A2 A1 R/W = 1 ACK D7 D6 D5 D4 Transmitting Data D3 D2 D1 D0 R/W = 0 Not ACK

SCL

1 2 Data in sampled

1 SCL held low while CPU responds to SSPIF

SSPIF BF (SSPSTAT<0>) cleared in software SSPBUF is written in software CKP (SSPCON<4>) Set bit after writing to SSPBUF (the SSPBUF must be written-to before the CKP bit can be set) From SSP interrupt service routine

8.3.4. Modo I2C maestro


Funcionamiento en una escritura. SSPCON.WCOL indica que ha habido una colision Secuencia de transmision: de start con SSPCON2.SEN = 1. Se genera la condicion del modulo. PIR1.SSPIF estar a a 1. Se espera la inicializacion del dispositivo en SSPBUF. Se escribe la direccion es transmitida. La direccion El modulo MSSP lee el bit ACK y lo copia en SSPCON2.ACKSTAT. si est Se activa PIR1.SSPIF y se produce una interrupcion, a habilitada. Se escribe el dato en SSPBUF. El dato es transmitido. El modulo MSSP lee el bit ACK y lo copia en SSPCON2.ACKSTAT. de stop con SSPCON2.PEN. Se genera la condicion si est Se genera una interrupcion an habilitadas.

Cap tulo 8. M odulo MSSP Cronograma de transmision (direccion de 7 bits)

109

Write SSPCON2<0> SEN = 1 START condition begins SEN = 0 Transmit Address to Slave SDA A7 A6 A5 A4 A3 A2 A1 R/W = 0 ACK = 0

From slave clear ACKSTAT bit SSPCON2<6> Transmitting Data or Second Half of 10-bit address D7 D6 D5 D4 D3 D2 D1 D0 ACK

ACKSTAT in SSPCON2 = 1

SSPBUF written with 7-bit address and R/W start transmit SCL S 1 2 3 4 5 6 7 8 9 1 SCL held low while CPU responds to SSPIF 2 3 4 5 6 7 8 9 P

SSPIF Cleared in software Cleared in software service routine From SSP interrupt

Cleared in software

BF (SSPSTAT<0>) SSPBUF written SEN After start condition SEN cleared by hardware. SSPBUF is written in software

PEN

R/W

Cronograma de recepcion (direccion de 7 bits)

Write to SSPCON2<4> to start acknowledge sequence SDA = ACKDT (SSPCON2<5>) = 0 Write to SSPCON2<0> (SEN = 1) Begin Start Condition SEN = 0 Write to SSPBUF occurs here Start XMIT Transmit Address to Slave SDA A7 A6 A5 A4 A3 A2 A1 Master configured as a receiver by programming SSPCON2<3>, (RCEN = 1) ACK from Slave R/W = 1 ACK D7 RCEN cleared automatically Receiving Data from Slave D6 D5 D4 D3 D2 D1 D0 ACK D7 ACK from Master SDA = ACKDT = 0 RCEN = 1 start next receive Receiving Data from Slave D6 D5 D4 D3 D2 D1 D0 ACK Bus Master terminates transfer P Set SSPIF interrupt at end of acknowledge sequence Set ACKEN start acknowledge sequence SDA = ACKDT = 1 RCEN cleared automatically PEN bit = 1 written here

ACK is not sent 1 2 3 4 5 6 7 8 9 3 5 6 7 8 9 1 2 3 4 5 6 7 8 9 Set SSPIF at end of receive

SCL

Data shifted in on falling edge of CLK Set SSPIF interrupt at end of receive SSPIF SDA = 0, SCL = 1 while CPU responds to SSPIF BF (SSPSTAT<0>) Cleared in software Cleared in software Cleared in software Set SSPIF interrupt at end of acknowledge sequence Cleared in software

Cleared in software

Set P bit (SSPSTAT<4>) and SSPIF

Last bit is shifted into SSPSR and contents are unloaded into SSPBUF

SSPOV SSPOV is set because SSPBUF is still full

ACKEN

Otros Registros en el modo I2C esclavo. SSPADD. En el banco 1. Registro de direccion

110

M odulo MSSP: protocolo I2C SSPCON2. En el banco 1. Registro de control numero 2 de la comunicacion. SSPCON2
Bit 7 6 5 4 3 2 1 Bit 0

GCEN

ACKSTAT ACKDT

ACKEN

RCEN

PEN

RSEN

SEN

de llamada general. GCEN Activa la deteccion 0: Desactiva la llamada general. cuando una direccion de llamada general es recibida (dir=00000000b). 1: Activa la interrupcion ACK). Modo I2C maestro. ACKSTAT Estado del reconocimiento del dato (senal 0: El ACK se recibio. del esclavo. 1: El ACK no se recibio ACK a transmitir. Solo modo maestro. ACKDT Senal 0: ACK activo. 1: ACK no activo. ACKEN Activa la secuencia para dar el reconocimiento (al recibir). Solo en modo I2C maestro. 0: Desactivado. 1: Activa la secuencia. Se borra al terminar. Solo en modo I2C maestro. RCEN Habilita la recepcion. 0: Desactivada. de un dato de 8 bits. 1: Activada la recepcion PEN Genera secuencia de stop. Solo en modo I2C maestro. 0: No hace nada. 1: Genera la secuencia. RSEN Genera secuencia de start repetida. Solo en modo I2C maestro. 0: No hace nada. 1: Genera la secuencia. SEN Genera secuencia de start. Solo en modo I2C maestro. 0: No hace nada. 1: Genera la secuencia.

Registros asociados
Address
0Bh, 8Bh, 10Bh,18Bh 0Ch 8Ch 0Dh 8Dh 13h 14h 91h 94h

Name
INTCON PIR1 PIE1 PIR2 PIE2 SSPBUF SSPCON SSPCON2 SSPSTAT

Bit 7
GIE PSPIF
(1)

Bit 6
PEIE ADIF ADIE (2) (2)

Bit 5
T0IE RCIF RCIE

Bit 4
INTE TXIF TXIE EEIF EEIE

Bit 3
RBIE SSPIF SSPIE BCLIF BCLIE

Bit 2
T0IF CCP1IF CCP1IE

Bit 1
INTF TMR2IF TMR2IE

Bit 0
RBIF TMR1IF TMR1IE CCP2IF CCP2IE

POR, BOR
0000 000x 0000 0000 0000 0000 -r-0 0--0 -r-0 0--0 xxxx xxxx

MCLR, WDT
0000 000u 0000 0000 0000 0000 -r-0 0--0 -r-0 0--0 uuuu uuuu 0000 0000 0000 0000 0000 0000

PSPIE(1)

Synchronous Serial Port Receive Buffer/Transmit Register WCOL GCEN SMP SSPOV ACKSTAT CKE SSPEN ACKDT D/A CKP ACKEN P SSPM3 RCEN S SSPM2 PEN R/W SSPM1 RSEN UA SSPM0 SEN BF

0000 0000 0000 0000 0000 0000

Legend:

= unknown,

= unchanged,

= unimplemented read as '0'. Shaded cells are not used by the SSP in I2C mode.

Cap tulo 8. M odulo MSSP Ejemplo Listado 8.4: EX/EX TX I2C/TX I2C.c
#include <pic.h> unsigned char EnviaI2C(const int Dir, const int Dato) { SEN = 1; // START while(!SSPIF); SSPIF = 0; SSPBUF = Dir & 0xFE; while(!SSPIF); SSPIF = 0;
10

111

// DIRECCION, R/W=0 // No recibi o el /ACK // DATO // No recibi o el ACK // STOP

if(ACKSTAT) return 1; SSPBUF = Dato; while(!SSPIF); SSPIF = 0;


15

if(!ACKSTAT) return 1; PEN = 1; while(!SSPIF); SSPIF = 0; return 0; } void main() { // Inicia el modulo TRISC3 = 1; TRISC4 = 1; SSPCON = 0x2B; SSPSTAT = 0x40; while(1) { EnviaI2C(0x30, 0x30); } }

20

25

30

// // // // //

RC3/SCK entrada RC4/SDA entrada Modo I2C maestro, reloj por firmware, habilito MSSP A 400kHz

// Envia un dato a una direccion

35

112

M odulo MSSP: protocolo I2C

Cap tulo 9 Otras caracter sticas


Nunca pidas que las cosas se hagan como quieres; mas procura quererlas como ellas se hacen. Por este medio todo te suceder a como lo deseas. Epicteto

9.1. Introduccion
Existen otras caracter sticas dentro de esta familia de microcontroladores que re y que estudiaremos en este cap sumimos a continuacion tulo: del microcontrolador. Palabra de conguracion del oscilador. Seleccion Reset. Mecanismos de reinicio: del circuito. Power-on reset (POR). Al conectar la alimentacion Power-up timer (PWRT). Durante un tiempo al principio. Oscillator start-up timer (OST). Hasta que el oscilador oscile nominalmente. de alimentacion cae. Brown-out reset (BOR). Si la tension Interrupciones. Watchdog timer (WDT). Temporizador perro guardi an. SLEEP. Modo de bajo consumo: instruccion del codigo. Proteccion Identicacion. serie en el sistema (ICSP: In Circuit Serial Programming). Programacion serie en el sistema de bajo voltaje (LVP: Low Voltage Programming) Programacion en el sistema (ICD: In Circuit Debugging). Depuracion

113

114

Conguraci on del microcontrolador

9.2. Conguracion del microcontrolador


del microAlgunas de estas prestaciones se congurar an en tiempo de grabacion tomando el signicado que aparece controlador a trav es de la palabra de conguracion a continuacion:
CP1 bit13 bit 13-12: bit 5-4: CP1:CP0: Flash Program Memory Code Protection bits (2) 11 = Code protection off 10 = 1F00h to 1FFFh code protected (PIC16F877, 876) 10 = 0F00h to 0FFFh code protected (PIC16F874, 873) 01 = 1000h to 1FFFh code protected (PIC16F877, 876) 01 = 0800h to 0FFFh code protected (PIC16F874, 873) 00 = 0000h to 1FFFh code protected (PIC16F877, 876) 00 = 0000h to 0FFFh code protected (PIC16F874, 873) DEBUG: In-Circuit Debugger Mode 1 = In-Circuit Debugger disabled, RB6 and RB7 are general purpose I/O pins. 0 = In-Circuit Debugger enabled, RB6 and RB7 are dedicated to the debugger. Unimplemented: Read as 1 WRT: Flash Program Memory Write Enable 1 = Unprotected program memory may be written to by EECON control 0 = Unprotected program memory may not be written to by EECON control CPD: Data EE Memory Code Protection 1 = Code protection off 0 = Data EEPROM memory code protected LVP: Low Voltage In-Circuit Serial Programming Enable bit 1 = RB3/PGM pin has PGM function, low voltage programming enabled 0 = RB3 is digital I/O, HV on MCLR must be used for programming BODEN: Brown-out Reset Enable bit (1) 1 = BOR enabled 0 = BOR disabled PWRTE: Power-up Timer Enable bit (1) 1 = PWRT disabled 0 = PWRT enabled WDTE: Watchdog Timer Enable bit 1 = WDT enabled 0 = WDT disabled FOSC1:FOSC0: Oscillator Selection bits 11 = RC oscillator 10 = HS oscillator 01 = XT oscillator 00 = LP oscillator CP0 DEBUG

WRT CPD

LVP

BODEN

CP1

CP0

PWRTE WDTE F0SC1

F0SC0 bit0

Register: CONFIG Address 2007h

bit 11:

bit 10: bit 9:

bit 8:

bit 7:

bit 6:

bit 3:

bit 2:

bit 1-0:

Note 1: Enabling Brown-out Reset automatically enables Power-up Timer (PWRT), regardless of the value of bit PWRTE. Ensure the Power-up Timer is enabled anytime Brown-out Reset is enabled. 2: All of the CP1:CP0 pairs have to be given the same value to enable the code protection scheme listed.

se encuentra en el espacio de memoria de conguEsta palabra de conguracion y ocupa la posicion 2007h. racion Para denirla desde el propio codigo fuente en ensamblador haremos:
LIST P=16F877, R=DEC INCLUDE "P16F877.INC" ; Despues de esta inclusion ...

__CONFIG _CP_OFF & _DEBUG_OFF & _WRT_ENABLE_OFF & _CPD_OFF & _LVP_OFF & _BODEN_OFF & _PWRTE_ON & _WDT_OFF & _XT_OSC

Para denirla desde el propio codigo fuente en lenguaje C haremos:


#include <pic.h> // Para el PIC16F877 __CONFIG( UNPROTECT & DEBUGDIS & WRTDIS & DUNPROT & LVPDIS

Cap tulo 9. Otras caracter sticas


& BORDIS & PWRTDIS & WDTDIS & XT);

115

9.3. Conguracion del oscilador


Dispone de varios modos de funcionamiento. Podemos distinguir dos fundamentalmente: de reloj externa o si conectamos Modos LP, XT, HS. Si le conectamos una senal entre las patillas OSC1 y OSC2 un cristal de cuarzo o un resonador cer amico. El modo LP (Low Power) es de bajo consumo, pensado para frecuencias de hasta 200 kHz. El modo XT (cristal o resonador) est a pensado para consumos medios con frecuencias de hasta 4 MHz. El modo HS (High Speed) es para frecuencias de hasta 20 MHz y presenta el consumo m as alto. de frecuencia Si el oscilador es externo, por la patilla OSC2 sale una senal Fosc /4. en los modos LP, XT y HS es el siguiente: El esquema de conexion
C1(1) OSC1 To internal logic SLEEP PIC16F87X

XTAL OSC2 RS(2) C2(1)

RF(3)

Note 1: See Table 12-1 and Table 12-2 for recommended values of C1 and C2. 2: A series resistor (RS) may be required for AT strip cut crystals. 3: RF varies with the crystal chosen.

Si conectamos un reloj externo:

Clock from ext. system


Open

OSC1 PIC16F87X OSC2

de reloj conectando un red resistencia/capaciModo RC. Conseguimos la senal dad (RC) que se cargar a y descargar a. El consumo es pequeno. de alimentacion y tolerancias La frecuencia depender a de la temperatura, tension de los componentes Rext y Cext . Un esquema se puede ver a continuacion:

116
VDD Rext OSC1 Cext VSS FOSC/4 Recommended values: OSC2/CLKOUT 3 k Rext 100 k Cext > 20pF Internal Clock PIC16F87X

Reset

9.4. Reset
de reset que recibe el nucleo La senal del microcontrolador procede de diversas fuentes como se puede apreciar en el esquema siguiente:
External Reset MCLR WDT Module VDD rise detect VDD Brown-out Reset OST/PWRT OST 10-bit Ripple counter OSC1 (1) On-chip RC OSC PWRT 10-bit Ripple counter R Q Chip_Reset Power-on Reset S WDT SLEEP

Time-out Reset

BODEN

Enable PWRT Enable OST

Note 1: This is a separate oscillator from the RC oscillator of the CLKIN pin.

Las diferentes fuentes de reset se enumeran a continuacion: Power-On Reset (POR). Reset generado mientras que Vdd est e entre 1,2 y 1,7 V. Evita el uso de redes RC en /MCLR (una resistencia de 10 k es suciente). PoWeR-up Timer (PWRT). Proporciona 72 milisegundos anadidos de reset despu es depende de la temperatura, la tension de alimentacion del POR. Esta temporizacion y puede variar con el chip. Se activa en la palabra de conguracion.

Cap tulo 9. Otras caracter sticas

117

de Oscillator Start-up Timer (OST). Proporciona 1024 ciclos de reloj extra de senal reset despu es de PWRT para asegurar que el oscilador funcione correctamente. Se activa autom aticamente si se selecciona XT, LP o HS como modos de oscilacion. BODEN. Si Vdd cae Brown-Out Reset (BOR). Se activa con el bit de conguracion por debajo de 4 V durante m as de 100 microsegundos se reinicia el sistema, que no comenzar a a ejecutar instrucciones hasta que Vdd >4 V y despu es del PWRT correspondiente. Resumen de los tiempos de reset
TABLE 12-3: TIME-OUT IN VARIOUS SITUATIONS
Power-up PWRTE = 0 XT, HS, LP RC 72 ms + 1024TOSC 72 ms PWRTE = 1 1024TOSC 72 ms + 1024TOSC 72 ms Brown-out Wake-up from SLEEP 1024TOSC Oscillator Configuration

Bits de estado STATUS.TO y STATUS.PD y PCON.POR y PCON.BOR despu es del reset


TABLE 12-4:
POR 0 0 0 1 1 1 1 1 BOR x x x 0 1 1 1 1

STATUS BITS AND THEIR SIGNIFICANCE


TO 1 0 x 1 0 0 u 1 PD 1 x 0 1 1 0 u 0 Power-on Reset Illegal, TO is set on POR Illegal, PD is set on POR Brown-out Reset WDT Reset WDT Wake-up MCLR Reset during normal operation MCLR Reset during SLEEP or interrupt wake-up from SLEEP

Estado inicial despu es del reset


TABLE 12-5: RESET CONDITION FOR SPECIAL REGISTERS
Condition Power-on Reset MCLR Reset during normal operation MCLR Reset during SLEEP WDT Reset WDT Wake-up Brown-out Reset Interrupt wake-up from SLEEP Program Counter 000h 000h 000h 000h PC + 1 000h PC + 1(1) STATUS Register 0001 1xxx 000u uuuu 0001 0uuu 0000 1uuu uuu0 0uuu 0001 1uuu uuu1 0uuu PCON Register ---- --0x ---- --uu ---- --uu ---- --uu ---- --uu ---- --u0 ---- --uu

Legend: u = unchanged, x = unknown, - = unimplemented bit read as '0'. Note 1: When the wake-up is due to an interrupt and the GIE bit is set, the PC is loaded with the interrupt vector (0004h).

118 Cronograma t pico de arranque


VDD

Interrupciones

MCLR INTERNAL POR TPWRT

PWRT TIME-OUT

TOST

OST TIME-OUT

INTERNAL RESET

9.5. Interrupciones
aunque Esta familia de microcontroladores dispone de 14 fuentes de interrupcion, el esquema algunos modelos no disponen de todas ellas. Se muestra a continuacion de interrupciones en el que se pueden apreciar los bits de hahardware de generacion (terminados con la letra E) y los bits de noticacion (terminados con la letra bilitacion el modelo de F). Tambi en se muestra una tabla con las interrupciones presentes segun microcontrolador.
EEIF EEIE PSPIF PSPIE ADIF ADIE RCIF RCIE TXIF TXIE SSPIF SSPIE CCP1IF CCP1IE TMR2IF TMR2IE TMR1IF TMR1IE CCP2IF CCP2IE BCLIF BCLIE T0IF T0IE INTF INTE RBIF RBIE PEIE GIE Wake-up (If in SLEEP mode)

Interrupt to CPU

The following table shows which devices have which interrupts.


Device PIC16F876/873 PIC16F877/874 T0IF INTF RBIF PSPIF ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF EEIF BCLIF CCP2IF Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes

Cap tulo 9. Otras caracter sticas Descripcion


INTCON.GIE habilita globalmente las interrupciones.

119

la ejecucion del programa salta a la posicion 4 de Al producirse una interrupcion la memoria de programa y se inhiben globalmente las interrupciones hasta que de retorno de interrupcion: RETFIE. es ejecutada la instruccion Independientemente de que est en habilitadas global o localmente las interrup se ponen a 1. Es nececiones, los ags que notican la ocurrencia de la condicion sario que el programador los vuelva a poner a 0 (son bits pegajosos: sticky bits). es necesario borrarlos para evitar que se Despu es de atender una interrupcion vuelva a producir la misma interrupcion. El registro INTCON almacena las habilitaciones y senalizaciones de las interrupciones debidas a RB0/INT, cambio en el puerto RB4..RB7 y desbordamiento del temporizador TMR0. Los dem as ags se encuentran en los registros PIR1 y PIR2. Los bits de habil est itacion an en los registros PIE1 y PIE2. Para habilitar estos hay que activar el bit INTCON.PEIE. de 3 o 4 Para las interrupciones externas puede haber un retardo en su atencion por un tema de sincronizacion. ciclos de instruccion Es necesario salvaguardar el contexto de ejecucion. Las variables W_TEMP, STATUS_TEMP y PCLATH_TEMP deben estar denidas en los 16 bytes ultimos de los bancos (ya que son comunes a los 4 bancos y facilita el proceso). V ease el ejemplo:
W_TEMP equ 127 STATUS_TEMP equ 126 PCLATH_TEMP equ 125 MOVWF SWAPF CLRF MOVWF MOVF MOVWF CLRF : :(ISR) : MOVF MOVWF SWAPF MOVWF SWAPF SWAPF W_TEMP STATUS,W STATUS STATUS_TEMP PCLATH, W PCLATH_TEMP PCLATH ; ; ; ; ; ; ; ; W_TEMP = W W = swap(STATUS) Pone banco 0 al borrar IRP, RP1 y RP0 STATUS_TEMP = W = swap(STATUS) Solo requerido si usamos las paginas de codigo 1, 2 o 3 PCLATH_TEMP = PCLATH Pone pagina 0 de codigo

; Atencion de la interrupcion PCLATH_TEMP, W PCLATH STATUS_TEMP,W STATUS W_TEMP,F W_TEMP,W ; Recupera PCLATH ; Recupera STATUS ; Recupera W

En lenguaje C se pondr a:

120

Temporizador perro guardi an

void interrupt ISR(void) { // ... }

donde no habr a que preocuparse de salvaguardar el contexto por que lo har a el llame a la subrutina propio C y donde debemos procurar: que ninguna funcion a las interrupciones (ISR: Interrupt Service Routine, el nombre es opde atencion cional), y que desde la ISR no se llame a otras funciones que sean llamadas a su vez desde otros sitios. No existe una pila din amica para guardar los valores de las variables.

9.6. Temporizador perro guardi an


Es un temporizador cuyo oscilador RC se encuentra integrado en el microcontrolador. El perro guardi an provoca un reset del sistema cuando se desborda. Si el micro SLEEP) solamente lo despierta. El se encuentra en modo de bajo consumo (instruccion bit STATUS.NOT_TO = 0 senalizar a el desbordamiento de este temporizador. es la de que el sistema no entre en un estado descontrolado: el proSu funcion CLRWDT) con una gramador deber a, si ha activado el WDT, ponerlo a cero (instruccion cierta frecuencia dentro de su programa. Si debido a un mal funcionamiento hardware de instrucciones no borra el WDT, el sistema se reiniciar o software la ejecucion a. El tiempo nominal de desbordamiento es dependiente de la temperatura, la tension y var de alimentacion a con el chip, pero viene a ser de unos 18 milisegundos, si no se usa la post-escala. Esquema hardware
From TMR0 Clock Source (Figure 5-1) 0 WDT Timer 1 M U X Postscaler 8 8 - to - 1 MUX WDT Enable Bit PSA To TMR0 (Figure 5-1) 0 MUX 1 PSA PS2:PS0

Note: PSA and PS2:PS0 are bits in the OPTION_REG register.

WDT Time-out

Cap tulo 9. Otras caracter sticas Registros asociados


Address 2007h 81h,181h Name Config. bits OPTION_REG Bit 7 (1) RBPU Bit 6 BODEN(1) INTEDG Bit 5 CP1 T0CS Bit 4 CP0 T0SE Bit 3 PWRTE(1) PSA Bit 2 WDTE PS2 Bit 1 FOSC1 PS1

121

Bit 0 FOSC0 PS0

Legend: Shaded cells are not used by the Watchdog Timer. Note 1: See Register 12-1 for operation of these bits.

9.7. Modo de bajo consumo: SLEEP


SLEEP. Se entra en este modo ejecutando la instruccion Entonces STATUS.NOT_PD = 0 y se inicia la cuenta del WDT, que despertar a al micro al desbordarse este, siempre que est e activo (bits de conguracion) En este modo el reloj del sistema deja de oscilar, aunque las salidas se mantendr an en el mismo estado. El sistema se puede despertar de las siguientes maneras: del reset externo /MCLR. Activacion Desbordamiento del WDT. externa (RB0 o cambio en RB4..RB7). Interrupcion Interrupciones de otros perif ericos: Lectura o escritura en el PSP. de TMR1 (contador as Interrupcion ncrono). en modo captura (CCP). Interrupcion Disparo de un evento especial (TMR1 con reloj externo). por deteccion start o stop en el modulo Interrupcion MSSP. en modo esclavo MSSP (SPI/I2C). Transmision/recepci on de la USART en modo esclavo. Transmision/recepci on de la conversion A/D. Finalizacion escritura en la EEPROM de datos. Finalizacion

9.8. Proteccion del codigo


Para proteger la propiedad intelectual de nuestro trabajo se puede proteger contra lecturas el acceso tanto a la memoria de programa como a la memoria de datos EEP ROM de nuestro microcontrolador. Esto se hace a trav es de la palabra de conguracion anterior. vista en una seccion

122

Identicaci on

9.9. Identicacion
(2000h-2003h) para idenDispone de 4 posiciones de la memoria de conguracion Tendremos por tanto 4 d ticar el sistema. Solamente emplea 4 bits por direccion. gi como el checksum del programa tos hexadecimales. Se puede almacenar informacion o se puede almacegrabado (es un codigo para comprobar si el programa se modico) del programa grabado, etc. nar un codigo que haga referencia a la version Para denirlo desde el propio codigo fuente:
LIST P=16F877, R=DEC INCLUDE "P16F877.INC" __IDLOCS(1234h) ; Despues de esta inclusion ...

Para denirla desde el propio codigo fuente en lenguaje C haremos:


#include <pic.h> __IDLOC(0x1234);

9.10. Programacion serie en el sistema (ICSP)


nos permite grabar el programa en el microcontrolador. Se necesita Esta prestacion un hardware especial y un software a medida (lo vemos en pr acticas).

9.11. Programacion en circuito de bajo voltaje (LVP)


LVP = 1 para activarlo. Esto solo se puede hacer de la El bit de conguracion m forma ordinaria con un voltaje de programacion as elevado. de la programacion con bajo La patilla RB3/PGM pasa a ser la patilla de activacion voltaje (Vdd ) quedando condenada a ser una entrada con esa funcion espec ca. del circuito y las patillas Son necesarias adem as Vdd y Vss para la alimentacion RB6 y RB7 para el reloj y los datos serie. Idem.

9.12. Depuracion en circuito


especial que permite depurar el contenido de un prograSe trata de una prestacion ma a trav es de las patillas RB6 y RB7. Es necesario disponer de una interfaz adecuada para conectarlo con el computador y un software adecuado (MPLAB lo emplea). DEBUG = 0. Se activa con el bit de conguracion Algunos recursos del micro se reservan para depuracion:

Cap tulo 9. Otras caracter sticas


TABLE 12-7:
I/O pins Stack Program Memory Data Memory

123
DEBUGGER RESOURCES
RB6, RB7 1 level Address 0000h must be NOP Last 100h words 0x070(0x0F0, 0x170, 0x1F0) 0x1EB - 0x1EF

Se necesita un hardware especial para utilizarlo.

124

Depuraci on en circuito

Cap tulo 10 Otros microcontroladores PIC avanzados


No pienso nunca en el futuro porque llega muy pronto Albert Einstein

10.1. Introduccion
Me gustar a comenzar este cap tulo dici endoles que todo lo aprendido est a ya obsoleto. Cierto. El fabricante de esta familia (16F87x) de microcontroladores ha sacado al mercado el sustituto de la misma: 16F88x. He de decir que a mi tambi en me ha pillado por sorpresa. Cuando he ido a comprar el material para el curso he visto que exist a una familia con casi las mismas caracter sticas -mejores caracter sticas- y a un precio notablemente m as bajo (unos 2 euros frente a 10 o 12). En vista de la posible no disponibilidad comentar e las diferencias m as notables proporcionada por en unas im agenes extra das directamente de la hoja de migracion Microchip y que se adjunta en el CDROM.

125

126
TABLE 1: PIC16F87XA PIC16F88X MIGRATION DIFFERENCES

Introducci on

Functional Differences No. 1 2 3 4 5 6 7 8 9 10 11 12 Difference Ports A, B, and E Weak pull-ups are individually configurable WDT (Time-out period may be extended) Timer1 with gate control 2 independent analog comparators ECCP and CCP Additional A/D channels Enhanced USART with auto-baud Configuration Word BOR voltage is selectable Program Flash memory write Parallel slave port H/W S/W Prog.

Legend: H/W Issues may exist with regard to the application circuit. S/W Issues may exist with regard to the user program. Programming Issues may exist with regard to programming the device.

Cap tulo 10. Otros microcontroladores PIC avanzados

127
PORTE
The ANSEL register is used to configure the Input mode of pins AN<7:0>, respectively. If an analog function is required on AN<7:5> the corresponding bit of the ANSEL register should be set. Once the ANSEL bit is set, the digital input driver will be disabled and the corresponding PORTE bit, if read, will read as 0. By default ANSEL is 0FFh. For a pin on PORTE to operate as a digital input, the corresponding ANSEL bit must be cleared. ANSEL has no effect on the output functionality of PORTE. RE3 is a new input only pin to PORTE. When configured for external MCLR, RE3 acts as an unimplemented pin and always reads as 0.

CODE CONVERSION
The vast majority of the code that was developed for the PIC16F87XA family is portable to its corresponding PIC16F88X counterpart. However, in some cases, some changes may be required depending on which feature set is being used. To migrate source code to the PIC16F88X, the following steps must be performed: 1. 2. Replace the PIC16F87XA include file with the corresponding PIC16F88X include file. Configure the ANSEL and ANSELH registers to assure proper operation of PORTA, PORTB and PORTE. The ANSEL and ANSELH registers default state disables the digital input buffer forcing these port pins to always read as 0. Any source code that made use of the Parallel Slave Port (PSP) peripheral will need to be rewritten. The PSP peripheral does not exist in the PIC16F88X product family. Make the necessary changes to the new or enhanced peripherals that are being used, as listed below. Verify the Configuration bits are set properly.

3.

WEAK PULL-UPS ON PORTB


The weak pull-ups on PORTB now have individual control via the WPUB register. Clearing the RBPU bit of the OPTION register, the weak pull-up feature is enabled. By default all individual weak pull-ups will be enabled. No software changes should be needed for this feature to operate as intended.

4.

5.

PORTA
The ANSEL register is used to configure the Input mode of pins AN<7:0>, respectively. If an analog function is required on AN<4:0> the corresponding bit of the ANSEL register should be set. Once the ANSEL bit is set the digital input driver will be disabled and the corresponding PORTA bit, if read, will read as 0. By default ANSEL is 0FFh. For a pin on PORTA to operate as a digital input, the corresponding ANSEL bit must be cleared. ANSEL has no effect on the output functionality of PORTA. RA0 has the ULPWU (ultra low-power wake-up) multiplexed on the pin. The ULPWU is enabled by setting the ULPWUE bit of the PCON register. By default the ULPWU is off. RA6 and RA7 are new pins for PORTA. In XT, HS or LP Clock modes these port pins will act as unimplemented pins and will read as 0. In RCIO Clocking mode RA6 will function as an IO.

INTERRUPT-ON-CHANGE PORTB
The IOC on PORTB now has individual control via the IOCB register. Setting the RBIE bit of the INTCON register enables the IOC feature. By default, all individual interrupt-on-change are disabled. For software compatibility the following should be written to the IOCB register:

EXAMPLE 1:

COMPATIBILITY FOR INTERRUPT-ON-CHANGE PORTB


b11111111

IOCB

EXTENDED WATCHDOG TIMER (WDT)


The WDTCON register is a new register to allow more flexibility in the watchdog time-out period. The WDTCON register in conjunction with the shared prescaler of Timer0, allows the time-out period to vary from 1ms to 268 seconds. The default setting of the WDTCON register sets the time-out period to be 17 ms with no prescaler. No software changes are required to have the watchdog time-out period to stay the same.

PORTB
The ANSELH register is used to configure the Input mode of pins AN<13:8>, respectively. If an analog function is required on AN<13:7> the corresponding bit of the ANSEL register should be set. Once the ANSELH bit is set, the digital input driver will be disabled and the corresponding PORTB bit, if read, will read as 0. By default ANSELH is 0FFh. For a pin on PORTB to operate as a digital input, the corresponding ANSELH bit must be cleared. ANSELH has no effect on the output functionality of PORTB.

128

Introducci on
EXAMPLE 5: MODE 010: TWO INDEPENDENT COMPARATORS
b100x0000 b100x0001 02h (default) bxxxx1111

TIMER1 WITH GATE ENABLE


Two bits have been added to the T1CON register which were previously unimplemented. Bit 6 (TMR1GE) selects if Timer1 is gated by the T1G pin and bit 7 (T1GINV) changes the T1G pin from being active-high to active-low. By default, TMR1GE is off. Source code must have bit 6 of T1CON cleared in order for Timer1 to not be effected by the TMR1GE function.

CM1CON0 CM2CON0 CM2CON1 ANSEL

EXAMPLE 2:

TIMER1 WITH GATE ENABLE


bx0xxxxxx

EXAMPLE 6:

T1CON

MODE 011: TWO INDEPENDENT COMPARATORS WITH OUTPUTS


b101x0000 b101x0001 02h (default) bxxxx1111

COMPARATOR MODULES
The comparator module has changed from the PIC16F87XA to the PIC16F88X. The Comparator modes have been removed in favor of having two independent comparators. Each comparator has a separate control register and the old CMCON register of PIC16F87XA no longer exists. For each Comparator mode, the new settings should be as follows:

CM1CON0 CM2CON0 CM2CON1 ANSEL

EXAMPLE 7:

MODE 100: TWO COMMON REFERENCE COMPARATORS


b100x0000 b100x0001 02h (default) bxxxx1011

Note 1: CMCON of the PIC16F87XA is in bank 1. CM1CON0, CM2CON0 and CM2CON1 of the PIC16F88X are in bank 2. 2: The SRCON register should be left in its default state of 00h. 3: CVRCON register has been renamed VRCON and it was moved from address 9Dh to 97h in the memory map. The functionality of CVRCON has not changed.

CM1CON0 CM2CON0 CM2CON1 ANSEL

Comparator 2 will not function properly if this is the mode previously used. The positive input of comparator 2 cannot be mapped to the positive input of comparator 1 via software. The following settings have the positive input of comparator 2 mapped to RA2.

EXAMPLE 8:

EXAMPLE 3:

MODE 000: COMPARATOR RESET


b00000000 (default) b00000000 (default) 02h (default) bxxxx1111 CM1CON0 CM2CON0 CM2CON1 ANSEL

MODE 101: TWO COMMON REFERENCE COMPARATORS WITH OUTPUTS


b101x0000 b101x0001 02h (default) bxxxx1011

CM1CON0 CM2CON0 CM2CON1 ANSEL

EXAMPLE 4:

MODE 001: ONE INDEPENDENT COMPARATOR WITH OUTPUT


b10100100 b00000000 (default) 02h (default) bxxxx1001

Comparator 2 will not function properly if this is the mode previously used. The positive input of comparator 2 cannot be mapped to the positive input of comparator 1 via software. The following settings have the positive input of comparator 2 mapped to RA2.

CM1CON0 CM2CON0 CM2CON1 ANSEL

Cap tulo 10. Otros microcontroladores PIC avanzados


EXAMPLE 9: MODE 110: FOUR INPUTS MULTIPLEXED TO TWO COMPARATORS.
b100x0100 b100x0101 32h bxxxx1111

129

ANALOG-TO-DIGITAL CONVERTER
There are three major changes with the A/D module that affect the ADCON0 and ADCON1 registers. 1. One conversion clock select bit was removed from ADCON1, leaving 4 clock selections to time an A/D conversion. One additional channel select bit was added to ADCON0 to allow selection of channels AN9AN13. The port Configuration bits of ADCON1 register have been removed. Determination of analog or digital for and individual pin is now provided by the ANSELH:ANSEL register pair. If an analog function is required on AN<13:0> the corresponding bit of the ANSELH:ANSEL register pair should be set. Once the bit is set, the digital input driver of the corresponding port pin will be disabled. By default ANSELH and ANSEL are 0FFh.

CM1CON0 CM2CON0 CM2CON1 ANSEL

2.

Comparator 1 and comparator 2 may not function properly if this is the mode previously used. The negative input of comparator 1 can not be mapped to RA3 and the negative input of comparator 2 can not be mapped to RA2 via software. The following settings have the negative input of comparator 1 mapped to RA0 and the negative input of comparator 2 mapped to RA1.

3.

EXAMPLE 10:

MODE 111: COMPARATORS OFF

CM1CON0 CM2CON0 CM2CON1 ANSEL

b00000000 (default) b00000000 (default) 02h (default) bxxxx0000

To implement these changes both ADCON0 and ADCON1 have been redefined. These registers along with the ANSELH and ANSEL registers will have to be reconfigured to get a proper conversion.

130
REGISTER 1: ADCON0

Introducci on

ADCS1 bit 7

ADCS0

CHS3

CHS2

CHS1

CHS0

GO/DONE

ADON bit 0

Legend: R = Readable bit -n = Value at POR W = Writable bit 1 = Bit is set P = Programmable 0 = Bit is cleared U = Unimplemented bit, read as 0 x = Bit is unknown

bit 7-6

ADCS<1:0>: A/D Conversion Clock Select bits 00 = FOSC/2 01 = FOSC/8 10 = FOSC/32 11 = FRC (clock derived from a dedicated internal oscillator = 500 kHz max.)

bit 5-2

CHS<3:0>: Analog Channel Select bits 0000 = AN0 0001 = AN1 . . . 1101 = AN13 1110 = CVREF 1111 = Fixed Ref (0.6 volt fixed reference)

bit 1

GO/DONE: A/D Conversion Status bits 1 = A/D conversion cycle in progress. Setting this bit starts an A/D conversion cycle. This bit is automatically cleared by hardware when the A/D conversion has completed. 0 = A/D conversion completed/not in progress

bit 0

ADON: ADC Enable bit 1 = ADC is enabled 0 = ADC is disabled and consumes no operating current

REGISTER 2:
ADFM bit 7

ADCON1
VCFG1 VCFG1 bit 0

Legend: R = Readable bit -n = Value at POR W = Writable bit 1 = Bit is set P = Programmable 0 = Bit is cleared U = Unimplemented bit, read as 0 x = Bit is unknown

bit 7

ADFM: A/D Conversion Result Format Select bit 1 = Right justified 0 = Left justified

bit 6 bit 5

Unimplemented: Read as 0 VCFG1: Voltage Reference bit 1 = VREF- pin 0 = VSS

bit 4

VCFG1: Voltage Reference bit 1 = VREF+ pin 0 = VDD

bit 3-0

Unimplemented: Read as 0

Cap tulo 10. Otros microcontroladores PIC avanzados

131

ECCP AND CCP MODULES


The only change to the CCP modules is in the PWM mode of CCP1. No changes have been made to the Capture or Compare modes of the CCP or ECCP. Bits 7 and 6 of the CCP1CON register, which were previously unimplemented, have been added to control the P1B, P1C and P1D outputs. These outputs are typically used for driving a Half Bridge or Full Bridge and are only active in CCP1s PWM mode. To disable the P1B, P1C and P1D outputs, bits 7 and 6 of CCP1CON should be cleared.

CONFIGURATION WORDS
The Configuration Word of the PIC16F87XA product family has been expanded to two Configuration Words. Below are the definitions of the two Configuration Words for the PIC16F88X product family, verify they are set properly.

BROWN OUT DETECT


The Brown-out Detect circuit now has 2 separate voltages in which it can operate at, either 2.1 volts or 4.0 volts. Determination of the Brown-out trip point is determined by the setting of the BOR4 bit of Configuration Word 2. To enable the Brown-out Detect, there are now 3 different modes:

EXAMPLE 11:

CLEARING CCP1CON BITS 7 AND 6

CCP1CON

b00xxxxxx

EXAMPLE 13:

BROWN-OUT RESET CONFIGURATION WORD 1

EUSART WITH AUTO-BAUD


The baud rate of EUSART is controlled by the 16-bit SBRGH:SPBRG register pair. Previously the AUSART baud rate was controlled by the 8-bit SPBRG register. To have the EUSART operate at the same baud rate of the AUSART, both the SPBRGH and the BRG16-bit of the BAUDCTL register must be cleared. The EUSART also incorporates Auto-Baud Detection. Auto-baud is controlled exclusively by the BAUDCTL register and the SENDB bit of TXSTA. To disable this feature both the SENDB bit of the TXSTA register and the BAUDCTL register must remain cleared.

bit 9-8 BOREN<1:0>: Brown-out Reset Selection bits(1) 11 = BOR enabled 10 = BOR enabled during operation and disabled in Sleep 01 = BOR controlled by SBOREN bit of the PCON register 00 = BOR disabled Note 1: It is recommended for compatibility to have the BOREN<1:0> set to 11.

EXAMPLE 12:
TXSTA SPBRGH BAUDCTL bxxxx0xxx b00000000 b00000000

PROGRAM FLASH MEMORY WRITE


PIC16F87XA Erase Size Write Block Size 4 words 4 words PIC16F882/ 883/884 16 words 4 words PIC16F886/887 16 words 8 words

Writing to program memory for the PIC16F88X parts is performed in multiple block write to a row. A block consists of either four or eight words of sequential addresses and a row is defined as 16 words with the first address as EEADR<3:0>=0000. To write a row, you must write blocks sequentially starting at the first address of the row. The first block written to a row erases the entire row. Consecutive block writes to the same row will not cause an additional row erase. All other aspects of the Program Flash Memory Write remain the same.

132
REGISTER 3: CONFIG: CONFIGURATION WORD REGISTER

Introducci on

bit 15

DEBUG

LVP

FCMEN

IESO

BOREN1

BOREN0 bit 8

CPD bit 7

CP

MCLRE

PWRTE

WDTE

FOSC2

FOSC1

FOSC0 bit 0

Legend: R = Readable bit -n = Value at POR W = Writable bit 1 = Bit is set P = Programmable 0 = Bit is cleared U = Unimplemented bit, read as 0 x = Bit is unknown

bit 15-14 bit 13

Unimplemented: Read as 1 DEBUG: In-Circuit Debugger Mode bit 1 = In-Circuit Debugger disabled, RB6/CSPCLK and RB7/ICSPDAT are general purpose I/O pins 0 = In-Circuit Debugger enabled, RB6/CSPCLK and RB7/ICSPDAT are dedicated to the debugger LVP: Low Voltage Programming Enable bit 1 = RB3/PGM pin has PGM function, low voltage programming enabled 0 = RB3 pin is digital I/O, HV on MCLR must be used for programming FCMEN: Fail-Safe Clock Monitor Enabled bit 1 = Fail-Safe Clock Monitor is enabled 0 = Fail-Safe Clock Monitor is disabled IESO: Internal External Switchover bit 1 = Internal External Switchover mode is enabled 0 = Internal External Switchover mode is disabled BOREN<1:0>: Brown-out Reset Selection bits(1) 11 = BOR enabled, SBOREN bit disabled 10 = BOR enabled during operation and disabled in Sleep, SBOREN bit disabled 01 = BOR controlled by SBOREN bit of the PCON register 00 = BOR and SBOREN bits disabled

bit 12

bit 11

bit 10

bit 9-8

bit 7

CPD: Data Code Protection bit(2) 1 = Data memory code protection is disabled 0 = Data memory code protection is enabled
CP: Code Protection bit(3) 1 = Program memory code protection is disabled 0 = Program memory code protection is enabled MCLRE: MCLR pin function select bit(4) 1 = MCLR pin function is MCLR 0 = MCLR pin function is digital input, MCLR internally tied to VDD PWRTE: Power-up Timer Enable bit 1 = PWRT disabled 0 = PWRT enabled WDTE: Watchdog Timer Enable bit 1 = WDT enabled 0 = WDT disabled and can be enabled by SWDTEN bit of the WDTCON register FOSC<2:0>: Oscillator Selection bits 111 = EXTRC oscillator: External RC on RA5/OSC1/CLKIN, CLKOUT function on RA4/OSC2/CLKOUT pin 110 = EXTRCIO oscillator: External RC on RA5/OSC1/CLKIN, I/O function on RA4/OSC2/CLKOUT pin 101 = INTOSC oscillator: CLKOUT function on RA4/OSC2/CLKOUT pin, I/O function on RA5/OSC1/CLKIN 100 = INTOSCIO oscillator: I/O function on RA4/OSC2/CLKOUT pin, I/O function on RA5/OSC1/CLKIN 011 = EC: I/O function on RA4/OSC2/CLKOUT pin, CLKIN on RA5/OSC1/CLKIN 010 = HS oscillator: High-speed crystal/resonator on RA4/OSC2/CLKOUT and RA5/OSC1/CLKIN 001 = XT oscillator: Crystal/resonator on RA4/OSC2/CLKOUT and RA5/OSC1/CLKIN 000 = LP oscillator: Low-power crystal on RA4/OSC2/CLKOUT and RA5/OSC1/CLKIN

bit 6

bit 5

bit 4

bit 3

bit 2-0

Note 1: 2: 3: 4:

Enabling Brown-out Reset does not automatically enable Power-up Timer. The entire data EEPROM will be erased when the code protection is turned off. The entire program memory will be erased when the code protection is turned off. When MCLR is asserted in INTOSC or RC mode, the internal clock oscillator is disabled.

Cap tulo 10. Otros microcontroladores PIC avanzados


REGISTER 4:
bit 15

133

CONFIG2: CONFIGURATION WORD REGISTER 2


WRT1 WRT0 BOR4V bit 8

bit 7

bit 0

Legend: R = Readable bit -n = Value at POR W = Writable bit 1 = Bit is set P = Programmable 0 = Bit is cleared U = Unimplemented bit, read as 0 x = Bit is unknown

bit 15-11 bit 10-9

Unimplemented: Read as 1 WRT<1:0>: Flash Program Memory Self Write Enable bits PIC16F883/PIC16F884 00 = 0000h to 07FFh write-protected, 0800h to 0FFFh may be modified by EECON control 01 = 0000h to 03FFh write-protected, 0400h to 0FFFh may be modified by EECON control 10 = 0000h to 00FFh write-protected, 0100h to 0FFFh may be modified by EECON control 11 = Write protection off PIC16F886/PIC16F887 00 = 0000h to 0FFFh write-protected, 1000h to 1FFFh may be modified by EECON control 01 = 0000h to 07FFh write-protected, 0800h to 1FFFh may be modified by EECON control 10 = 0000h to 00FFh write-protected, 0100h to 1FFFh may be modified by EECON control 11 = Write protection off PIC16F882 00 = 0000h to 07FFh write-protected, entire program memory is write protected 01 = 0000h to 03FFh write-protected, 0100h to 07FFh may be modified by EECON control 10 = 0000h to 00FFh write-protected, 0100h to 07FFh may be modified by EECON control 11 = Write protection off

bit 8

BOR4V: Brown-out Reset Selection bit 0 = Brown-out Reset set to 2.1V 1 = Brown-out Reset set to 4.0V

bit 7-0

Unimplemented: Read as 1

134

Gu a de productos de Microchip de 8 bits

10.2. Gu a de productos de Microchip de 8 bits

Cap tulo 10. Otros microcontroladores PIC avanzados

135

136

Gu a de productos de Microchip de 8 bits

Cap tulo 10. Otros microcontroladores PIC avanzados

137

138

Gu a de productos de Microchip de 8 bits

Cap tulo 10. Otros microcontroladores PIC avanzados

139

140

Gu a de productos de Microchip de 8 bits

Cap tulo 10. Otros microcontroladores PIC avanzados

141

142

Gu a de productos de Microchip de 8 bits

Cap tulo 10. Otros microcontroladores PIC avanzados

143

144

Gu a de productos de Microchip de 8 bits

Cap tulo 10. Otros microcontroladores PIC avanzados

145

146

Gu a de productos de Microchip de 8 bits

Cap tulo 10. Otros microcontroladores PIC avanzados

147

148

Gu a de productos de Microchip de 8 bits

Cap tulo 10. Otros microcontroladores PIC avanzados

149

150

Otras familias

10.3. Otras familias

Need additional memory or peripherals?

Cut down you cycle time! D Microchips d easy migratio our entire por devices. Upgr product with replacements code has nev with our MPL Development (IDE), and sim compatible d 8-Bit, 16-Bit and 32-Bit Microcontroller (MCU) and Digital Signal Controller (DSC) Products easy-to-use product roadmaps display the migration pa
Program RAM Memory (Bytes) (Kbytes) 8-Bit MCUs Baseline (12-bit Instruction Word) Family PIC10FXXX 0.375-0.75 16-24 Pins Max Speed A/D Ch. A/D Res. (bits) A/D Sample (ksps) Comp 8/16/32-bit Timers (x8, x16, x32) 1 x8 1 x8 1 x8 1-2 x8, 1 x16 1-2 x8, 1 x16 1-2 x8, 1 x16 2 x8, 1 x16 0-2 x8, 2-3 x16 1-2 x8, 2-3 x16 1 x8, 3 x16 5 x16 3-9 x16 3-5 x16 3-9 x16 3-5 x16 3-9 x16 3 x16 2-3 x16 5 x16, 1 x32 Communication Peripherals PWM Ch. PWM Type Other Features 4-8 MHz, 0-2 8 75 (1-2 MIPS) 4-8 MHz, PIC12FXXX 0.75-1.50 25-41 8 0-3 8 75 (1-2 MIPS) 20 MHz, PIC16FXXX 0.75-3.0 25-134 14-44 0-3 8 75 (5 MIPS) 8-Bit MCUs Mid-Range (14-bit Instruction Word), ICSP (except ROM), Self-Write and nanoWatt available 20 MHz, PIC12FXXX 1.75-3.5 64-128 8 0-4 10 30 (5 MIPS) 20 MHz, PIC12HVXXX 1.75 64 8 0-4 10 30 (5 MIPS) 20 MHz, PIC16FXXX 1.75-14 64-368 14-64 0-13 8 or 10 30 (5 MIPS) 20 MHz, 0-12 10 30 PIC16HVXXX 1.75-3.5 64-128 14-20 (5 MIPS) 8-Bit MCUs High Performance (16-bit Instruction Word), ICSP, Self-Write and nanoWatt available 32-48 MHz, 4-16 10 or 12 30-200 PIC18FXXX 4-128 256-3936 18-80 (12 MIPS) 40-48 MHz, 10-16 10 100 PIC18FXXJXX 8-128 1024-3936 28-100 (10-12 MIPS) 64 MHz, PIC18FXXKXX 8-64 768-3936 28-44 10-13 10 100 (16 MIPS) 16-Bit MCUs General Purpose (24-bit Instruction Word), ICSP, Self-Write, nanoWatt 32 MHz, PIC24FXXX 16-256 4K-16K 28-100 10-16 10 500 (16 MIPS) 160 MHz, 500 or PIC24HXXX 12-256 1K-16K 18-100 6-32 10 or 12 (40 MIPS) 1.1M 16-Bit DSCs General Purpose (24-bit Instruction Word), ICSP, Self-Write, nanoWatt 120 MHz, dsPIC30FXXX 24-144 2K-8K 40-80 13-16 12 200 (30 MIPS) 160 MHz, 500 or dsPIC33FXXX 12-256 1K-30K 18-100 6-32 10 or 12 (40 MIPS) 1.1M 16-Bit DSCs Motor Control (24-bit Instruction Word), ICSP, Self-Write, nanoWatt 120 MHz, dsPIC30FXXX 12-144 512-8K 28-80 6-16 10 1.0M (30 MIPS) 160 MHz, 500 or dsPIC33FXXX 12-256 1K-30K 20-100 4-24 10 or 12 (40 MIPS) 1.1M 16-Bit DSCs Sensor (24-bit Instruction Word), ICSP, Self-Write, nanoWatt 120 MHz, dsPIC30FXXX 12-24 1K-2K 18-28 8-10 12 200 (30 MIPS) 16-Bit DSCs SMPS and Digital Power Conversion (24-bit Instruction Word), ICSP, Self-Write, nanoWatt 120 MHz, dsPIC30FXXX 6-12 256-512 28-44 6-12 10 2.0M (30 MIPS) 32-Bit MCUs High Performance, General Purpose (32-bit and 16-bit Instruction Word), ICSP, Self-Write 80 MHz, PIC32MXXX 32-512 8K-32K 64-100 16 10 400 (80 MIPS) 6 0-1 0-1 0-2 1 1 0-2 2 0-3 2 2 2-3 0-2 0-2 0-2 2-4 2 A/E/USART, MI2C/SPI USB 2.0, CAN 2.0, A/E/USART, MI2C/SPI USB 2.0, A/EUSART, Ethernet, MI2C, SPI EUSART, MI2C, SPI UARTw/IrDA, I2C, SPI, USB OTG UARTw/IrDA, I2C, SPI, ECAN UART, I C, SPI, CAN, DCI (AC97/I2S)* UART w/IrDA, I2C, SPI, ECAN, DCI UART, I2C/SPI, QEI, CAN UART w/IrDA, I2C, SPI, QEI, ECAN UART, I2C, SPI UART, I2C/SPI UART w/IrDA, I2C, SPI, USB OTG
2

0-2 0-2 0-4 0-4 0-5 2-5 2 5-9 2-8 2-8 2-8 6-8 6-8 2 4-8 5

CCP/ECCP ECCP CCP/ECCP CCP/ECCP CCP/ECCP , Motor Ctrl.* CCP/ECCP CCP/ECCP Standard Standard Standard Standard Motor Ctrl. Motor Ctrl. Standard High-speed Standard

Flash Data Memory* Flash Data Memory* EEPROM* Shunt Regulator, 15V Operation PSP*, Op amp*, LCD*, EEPROM* Shunt Regulator, Op amp*, 15V Operation PSP*, EMA*, EEPROM*, LCD PMP*, PSP*, EMA*, LCD PSP* CRC, RTCC, PMP , PPS*, JTAG, CTMU PPS*, CodeGuard , JTAG, DMA, PMP*, RTCC*, CRC* CodeGuard, EEPROM CodeGuard, JTAG, DMA, PMP*, RTCC*, DAC*, CRC* CodeGuard, EEPROM CodeGuard, JTAG, DMA*, PMP*, RTCC*, CRC* CodeGuard, EEPROM* CodeGuard DMA, CRC, RTCC, JTAG, Trace, PMP16, VREG, Code Protect

Parte II PRACTICUM

151

Cap tulo 11 Grabador/ bootloader


En Espana, la mejor manera de guardar un secreto es escribir un libro Manuel Azana

11.1. Grabador
11.1.1. Hardware compatible JDM
Se trata de montar el siguiente grabador que es un programador por puerto serie externa y que est sin alimentacion a basado en el grabador JDM de bajo precio. Este es v diseno alido para los modelos de 18 (16F84A, 16F88, etc.), 28 (16F876, 17F873, etc.) y 40 patillas (16F877, 16F874, etc.) de la serie 16F de Microchip.

153

154 Esquema el ectrico


R1 U2
16 15 4 15k RES40

Grabador

OSC1/CLKIN OSC2/CLKOUT MCLR

RA0 RA1 RA2 RA3 RA4/TOCKI RB0/INT RB1 RB2 RB3 RB4 RB5 RB6 RB7

17 18 1 2 3 6 7 8 9 10 11 12 13

Q1
BC549 TO92/18

J2
1 6 2 7 3 8 4 9 5 DB9H PCB D-09-F-R

PIC16F84 DIL18

R2
VDD 10k RES40

U1
9 10 1 2 3 4 5 6 7

D2
RB0/INT RB1 RB2 RB3/PGM RB4 RB5 RB6/PGC RB7/PGD RC0/T1OSO/T1CKI RC1/T1OSI/CCP2 RC2/CCP1 RC3/SCK/SCL RC4/SDI/SDA RC5/SDO RC6/TX/CK RC7/RX/DT
21 22 23 24 25 26 27 28 11 12 13 14 15 16 17 18 LED PACKAGE=DO35

OSC1/CLKIN OSC2/CLKOUT MCLR/Vpp/THV RA0/AN0 RA1/AN1 RA2/AN2/VREFRA3/AN3/VREF+ RA4/T0CKI RA5/AN4/SS

C1
100uF ELEC-RAD10 13 14 1 2 3 4 5 6 7 VSS 8 9 10

U3
OSC1/CLKIN OSC2/CLKOUT MCLR/Vpp/THV RA0/AN0 RA1/AN1 RA2/AN2/VREFRA3/AN3/VREF+ RA4/T0CKI RA5/AN4/SS RE0/AN5/RD RE1/AN6/WR RE2/AN7/CS RB0/INT RB1 RB2 RB3/PGM RB4 RB5 RB6/PGC RB7/PGD RC0/T1OSO/T1CKI RC1/T1OSI/CCP2 RC2/CCP1 RC3/SCK/SCL RC4/SDI/SDA RC5/SDO RC6/TX/CK RC7/RX/DT RD0/PSP0 RD1/PSP1 RD2/PSP2 RD3/PSP3 RD4/PSP4 RD5/PSP5 RD6/PSP6 RD7/PSP7
PIC16F877 DIL40 33 34 35 36 37 38 39 40 15 16 17 18 23 24 25 26 19 20 21 22 27 28 29 30

R3
680 RES40

D1
Zenner 5V1 DO35

PIC16F876A DIL28 NARROW /MCLR RB7/PGD RB6/PGC GND VDD

Grabador PIC16F87x/16F8x

J1
CONN-SIL5

Placa de circuito impreso Vista por la cara de componentes, se hacen notar los dos puentes que tiene.

Vista de la cara de soldadura (desde la cara de componentes)

1 2 3 4 5

Cap tulo 11. Grabador/ bootloader

155

Listado de materiales QTY 1 1 1 1 1 1 1 1 1 1 1 1 PART-REFS VALUE PACKAGE R1 15k RES40 R2 10k RES40 R3 680 RES40 C1 100uF ELEC-RAD10 U1 Tiras pin hembra DIL28 NARROW (opcional) U2 Tiras pin hembra DIL18 (opcional) U3 Tiras pin hembra DIL40 Q1 BC549 TO92/18 D1 Zenner 5V1 DO35 D2 LED DO35 J1 Tira pin macho CONN-SIL5 J2 DB9H PCB D-09-F-R

Se conectar a a un puerto serie de un PC con un cable alargador serie (macho por un lado y hembra por el otro).

156 Fotograf a del grabador montado

Grabador

11.1.2. Software ICProg


Es el programa que emplearemos para grabar los circuitos usando el montaje an m terior. La version as actual (26 de agosto de 2008) es la 1.06B que se adjunta en el CDROM. El cuadro principal de dialogo del programa se muestra a continuacion:

Para su uso con nuestro grabador deber a estar congurado como sigue:

Cap tulo 11. Grabador/ bootloader

157

Es muy sencillo de manejar. Se elige el microcontrolador. Se carga el chero .hex a (a la derecha de la pantalla principal) y se grabar. Se revisa la palabra de conguracion programa todo.

11.2. Bootloader
que se graba en el micro para permiEl bootloader es un programa muy pequeno tir comunicar el microcontrolador con el ordenador a trav es de puerto serie y de esta manera transmitirle el programa directamente al micro a trav es del bootloader sin necesidad de extraer el microcontrolador de nuestro sistema al hardware grabador y viceversa. Para ello condenamos dos patillas del microcontrolador -las del puerto seriea este uso espec co y consumimos parte de la memoria del microcontrolador -en torno a 256 posiciones de memoria Flash-.

11.2.1. Montaje bootloader para micros de 28 patillas


v Se trata de montar el siguiente diseno, alido para los modelos de 28 patillas de la serie 16F87x de Microchip.

158 Esquema el ectrico

Bootloader

R2 X1 U2
9 10 1 2 3 4 5 6 7 OSC1/CLKIN OSC2/CLKOUT MCLR/Vpp/THV 20 10k 21 22 23 24 25 26 27 28 11 12 13 14 15 16 17 18

VDD

Resonador 4MHz

PLPCB1
CONN-S2 VDD

C3
0.1uF

C5
0.1uF

5 9 4 8 3 7 2 6 1 CONN-D9F

GND

CTS_Out TxD_In RTS_In RxD_Out

1 2 3 4 5 6 7 8

C1+ VCC V+ GND C1T1OUT C2+ R1IN C2R1OUT VT1IN T2OUT T2IN R2IN R2OUT MAX232

16 15 14 13 12 11 10 9

PIC16F876 8 19

C4
0.1uF

C6
0.1uF

C1
100nF

VSS

Diseno de la placa de circuito impreso Vista de la cara de componentes.

Vista de la cara de soldadura desde la cara de componentes.

Listado de componentes
QTY PART-REFS --- --------Resistors --------1 R2 VALUE ----10k

VSS VSS

J1

U1

RA0/AN0 RA1/AN1 RA2/AN2/VREFRA3/AN3/VREF+ RA4/T0CKI RA5/AN4/SS RC0/T1OSO/T1CKI RC1/T1OSI/CCP2 RC2/CCP1 RC3/SCK/SCL RC4/SDI/SDA RC5/SDO RC6/TX/CK RC7/RX/DT

RB0/INT RB1 RB2 RB3/PGM RB4 RB5 RB6/PGC RB7/PGD

2 1

Cap tulo 11. Grabador/ bootloader

159

Capacitors ---------1 C1 4 C3-C6 Integrated Circuits ------------------1 U1 1 U2 Miscellaneous ------------1 J1 1 PLPCB1 1 X1

100nF 0.1uF

MAX232 Zocalo 28 pin estrecho

CONN-D9F Tira pin hembra (x2) Resonador/cristal 4MHz

11.2.2. Montaje bootloader para micros de 40 patillas


Esquema el ectrico
X1
13 14 1 2 3 4 5 6 7

U2
OSC1/CLKIN OSC2/CLKOUT MCLR/Vpp/THV RB0/INT RB1 RB2 RB3/PGM RB4 RB5 RB6/PGC RB7/PGD 33 34 35 36 37 38 39 40 15 16 17 18 23 24 25 26 19 20 21 22 27 28 29 30

Resonador 4MHz

R2
10k

PLPCB1
CONN-S2

8 9 10

RA0/AN0 RA1/AN1 RA2/AN2/VREFRA3/AN3/VREF+ RA4/T0CKI RA5/AN4/SS RC0/T1OSO/T1CKI RC1/T1OSI/CCP2 RE0/AN5/RD RC2/CCP1 RE1/AN6/WR RC3/SCK/SCL RE2/AN7/CS RC4/SDI/SDA RC5/SDO RC6/TX/CK RC7/RX/DT RD0/PSP0 RD1/PSP1 RD2/PSP2 RD3/PSP3 RD4/PSP4 RD5/PSP5 RD6/PSP6 RD7/PSP7 PIC16F877

C3
0.1uF

C5
0.1uF

2 1 C1+ VCC V+ GND C1T1OUT C2+ R1IN C2R1OUT VT1IN T2OUT T2IN R2IN R2OUT 16 15 14 13 12 11 10 9

VDD

J1
5 9 4 8 3 7 2 6 1 CONN-D9F GND 1 2 3 4 5 6 7 8

U1

CTS_Out TxD_In RTS_In RxD_Out

MAX232

C4
0.1uF

C6
0.1uF VSS

C1
100nF

Diseno de la placa de circuito impreso Vista de la cara de componentes.

160 Vista de la cara de soldadura desde la cara de componentes.

Bootloader

Listado de componentes
QTY PART-REFS --- --------Resistors --------1 R2 Capacitors ---------1 C1 4 C3-C6 Integrated Circuits ------------------1 U1 1 U2 Miscellaneous ------------1 J1 1 PLPCB1 1 X1 VALUE ----10k

100nF 0.1uF

MAX232 Zocalo 40 pin (pines largos)

CONN-D9F Tira pin hembra (x2) Resonador/cristal 4MHz

Cap tulo 11. Grabador/ bootloader Fotograf a del diseno montado y funcionando

161

11.2.3. Software
Firmware del microcontrolador El rmware b asico se encuentra en el CDROM. Existen dos versiones, una para la familia 16F87x y otra para la familia 16F87xA. Habr a que congurar la velocidad del del microcontrolador, as puerto serie y la frecuencia de operacion como la palabra de que pretendamos emplear en nuestra aplicacion. conguracion En nuestro caso trabajaremos con un 16F877 a 4 MHz y con una velocidad de 19200. Adem as deberemos procurar que: con LVP_OFF. El codigo del bootloader tenga la palabra de conguracion Que el codigo de usuario que compilemos para ser cargado con el bootloader tenga la forma:
ORG 0 goto ORG 4 ... Inicio ... Inicio

Es decir, es obligatorio que las cuatro primeras posiciones de la memoria sean de esta manera. Si el programa se realiza en lenguaje C bastar a con usar la opcion -ICD en el compilador.

162

Bootloader

aplicacion se debe grabar en el microcontrolador usando el diseno del Esta pequena grabador. Una vez programado se puede montar y alimentar. Al estar conectado al PC a trav es del puerto serie (emplea el mismo cable alargador) se pueden descargar los espec programas desde una aplicacion ca (PICdownloader.exe) del PC, sin tener que desmontar nada y sin el riesgo potencial de romper patas, conectar al rev es, etc. Listado 11.1: EX/BOOT/BOOTLDR 16F877.asm
;****************************************************************************** ; Bootloader for Microchip PIC16F870/871/873/874/876/877 * ; (c) 2000-2002, Petr Kolomaznik * ; Freely distributable * ;******************************************************************************

Listado 11.2: EX/BOOT/BOOTLDR 16F877.asm


;================== User setting section ====================================== list p=16f877 include "p16f877.inc" #define ICD_DEBUG 0 #define #define #define #define #define #define #define ; ; ; ; ; FOSC D4000000 ; BAUD D19200 ; BAUD_ERROR D4 ; TIME ; ; ; TRIGGER PORTB,7 ; TIMEOUT D6 ; WATCHDOGTIMER 0 ; <<< set type of microcontroller set same microcontroller in the project <<< if using MPLAB ICD Debugger, moves bootloader down 256 bytes to make room for it [0|1] <<< set quartz frequence [Hz], max. 20 MHz <<< set baud rate [bit/sec] <<< set baud rate error [ %] <<< set method of bootloader start PIN/TIME PIN : start on low level of trigger pin TIME: start on receive IDENT byte in TIMEOUT <<< only for PIN - set PORT_X,PIN_NR <<< only for TIME - set time [0.1s], max. 25 sec <<< Watchdog timer default OFF/ON [0|1]

10

15

Programa para la descarga Por ejemplo podemos usar el programa PICdownloader.exe, presente en el CDROM, como se muestra a continuacion:

Cap tulo 12 Software: Proteustm


Si no esper ais lo inesperado no lo encontrar eis, dado que es penoso descubrirlo, y adem as dif cil Her aclito de Efeso

12.1. Proteus
12.1.1. Introduccion
asistido por ordenador que permite dibujar Proteustm es un programa de diseno el esquema hardware de nuestros disenos y simularlos (tipo SPICE). La ventaja es h que permite una simulacion brida digital/analogica que permite simular tambi en algunos microcontroladores (los m as frecuentemente utilizados) y lo que es m as importante depurar el funcionamiento de nuestras aplicaciones. En esta pr actica pretendemos hacer uso de esta herramienta que se puede adquirir profesional para a trav es de la p agina web del Labcenter Microelectronics 1 . La version principiantes permite simular el microcontrolador 16F877 adem as del 16F84A y del 18F452 por unas 150 libras esterlinas (20 % de descuento si el uso es educacional). shareware2 (gratuita) que permite simular solamente el microconExiste una version trolador PIC16F84A. se incluyen en el CDROM. Todas las versiones (de demostracion)

12.1.2. Primeros pasos con Proteus ISIS


Para comenzar el tutorial lo primero es arrancar el programa, que tiene una pantalla Hay que indicar que inicial, despu es del logotipo como la que aparece a continuacion. el sistema Proteus consta de dos modulos o programas diferenciados: ISIS que es el modulo que permite hacer la captura esquem atica y las simulaciones -y que es objeto de placas de circuito de este tutorial- y ARES que es el modulo dedicado al diseno impreso (PCBs).
1 2

http://www.labcenter.co.uk http://www.proteuslite.com

163

164

Proteus

Inicialmente debemos crear un proyecto vac o (FileNew) o abrir uno ya existente (FileOpen). Si partimos de un nuevo proyecto distinguimos varias partes en la ven y que son: la barra de herramientas en la parte superior, debajo tana de la aplicacion una barra de estado que en realidad nos permitir de los menus, a modicar geom etricamente los componentes, y que adem as permitir a mediante cuatro sencillos botones pararla, ejecutar un paso, etc. Adem arrancar la simulacion, as tenemos otra barra de herramientas en formato vertical que va acompanada de una lista de dispositivos. Por ultimo tenemos la hoja donde vamos a colocar los distintos componentes. vamos a situar el montaje b En un primer diseno asico de un microcontrolador: el PIC 16F877. Para ello es necesario seleccionarlo. Con el atajo de teclado P lograremos situar cualquier componente como se ve en la siguiente gura:

Cap tulo 12. Software: Proteustm

165

Simplemente debemos teclear el nombre o parte del nombre del dispositivo busca de uno de ellos do y nos aparecer a una lista de posibles candidatos y con la seleccion el esquema gr aco que lo dene. Una vez aceptado el componente solo tendremos que seleccionar un lugar con el y pulsar el boton izquierdo para situarlo en la hoja de diseno: raton

Haremos lo mismo con otros componentes necesarios como el cristal de cuarzo (CRYSTAL).

166

Proteus

Para trazar un cable entre dos elementos simplemente aproximaremos el cursor izquierdo del raton para trazar hasta la patilla correspondiente y pulsaremos el boton autom aticamente el cable. Si queremos que el cable recorra una gura determinada, simplemente pulsaremos a lo largo del camino a recorrer y terminaremos con el segundo elemento.

Despu es de haber colocado y conectado otros elementos como los condensadores (CAP), necesitaremos poner algunas tierras (GROUND) y alimentaciones (POWER).

Cap tulo 12. Software: Proteustm

167

Estas se encuentran pulsando en la barra de herramientas vertical el icono relacionado con los terminales.

de estos elementos se hace de la misma manera. Si necesitamos ver amLa conexion se puede hacer a trav de la barra de herramientas pliada la hoja de diseno es del menu, horizontal o utilizando los atajos de teclado (teclas F5,F6,F7,F8). Una vez colocados los componentes querremos modicar su valor. Para ello selec l con el boton derecho del raton, cionamos el componente concreto pulsando sobre e con el boton izquierdo. Cuidado por que si pulsamos dos veces con y a continuacion derecho eliminaremos el componente. El atajo de teclado U nos ayudar el boton aa el componente borrado por error. recuperar (deshacer la ultima operacion)

168

Proteus

Despu es de haber modicado los valores como los que aparecen en la gura (resistencias: RES), deberemos indicarle al microcontrolador con qu e frecuencia va a ser simulado.

Seleccionamos el micro y editamos sus propiedades

Cap tulo 12. Software: Proteustm

169

Colocaremos la frecuencia de reloj coincidente con la del cristal de cuarzo del es quema. Ahora ha llegado el momento de anadir codigo al microcontrolador.

SourceAdd/Remove Source Files .. seleccionaremos el Por lo tanto, en el menu listado en ensamblador o C (si se dispone del compilador correspondiente) que queremos colocar en el micro (el programa principal; los dem as cheros estar an incluidos de alguna manera en el chero principal).

Si el chero no existe no importar a ya que ser a creado al editarlo

170

Proteus

en este caso seAl mismo tiempo seleccionaremos la herramienta de compilacion, leccionaremos MPASMWIN.

Source aparecer se Dentro del menu a el chero relacionado. Pulsando esa opcion arrancar a un editor para modicar/crear el programa.

Cap tulo 12. Software: Proteustm Escribiremos el siguiente codigo:


LIST P=16F877, R=DEC INCLUDE "P16F877.INC" ORG 0 goto ORG 4 Inicio bcf bsf movlw movwf movlw movwf clrf bcf Bucle movfw addlw movwf goto END STATUS,RP1 STATUS,RP0 11111111b TRISA 6 ADCON1 TRISB STATUS,RP0 PORTA 2 PORTB Bucle Inicio

171

; Selecciona el banco 1 ; W=111111111b ; TRISA = W (PORTA todo entradas) ; PORTA digital ; TRISB = 0 (PORTB todo salidas) ; Selecciona el banco 0 ; W = PORTA ; W = W + 2 ; PORTB = W

SourceBuild All. Y lo compilaremos mediante la opcion

error de sintaxis aparecer Si todo fue bien y no cometimos ningun a la siguiente ventana indic andonos que todo fue bien. El ensamblador/compilador utilizado es ex terno al entorno, luego se pueden anadir herramientas de este tipo para programar el microcontrolador en el lenguaje que deseemos.

172

Proteus

Finalmente deberemos incluir el codigo compilado en el microcontrolador. Seleccionamos el micro y editamos sus propiedades. En este caso rellenaremos el campo .HEX Program File con el chero generado que tendr a extension

Seleccionamos el chero:

Cap tulo 12. Software: Proteustm

173

Ahora podemos proceder a simular el circuito dando a la tecla PLAY de la barra de estado. Se generar a una lista de nodos, se compilar a todo lo necesario, y se comen zar a la simulacion

174

Proteus

Nos faltar a anadir algunos elementos m as para ver el funcionamiento de forma m as correcta (LOGICSTATE).

Cap tulo 12. Software: Proteustm

175

Para depurar el programa no tenemos m as que pulsar la tecla PAUSE de la barra de estado y podremos ejecutar paso a paso las instrucciones, examinar la memoria, los Debug. registros, nuestras variables, etc. Todo esto se selecciona en el menu

176

Proteus

Al tiempo que se ejecutan paso a paso las instrucciones, el esquema se actualizar a encendiendo y apagando los LEDs conectados, funcionando los instrumentos virtuales colocados, los displays, etc.

12.1.3. Primeros pasos con Proteus ARES


rePara conseguir hacer una PCB con Proteus ARES hay que partir de un diseno alizado con Proteus ISIS en el que todos los componentes empleados dispongan de del bootloader de 28 su correspondiente huella (footprint). Voy a trabajar con el diseno pines para seguir un ejemplo:

Cap tulo 12. Software: Proteustm

177

Para poder comprobar las huellas que van a emplear cada unos de los elementos vamos a editarlos y vamos a mostrar la huella. Se hace seleccionado y Ctrl-E para editar las propiedades. El campo PCB package debe estar denido y decimos que oculte el nombre pero no el valor:

El esquema quedar a como sigue:

178

Proteus

Despu es de esto pasaremos al modulo ARES invocando Ctrl-A o accediendo al Tools-Netlist to ARES: menu

Aparecer a el programa Proteus ARES en pantalla y si todo fue bien -esto es, que todos los componentes tienen una huella v alida- estaremos en el siguiente punto. Si al guna huella no estuviera, se puede saltar (skip) y cambiando al programa ISIS anadirla. Tambi en podemos consultar las huellas disponibles en ARES (atajo de teclado P).

Cap tulo 12. Software: Proteustm

179

Seleccionamos de la lista de la izquierda las huellas y las vamos situando en el cuadro de trabajo intentando situarlos convenientemente para un trazado de pistas sencillo:

180

Proteus

El trazado de las pistas se hace seleccionando en la lista de herramientas vertical del lado izquierdo y traz andolas directamente. El lado o plano se puede elegir con el espacio o con avanzar/retroceder p agina, o con el cuadro inferior izquierdo. Esto es la manera de hacerlo manual que al nal es la mejor.

Cap tulo 12. Software: Proteustm

181

Existen dos m etodos de rutado autom atico: uno integrado en ARES y otro externo que es el bueno (Electra AutoRouter) y que viene con Proteus. Este ultimo lo comentar e al nal. Ahora anadimos el borde (capa Edge en modo de dibujo) y la serigraf a restante:

182

Proteus

Para terminar generamos los cheros Gerber de pistas y Excellon de taladros para mandar fabricar la PCB. Lo mejor es incluir todas las capas necesarias y ponerlo en un Output-CADCAM Output chero empaquetado (.zip). En el menu

Cap tulo 12. Software: Proteustm

183

En el caso de que queramos emplear el autorouter, hay que decir que requiere una Tools-Electra fase previa que es indicarle el borde (capa Edge) y arrancar en el menu Autorouter

En el cuadro de arranque de la herramienta de autorutado externa simplemente la ejecutamos:

Y obtenemos otra ventana en la que le indicamos que lo haga. Al salir se importar a el resultado y podremos seguir.

12.2. PIC C
12.2.1. Introduccion
Si deseamos escribir nuestros programas utilizando un lenguaje de alto nivel como puede ser C podemos acudir a los multiples fabricantes de software. Se recomienda un compilador de C de la casa HI-TECH3 ).
3

http://www.htsoft.com/products/picccompiler.php

184 La p agina WEB del HITECH:

PIC C

una version de evaluacion (con prestaciones y duracion pone a nuestra disposicion 4 temporal limitadas) y versiones gratuitas y que se adjuntan en el CDROM.

http://www.htsoft.com/downloads/demos.php

Cap tulo 12. Software: Proteustm

185

12.2.2. Conguracion de Proteustm


Source Para poder utilizarlo con Proteustm se debe hacer lo siguiente en el Menu: Define Code Generation Tools. Se crea una nueva entrada (PICC) que se rellena como sigue:

Entre las opciones marcadas para el compilador est an


-ASMLIST. Genera un chero de listado en ensamblador (.LST). y depuracion compatible con MPLAB. Genera los cheros *.cof que -MPLAB. Compilacion vamos a emplear. del depurador en circuito de -ICD. Le decimos al compilador que queremos usar la prestacion Microchip que reserva 256 posiciones den la parte alta de la memoria de programa y algunas en la RAM. Con esto permitimos el uso de un programa bootloader que permitir a grabar el circuito sin necesidad de extraerlo y usar el grabador. -16F877A. Decidimos para que microcontrolador queremos que se compile. Esto habr a que modicarlo en cada proyecto ya que no se guarda con el esquem atico. optimizada y optimizacion global. Si no funcionara bien la depuracion -O -Zg9. Compilacion paso a paso, se puede probar a quitar optimizaciones (quitando -Zg9). -O %2. Especicamos el chero de salida. -Eerror.txt. Especicamos el chero (error.txt) donde se escribir an los mensajes de error. Este chero lo deberemos visualizar para comprobar los errores.

Si diera un error y no apareciese el chero error.txt signicar a que el error de la orden a ejecutar (Command line). est a en la denicion

186

MPLAB

12.2.3. Uso en Proteustm


Crearemos un nuevo chero fuente y le asignaremos como compilador el que acabamos de denir. Para compilar lo haremos de la forma habitual. El chero a incluir en el microcontrolador podr a ser, si se desea, el *.hex que ser a el empleado desde el programa en lenguaje C se deber grabador (ICProg), pero si se requiere la depuracion a emplear el chero *.cof. Con esto estaremos preparados para depurar nuestras aplicaciones escritas en C con Proteustm .

el chero *.cod se ver Si se emplea en la depuracion a a la vez el codigo C y el codigo ensamblador generado.

12.3. MPLAB
12.3.1. Introduccion
MPLAB v8.10 (26 de agosto de 2008) es la herramienta que proporciona de manera gratuita el fabricante de los microcontroladores que estudiamos y se puede descargar en el CDROM. de su p agina web 5 . Se adjunta la ultima version
5

http://www.microchip.com

Cap tulo 12. Software: Proteustm

187

Esta herramienta permite ensamblar y compilar nuestros programas as como depurar su funcionamiento. Permite el uso de compiladores de otros fabricantes e incluso con el software que vamos a utilizar: Proteustm . permite una integracion

188

MPLAB

Cap tulo 13 Motores Paso a Paso


Hasta la m as larga caminata empieza por un simple paso Confucio

13.1. Introduccion
Existen distintos tipos de motores paso a paso1 , entre otros los hay de reluctancia variable, de im an permanente, unipolares, bipolares, multifase, etc. En esta pr actica vamos a analizar los motores paso a paso unipolares. En la sigu de las iente gura se puede ver el montaje t pico que distingue la parte de generacion senales necesarias, la etapa de potencia y el motor paso a paso:

en el punto central El caso m as sencillo consta de dos bobinados con una conexion de cada uno de los bobinados (puntos a y b de la gura). Estos puntos suelen ir conec nominal del motor). El control del motor se realizar tados a VM OT OR (tension a con los cuatro terminales restantes 1a, 1b, 2a y 2b.
1 Una buena referencia bibliogr aca en red acerca de los motores paso a paso y su control se puede encontrar, en ingl es, en http://www.cs.uiowa.edu/ jones/step/. La p agina pertenece a Douglas W. Jones, THE UNIVERSITY OF IOWA Department of Computer Science

189

190

Introducci on

La secuencia de operaciones a realizar para conseguir el giro del motor est a repre se consigue que el motor avance sentada en la gura siguiente. Con cada combinacion 2 un paso . El numero de pasos por vuelta estar a especicado en la hoja de caracter sti cas del motor (depender a del numero de polos del rotor, etc.). Adem as el motor puede ir acompanado de un mecanismo reductor con lo que el numero de pasos por vuelta ser a mayor y el par obtenido tambi en.

de los bobinados requiere corriente suciente para generar el campo La excitacion l. Para conseguir esmagn etico necesario para mover el motor y la carga conectada a e to se precisa de un circuito de potencia para cada bobinado. En la gura se muestra el t pico puente H utilizado para alimentar un bobinado de un motor paso a paso. Las cajas representan amplicadores de corriente o interruptores. Los diodos son necesarios para evitar los picos de corriente producidos por las bobinas cuando los amplicadores conmutan su valor.
2 concreta y la estimulacion de una determinada posicion solo El motor estar a en una posicion xito si esta es la anterior o posterior a la actual. Inicialmente, si solo pretendemos que gire, tendr ae paso hasta que se sincronice la posicion del rotor con la posicion que queremos. perder a algun

Cap tulo 13. Motores Paso a Paso

191

Un circuito t pico que se suele utilizar con los motores paso a paso es el ULN2003 (que son 7 transistores Darlington de alta corriente) o el ULN2803 (con 8 transistores Darlington permite controlar 2 motores paso a paso a la vez), que incorporan los diodos de proteccion.

Un montaje t pico se puede observar en la siguiente gura:

RITMO

R1
AM FM

10k

U1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 MCLR/Vpp/THV RB7/PGD RA0/AN0 RB6/PGC RA1/AN1 RB5 RA2/AN2/VREFRB4 RA3/AN3/VREF+ RB3/PGM RA4/T0CKI RB2 RA5/AN4/SS RB1 VSS RB0/INT OSC1/CLKIN VDD OSC2/CLKOUT VSS RC0/T1OSO/T1CKI RC7/RX/DT RC1/T1OSI/CCP2 RC6/TX/CK RC2/CCP1 RC5/SDO RC3/SCK/SCL RC4/SDI/SDA PIC16F876_ 4MHz 28 27 26 25 24 23 22 21 20 19 18 17 16 15 1 2 3 4 5 6 7 8 9

U2
1B 2B 3B 4B 5B 6B 7B 8B GND ULN2803 1C 2C 3C 4C 5C 6C 7C 8C COM 18 17 16 15 14 13 12 11 10

M1
A1 AC A2 B1 BC B2

SENTIDO

+88.8 MOTOR-PASO_A_PASO

X1

4 MHz

C2
33pF

C1
33pF

192

Se pide

13.2. Se pide
1. Encontrar, en el motor paso a paso unipolar proporcionado, cuales son los terminales del mismo (mide la resistencia entre cada dos terminales). El motor puede tener 5 o 6 terminales. En el caso de tener 5 terminales signica que los terminales a y b son el mismo. Montar el circuito y escribir el programa b asico que sea capaz de hacer girar el motor en sentido horario y antihorario un paso con cada anco de la patilla RA0. del sentido de giro se realizar La seleccion a con la patilla RA3. 2. Poder seleccionar la velocidad de giro del motor. Para ello introduciremos entre del sentido paso y paso un retardo diferente para cada velocidad. La seleccion de giro se realizar a con la patilla RA2 y la velocidad se seleccionar a entre cuatro posibilidades indicadas con RA0 y RA1. Codicar las siguientes velocidades: 00: 50 pasos/segundo 01: 100 pasos/segundo 10: 150 pasos/segundo 11: 200 pasos/segundo necesitamos conocer cuanto vale el numero 3. Para una mejor realimentacion de pasos por segundo. Se pide enviar por el puerto serie al PC el valor de pasos por segundo. Las patillas RC4 y RC5 decrementar an/incrementar an el retardo entre pasos. nominal del motor: usar 5 V. Cuidado con la tension

13.3. Cuestiones
del motor? Cuantos pasos por vuelta tiene? a) Cu al es la resolucion b) Qu e consumo tiene? De qu e depende? c) Cual es la frecuencia m axima de giro del motor sin que pierda pasos? d) Sabr as calcular el par que tiene a cada velocidad y dibujar la curva par-velocidad? e) Recuerdas qu e es el momento de inercia?

13.4. Para nota


1. Existe una t ecnica para conseguir mayor par que consiste en polarizar dos devanados cada vez. Modica el programa para conseguirlo. La gura de la izquier da nos da una pista de como hacerlo.

Cap tulo 13. Motores Paso a Paso

193

2. Existe otra t ecnica llamada half-stepping para conseguir duplicar el numero de pasos por vuelta del motor. Consiste en conseguir posiciones intermedias polarizando alternativamente uno o dos devanados cada vez. La gura de la derecha nos indica la forma de excitar los devanados. Modica el programa y comprueba que se duplica el numero de pasos.

194

Hojas de datos

13.5. Hojas de datos


ULN2803: Eight Darlington Arrays
Order this document by ULN2803/D

Octal High Voltage, High Current Darlington Transistor Arrays


The eight NPN Darlington connected transistors in this family of arrays are ideally suited for interfacing between low logic level digital circuitry (such as TTL, CMOS or PMOS/NMOS) and the higher current/voltage requirements of lamps, relays, printer hammers or other similar loads for a broad range of computer, industrial, and consumer applications. All devices feature opencollector outputs and free wheeling clamp diodes for transient suppression. The ULN2803 is designed to be compatible with standard TTL families while the ULN2804 is optimized for 6 to 15 volt high level CMOS or PMOS.

ULN2803 ULN2804
OCTAL PERIPHERAL DRIVER ARRAYS
SEMICONDUCTOR TECHNICAL DATA

MAXIMUM RATINGS (TA = 25C and rating apply to any one device in the
package, unless otherwise noted.) Rating Output Voltage Input Voltage (Except ULN2801) Collector Current Continuous Base Current Continuous Operating Ambient Temperature Range Storage Temperature Range Junction Temperature
RJA = 55C/W Do not exceed maximum current limit per driver.

Symbol VO VI IC IB TA Tstg TJ

Value 50 30 500 25 0 to +70 55 to +150 125

Unit V V mA mA C C C A SUFFIX PLASTIC PACKAGE CASE 707

PIN CONNECTIONS

18 17 16 15 14 13 12 11 10

ORDERING INFORMATION
Characteristics Input Compatibility TTL, 5.0 V CMOS 6 to 15 V CMOS, PMOS Operating Temperature Range TA = 0 to + 70C

2 3 4 5 6 7 8 Gnd 9

D i Device ULN2803A ULN2804A

VCE(Max)/IC(Max) 50 V/500 mA

Cap tulo 13. Motores Paso a Paso Motor paso a paso: serie P535 El modelo que usaremos es el P535-L48-G17 (1U)

195

Geared Stepper motors


The P5-M35 series provides a combination of optimum size and price for use in instrumentation applications that require digital control of position and speed. Features include: x x x x x x High performance permanent magnet stepper motor Precision Ovoid gearhead incorporating metal gears for optimum torque transmission Wide range of standard gear ratio options from stock Choice of output shaft options Optional integral freewheel and clutch Special shaft and gear ratios to meet customer special requirements

P535 series

Dimensions: mm
2.2 21.5 16.5 Ls 2.8 4
0 - 0.02

47.6

12 Leads 300 12. 3.2 36 Db bearing dia. Db: 10mm ( L0 series) 8mm ( L8 series) 12.7 26.2

R 24.6

1.2
Shaft length Ls: plain 20 mm long ( L. 12.8 mm long with flat ( L. Flat length: 9 mm Additional options: Integral Clutch : L. Integral Freewheel CW version :L 1 option) 2 option ): 2C 2F & CCW version: L. 2R 3.3 4
0 - 0.1

P535-L48 geared stepper motor performance


Geared Stepper Motor P535-L48 -G01.... -G03 -G04 -G05 -G06 -G08 -G09 -G11 -G14 -G16 -G17 -G19 -G21 -G23 -G27 -G34 -G41 Standard Versions: Number of phases Rated voltage ( L/R Drive) Current per phase Resistance per phase Ratio 25:6 25:4 25:3 10:1 25:2 50:3 20:1 25:1 100:3 125:3 50:1 125:2 250:3 125:1 250:1 500:1 1250:1 Steps per rev. at output 200 300 400 480 600 800 960 1,200 1,600 2,000 2,400 3,000 4,000 6,000 12,000 24,000 60,000 P535L48 1U 4 5 450 11 Holding Torque ( Ncm ) 8.1 12.2 16.2 17.6 21.9 29.2 35.1 43.9 58.5 73.1 80 80 80 80 80 85 90 P535L48 2U 4 12 180 64 Max Working Torque ( Ncm ) 5.1 7.7 10.2 11.1 13.8 18.4 22.1 27.6 36.8 46.0 55.3 61.6 80 80 80 85 90 Typical Working Torque ( Ncm ) 3.0 4.5 6.0 6.5 8.1 10.8 13.0 16.3 21.7 27.1 32.5 36.3 48.3 72.5 80 85 90 Step rate @ typical working torque L/R : 200 Hz L/4R: 450 Hz

( mA ) ( Ohms )

Mclennan Servo Supplies Ltd.

Tel: +44 (0)8707 700 700

196

Hojas de datos

Cap tulo 14 Termometro digital

No le evit eis a vuestros hijos las dicultades de la vida, ensenadles mas bien a superarlas Louis PASTEUR

14.1. Introduccion
t Una aplicacion pica de los microcontroladores avanzados es la captura de datos un termometro analogicos. A modo de ejemplo vamos a disenar digital. Necesitamos un display para visualizar la temperatura: el LM1602 (compatible Hi ser tachi 44780) conocido por todos (se adjunta hoja de informacion) a una buena elec Necesitamos un conversor AD, pero el microcontrolador con el que trabajamos cion. dispone de uno integrado con varias entradas multiplexadas. Por ultimo, necesitamos un sensor de temperatura: el LM35D, cuya hoja de datos se adjunta, nos va a permi b tir, en su conguracion asica, un rango de temperaturas entre 2o C y 150o C. V ease la de las patillas en el encapsulado a continuacion: posicion
TO-92 Plastic Package

DS005516-2

Order Number LM35CZ, LM35CAZ or LM35DZ See NS Package Number Z03A

del hardware se muestra en el siguiente esquema una vez consultadas las El diseno hojas de datos: 197

198
LCD1
LM016L

Se pide

VSS VDD VEE

RS RW E 4 5 6

Temperatura Interior
VDD

1 2 3

U1

R2

24.0 2

10k

VOUT

R1 U2
9 10 1 2 3 4 5 6 7 OSC1/CLKIN OSC2/CLKOUT MCLR/Vpp/THV 20 10k RB0/INT RB1 RB2 RB3/PGM RB4 RB5 RB6/PGC RB7/PGD 21 22 23 24 25 26 27 28 11 12 13 14 15 16 17 18 VDD

3 VSS

LM35

X1
Temperatura Exterior
4 MHz

C2
1

C1
33pF

U3

33pF

33.0 2

PIC16F876 8 19

VOUT

LM35

14.2. Se pide
Para resolver el problema propondremos distintos hitos a conseguir: 1. Debemos ser capaces de pintar en el display alfanum erico. Se nos proporciona l. un chero (LCD.h) que incorpora las funciones b asicas para pintar en e El programa base ser a: Listado 14.1: EX/TERMOMETRO/TERMOMETRO0.c
#include <pic.h> #include "LCD.h"
4

// Para el PIC16F87x __CONFIG(WDTDIS & XT & UNPROTECT & PWRTDIS const unsigned char M[]="Hola Mundo";

VSS VSS

RA0/AN0 RA1/AN1 RA2/AN2/VREFRA3/AN3/VREF+ RA4/T0CKI RA5/AN4/SS RC0/T1OSO/T1CKI RC1/T1OSI/CCP2 RC2/CCP1 RC3/SCK/SCL RC4/SDI/SDA RC5/SDO RC6/TX/CK RC7/RX/DT

& LVPDIS );

void main() { unsigned char i=0; LCD_Port(); LCD_Reset(); // Inicia los puertos // Inicia el LCD // Pinta

14

LCD_Comando(LCDCasa); while( M[i]!=0 ) LCD_Caracter( M[i++] ); while(1); // Bucle sin fin


19

7 8 9 10 11 12 13 14

D0 D1 D2 D3 D4 D5 D6 D7

Cap tulo 14. Term ometro digital

199

2. Deberemos congurar el conversor AD y pintar el valor entero que obtengamos, que estar a entre 0 y 65535 (los 10 bits m as signicativos). 3. Convertiremos el dato entero al dato en grados cent grados y lo pintaremos. 4. Opcionalmente podremos visualizar la temperatura en grados Kelvin (K = 273,15+ C ) y grados Farenheit (F = 9 C + 32). 5 5. Convertiremos dos valores de temperatura, a saber, interna y externa, procedentes de dos sensores. 6. Calcularemos la m axima, la m nima, el promedio de cada temperatura.

14.3. Cuestiones
a)Se puede ampliar el rango de temperaturas (temperaturas negativas: rango des hardware? de -55o C a 150o C) con alguna modicacion 1 de la informacion mostrada? b) Se puede aumentar la resolucion c) Porqu e la temperatura mostrada es unas cent esimas de grado superior a la medida con un pol metro directamente en el sensor? d) Por qu e var a constantemente el valor digitalizado? e) Consumo total?
Si se coloca una referencia Vref + para reducir el fondo de escala del conversor AD hay que recordar que el fabricante recomienda que la diferencia entre Vref + y Vref sea superior a 2,0 V.
1

200

Hojas de datos

14.4. Hojas de datos


Sensor de temperatura LM35

LM35 Precision Centigrade Temperature Sensors

August 1999

LM35 Precision Centigrade Temperature Sensors


General Description
The LM35 series are precision integrated-circuit temperature sensors, whose output voltage is linearly proportional to the Celsius (Centigrade) temperature. The LM35 thus has an advantage over linear temperature sensors calibrated in Kelvin, as the user is not required to subtract a large constant voltage from its output to obtain convenient Centigrade scaling. The LM35 does not require any external calibration or trimming to provide typical accuracies of 14C at room temperature and 34C over a full 55 to +150C temperature range. Low cost is assured by trimming and calibration at the wafer level. The LM35s low output impedance, linear output, and precise inherent calibration make interfacing to readout or control circuitry especially easy. It can be used with single power supplies, or with plus and minus supplies. As it draws only 60 A from its supply, it has very low self-heating, less than 0.1C in still air. The LM35 is rated to operate over a 55 to +150C temperature range, while the LM35C is rated for a 40 to +110C range (10 with improved accuracy). The LM35 series is available packaged in hermetic TO-46 transistor packages, while the LM35C, LM35CA, and LM35D are also available in the plastic TO-92 transistor package. The LM35D is also available in an 8-lead surface mount small outline package and a plastic TO-220 package.

Features
n n n n n n n n n n n Calibrated directly in Celsius (Centigrade) Linear + 10.0 mV/C scale factor 0.5C accuracy guaranteeable (at +25C) Rated for full 55 to +150C range Suitable for remote applications Low cost due to wafer-level trimming Operates from 4 to 30 volts Less than 60 A current drain Low self-heating, 0.08C in still air Nonlinearity only 14C typical Low impedance output, 0.1 for 1 mA load

Typical Applications

DS005516-4 DS005516-3

FIGURE 1. Basic Centigrade Temperature Sensor (+2C to +150C)

Choose R1 = VS/50 A V OUT =+1,500 mV at +150C = +250 mV at +25C = 550 mV at 55C

FIGURE 2. Full-Range Centigrade Temperature Sensor

TRI-STATE is a registered trademark of National Semiconductor Corporation.

2000 National Semiconductor Corporation

DS005516

www.national.com

Cap tulo 14. Term ometro digital Display alfanum erico Hitachi 44780
The Concise LCD Data Sheet.
Instruction NOP Clear Display Cursor Home

201

http://www.senet.com.au/~cpeacock
Clocks 0 165 3

RS RW D7 D6 D5 D4 D3 D2 D1 D0 Description 0 0 0 0 0 0 0 0 0 0 No Operation 0 0 0 0 0 0 0 0 0 1 Clears display & sets address counter to zero. 0 0 0 0 0 0 0 0 1 0 Sets address counter to zero, returns shifted display to original position. DDRAM contents remains unchanged. Entry Mode Set 0 0 0 0 0 0 0 1 I/D S Sets cursor move direction, and specifies automatic shift. Display Control 0 0 0 0 0 0 1 D C B Turns display (D), cursor on/off (C) or cursor blinking(B). Cursor/display shift 0 0 0 0 0 1 S/C R/L 0 0 Moves cursor and shift display. DDRAM contents remains unchanged. Function Set 0 0 0 0 1 DL N M G 0 Sets interface data width(DL), number of display lines (N,M) and voltage generator control (G). Set CGRAM Addr 0 0 0 1 Character Generator RAM Sets CGRAM Address Set DDRAM Addr 0 0 1 Display Data RAM Address Sets DDRAM Address Busy Flag & Addr 0 1 BF Address Counter Reads Busy Flag & Address Counter Read Data 1 1 Read Data Reads data from CGRAM or DDRAM Write Data 1 0 Write Data Writes data from CGRAM or DDRAM Write Cycle

3 3 3 3 3 3 0 3 3

RS tas R/W tw Enable tr Data tds


Valid Data

tah

tf th

tc

(2)

Parameter Enable Cycle Time Enable Pulse Width (High) Enable Rise/Fall Time Address Setup Time Address Hold Time Data Setup Time Data Hold Time

Symbol

tc tw tr,tf tas tah tds th

Min (1) 500 230 40 10 80 10

Typ (1) -

Max (1) 20 -

Unit ns ns ns ns ns ns ns
Pin No 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Name Vss Vdd Vo RS R/W E D0 D1 D2 D3 D4 D5 D6 D7 I/O Power Power Analog Input Input Input I/O I/O I/O I/O I/O I/O I/O I/O Description GND +5v Contrast Control Register Select Read/Write Enable (Strobe) Data LSB Data Data Data Data Data Data Data MSB

Note 1 The above specifications are a indication only. Timing will vary from manufacturer to manufacturer.

Note 2 A 2 line by 16 Character LCD Module is Pictured. Data will work on most 1 line x 16 character, 1 line x 20 character, 2 line x 16 character, 2 line x 20 character, 4 lines x 20 character, 2 lines x 40 character etc. modules compatible with the HD44780 LCD Module.

202

Software LCD

14.5. Software LCD


Listado 14.2: EX/TERMOMETRO/LCD.h
1

// Fichero LCD.h // Se debe incluir en el fichero en que se vaya a usar, una sola vez #include <pic.h> #include "binario.h" // Definimos las conexiones #define LCD_Data PORTB /* Puerto de datos */ #define LCD_RS RC0 /* Comando o dato */ #define LCD_RW RC1 /* Lectura/Escritura LCD */ #define LCD_E RC2 /* Habilita LCD */ void LCD_Port() { TRISC = TRISC & 0xF8; TRISB = 0; LCD_E = 0; } // COMANDOS para el LCD HD44780 #define LCDClear B00000001 #define LCDCasa B00000010 #define LCDInc B00000110 /* ** /* /* /* #define LCDDec B00000100 #define LCDOn B00001100 /* *** /* /* /* /* /* #define LCDOff B00001000 #define CursOn B00001110 #define CursOff B00001100 #define CursBlink B00001111 #define LCDIzquierda B00011000 /* **-/* /* /* #define LCDDerecha B00011100 #define CursIzquierda B00010000 #define CursDerecha B00010100 #define LCDFuncion B00111000 /* ***-/* /* /* /* #define LCDCGRAM B01000000 #define LCDLinea1 #define LCDLinea2 B10000000 B11000000

11

// RC0..RC2 salidas // PORTB todo salidas

16

21

26

31

36

41

46

51

/* Borra y cursor al principio */ /* Cursor al principio */ /* Selecciona incrementos */ Bit 1 I/D (=0 dec posici on) */ (=1 inc posici on)* */ Bit 0 S (=0 no despl. disp.)* */ (=1 desplaza disp.) */ /* Sel. decrementos, no despl. */ /* Control del display */ Bit 2 D (=0 display apagado) */ (=1 disp.encendido)* */ Bit 1 C (=0 sin cursor)* */ (=1 con cursor) */ Bit 0 B (=0 sin parpadeo)* */ (=1 con parpadeo) */ /* Disp. off, sin cursor, no parp. */ /* Disp. on, con cursor, no parp. */ /* Disp. on, sin cursor, no parp. */ /* Disp. on, con cursor, con parp. */ /* Desplaz. de cursor o disp. */ Bit 4 S/C (=0) Mueve el cursor */ (=1) Despl. el disp.* */ Bit 3 R/L (=0) A la izquierda* */ (=1) A la derecha */ /* Desplaza a la derecha el disp. */ /* Cursor a la izquierda */ /* Cursor a la derecha */ /* Bit 4 DL (=0 4 bit bus) */ (=1 8 bit bus)* */ Bit 3 N (=0 disp. de 1 linea) */ (=1 disp. de 2 l neas)**/ Bit 2 F (=0 font 5x8)* */ (=1 font 5x10) */ /* Pone direcci on CGRAM */ /* Posici on 0 (00h). L nea 1 /* Posici on 64 (40h). L nea 2 */ */

56

unsigned char LCD_Counter1, LCD_Counter2;

Cap tulo 14. Term ometro digital


// Subrutinas para el manejo del LCD .................
61

203

66

71

void Pausa_5ms() { // Bucle de retardo para el LCD (micro a 4 MHz) #asm CLRF _LCD_Counter1 // Borro el primer contador MOVLW 1Ah MOVWF _LCD_Counter2 // Inicio segundo contador _LCDLoop DECFSZ _LCD_Counter1,F GOTO _LCDLoop DECFSZ _LCD_Counter2,F GOTO _LCDLoop #endasm } void LCD_Chequea() { LCD_RW = 1; // TRISB = 0xFF;// while(1) { LCD_E = 1; // if(!RB7) break;// LCD_E = 0; // } TRISB = 0x00;// LCD_RW = 0; // }

76

Lee Todo entradas Activa LCD Mientras que est e ocupado Desactiva LCD Todo salidas Escribe

81

86

91

96

void LCD_Comando_Inicio(unsigned char c) { LCD_RW = 0; // Escribe LCD_RS = 0; // Comando LCD_Data = c; // Pone comando // Durante el arranque no podemos leer el estado LCD_E = 1; // Habilita LCD LCD_E = 0; // Deshabilita LCD } void LCD_Comando(unsigned char c) { LCD_RW = 0; // Escribe LCD_RS = 0; // Comando LCD_Data = c; // Pone comando LCD_Chequea(); // Comprueba si no est a ocupado LCD_E = 1; // Habilita LCD LCD_E = 0; // Deshabilita LCD } void LCD_Caracter(unsigned char c) { LCD_RW = 0; // Escribe LCD_RS = 0; // Comando LCD_Chequea(); // Comprueba si no est a ocupado LCD_Data = c; // Pone el dato LCD_RS = 1; // Dato LCD_E = 1; // Habilita LCD LCD_E = 0; // Deshabilita LCD }

101

106

111

116

204
121

Software LCD

126

void LCD_Reset() { LCD_Comando_Inicio(LCDFuncion); Pausa_5ms(); LCD_Comando_Inicio(LCDFuncion); Pausa_5ms(); LCD_Comando_Inicio(LCDFuncion); Pausa_5ms(); LCD_Comando_Inicio(LCDFuncion); Pausa_5ms(); LCD_Comando(LCDClear ); LCD_Comando(LCDInc ); LCD_Comando(CursOff); }

// Define modo de operaci on // // // // Borra pantalla // Autoincremento posici on // Cursor apagado

131

Cap tulo 15 Generacion de audio


En la vida hay algo peor que el fracaso: el no haber intentado nada. Franklin D. Roosvelt

15.1. Introduccion
cuadrada de una determinada freEn esta pr actica queremos generar una senal cuencia y escucharla a trav es de un altavoz. de una frecuencia dada. Se escuchar (cuadrada) Se pide generar una senal a la senal generada a trav es de un altavoz (se deber a limitar la corriente). Las senales variar an entre 0 y 5V con un ciclo de trabajo del 50 %. Estudiar si necesita amplicacion. a generar los tonos de la 4 octava musical (ver tabla). Como ejemplo de aplicacion Para simplicar, no reproducir las notas sostenido (#). Hacemos notar que no repro ducimos tonos puros (onda cuadrada), por lo que se escuchar an armonicos de otras frecuencias. Frecuencias (en hertzios) de las notas musicales:
Oct.0 Do Do# Re Re# Mi Fa Fa# Sol Sol# La La# Si Oct.1 32,70 34,65 36,71 38,89 41,20 43,65 46,25 49,00 51,91 55,00 58,27 61,74 Oct.2 65,41 69,30 73,42 77,78 82,41 87,31 92,50 98,00 103,83 110,00 116,54 123,47 Oct.3 130,81 138,59 146,83 155,56 164,81 174,61 185,00 196,00 207,65 220,00 233,08 246,94 Oct.4 261,63 277,18 293,66 311,13 329,63 349,23 369,99 392,00 415,30 440,00 466,16 493,88 Oct.5 523,25 554,37 587,33 622,25 659,26 698,46 739,99 783,99 830,61 880,00 932,33 987,77 Oct.6 1046,50 1108,73 1174,66 1244,51 1318,51 1396,91 1479,98 1567,98 1661,22 1760,00 1864,66 1975,53 Oct.7 2093,00 2217,46 2349,32 2489,02 2637,02 2793,83 2959,96 3135,96 3322,44 3520,00 3729,31 3951,07 Oct.8 4186,01

27,50 29,14 30,87

15.2. Se pide
Una primera forma con la frecuencia Una forma de generar el sonido consiste en reproducir la senal dada manteniendo durante el primer semi-periodo la patilla de salida en alta y durante el segundo semi-periodo en baja. Para generar toda la escala hemos de ser capaces de 205

206

Se pide

temporizar los semi-periodos correspondientes a cada frecuencia lo m as precisamente posible. Nos podemos ayudar de una tabla que contenga los retardos para cada nota. El problema estar a en que necesitaremos retardos de 16 bits. Una segunda t ecnica Una segunda manera mucho m as interesante consiste en aplicar la t ecnica DDS (Direct Digital Synthesis) que consiste en generar de forma digital la forma de onda re (fR ) tiene que ser m querida para cada frecuencia. La frecuencia de reproduccion as del doble de la m axima frecuencia a reproducir (criterio de Nyquist). Existir a un acumulador de 16 bits que ser a la fase de la forma de onda sinusoidal a generar. Para generar igual una frecuencia (f ) u otra debo sumarle un desfase en cada punto de reproduccion 16 a 2 f /fR .

Despu es se accede a una tabla de senos en ROM y se saca por el conversor AD. B asicamente se trata de recorrer la tabla del seno m as o menos r apido, dependiendo de la frecuencia de la nota. En nuestro caso y dado que el conversor AD del que el b disponemos es de 1 bit (salida digital) haremos la siguiente aproximacion: t m as signicativo del acumulador es el dato que queremos sacar. Generar una melod a Tomar como ejemplo los primeros compases del himno de la alegr a mostrados a continuacion:

Si4,4, La4,2, Do5,2, La4,4, Si4,1, Do5,2, Si4,2,

Do5,2, Si4,2, Si4,2, Si4,2, Do5,1, Re5,2, La4,3,

Re5,2, Re5,2, Do5,2, Si4,2, La4,2, Sol4,2, Sol4,2, Si4,4, La4,4, Si4,2, Si4,2, Do5,2, Re5,2, Re5,2, La4,2, Sol4,2, Sol4,2, La4,2, Si4,2, La4,4, Sol4,4, Sol4,2, La4,2, Si4,1, Do5,1, Si4,2, Sol4,2, La4,2, Si4,2, La4,2, Sol4,2, La4,2, Mi4,2, Si4,4, Si4,2, Re5,2, Do5,2, Si4,2, La4,2, Sol4,2, Sol4,2, La4,2, Sol4,1, Sol4,4

1 El formato de los datos mostrados es (NotaOctava, Duracion), donde la duracion equivale aproximadamente a 0,25 segundos (depender a del tempo).

Cap tulo 15. Generaci on de audio Propuesta

207

est Guardar los datos en la EEPROM interna. Una primera aproximacion a en que doble, se duplica). todas las notas duren lo mismo (si hay alguna de duracion

15.3. Cuestiones
a) El consumo del circuito depende de la nota que se interprete?Por qu e? cuadrada para que sonaran tonos m b)Como reducir as los armonicos de la senal as puros?

208

Cuestiones

Cap tulo 16 Motores de corriente continua


Es mas f acil variar el curso del un rio que el car acter de un hombre Proverbio chino

16.1. Introduccion
El esquema de funcionamiento de los motores de corriente continua se puede observar en la gura siguiente

Cuando una corriente el ectrica pasa a trav es de un hilo conductor dentro de un campo magn etico se generan unas fuerzas magn eticas que producen un par de fuerzas que hace mover el motor. Si cambia el sentido de la corriente, cambiar a el sentido de giro del motor. entre la corriente que pasa por el devanado y la fuerza generada. Existe una relacion de alimentacion mayor ser Adem as se da el hecho de que a mayor tension a la velocidad cr de giro del motor. Existir a una tension tica a partir de la cual el motor comenzar aa nominal (y m girar y una tension axima) de funcionamiento con par m aximo. En la siguiente gura se ve un desglose t pico de un motor de continua. 209

210

Introducci on

Etapa de potencia de un motor de continua es la que La etapa de potencia t pica para la alimentacion utilizando el integrado L293 cuya primera hoja de datos se describe a continuacion se adjunta. Se trata de un puente H que nos permitir a cambiar el sentido de giro del motor. Los diodos que aparecen son necesarios para evitar los picos de corriente generados por el motor, si se trabaja con el integrado L293B (el L293D lleva integrados estos diodos). Se puede emplear el diodo 1N4004 en nuestro caso.
VCC2 2 SES5001

M 2 SES5001 2A 7 8 1/2 L293 4, 5, 12, 13 GND 1 EN 6 3 2 16 VCC1 1A EN H H H H L 1A L H L H X 2A H L L H X Turn left Fast motor stop Fast motor stop Fast motor stop FUNCTION Turn right

L = low, H = high, X = dont care

Esquema hardware de un motor de corriente continua se muestra a Un esquema t pico de conexion 1 : continuacion
La diferencia entre el L293 y el L298 est a en que este ultimo tiene la posibilidad de medir la corriente que pasa por los devanados en las l neas SENSA y SENSB.
1

Cap tulo 16. Motores de corriente continua

211

12V

R1
10k

SENTIDO GIRO 1 + VELOCIDAD 0 0 - VELOCIDAD


0 PARADA
C1
33pF

1N4004

U3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 MCLR/Vpp/THV RB7/PGD RA0/AN0 RB6/PGC RA1/AN1 RB5 RA2/AN2/VREFRB4 RA3/AN3/VREF+ RB3/PGM RA4/T0CKI RB2 RA5/AN4/SS RB1 VSS RB0/INT OSC1/CLKIN VDD OSC2/CLKOUT VSS RC0/T1OSO/T1CKI RC7/RX/DT RC1/T1OSI/CCP2 RC6/TX/CK RC2/CCP1 RC5/SDO RC3/SCK/SCL RC4/SDI/SDA PIC16F876_ 28 27 26 25 24 23 22 21 20 19 18 17 16 15 9 5 7 10 12 6 11 1 15 IN1 IN2 IN3 IN4 ENA ENB VCC 4 VS OUT1 OUT2 OUT3 OUT4 GND 8

D1 U4
2 3 +88.8 13 14 1N4004

D2

+88.8
AC Volts

X1

4 MHz

SENSA SENSB L298

D4
1N4004

D3
1N4004

OSCILOSCOPIO C2
33pF A

RXD TXD RTS CTS

16.2. Se pide
del software para controlar no solo el puente H que haga girar el motor 1. El diseno en los dos sentidos sino tambi en las rutinas necesarias para controlar la velocidad de la anchura de los pulsos (PWM). del motor empleando la modulacion PWM conseguimos variar la velocidad del motor como si Con la modulacion efectiva aplicada fuera menor, pero con la ventaja de que la tension la tension cuando la velocidad aplicada es la nominal lo que nos da el par m aximo aun de giro sea menor. Adem as nos permitir a hacer girar el motor a una velocidad umbral de arranque del motor. inferior a la lograda con la tension PWM Se usar a el modulo CCP del microcontrolador. La frecuencia de la senal ser a de 1 kHz. Se emplear a una entrada (RA0) para seleccionar el sentido de giro del motor. La patilla RA3 ser a el freno del motor, de forma que cuando se active el motor se frene r apidamente. La patilla RA1 incrementar a en una unidad el ciclo de trabajo, mientras que RA2 lo decrementar a en una unidad. Inicialmente el ciclo de trabajo estar a en el 50 %. 2. Realimentar con el PC a trav es del puerto serie para indicar el ciclo de trabajo de PWM generada. la senal

16.3. Cuestiones
del ciclo de trabajo para el que sigue girando el a) Cu al es el valor m as pequeno umbral de arranque del motor? motor? Se ha mejorado la tension

212

Hojas de datos

PWM? Qu b) Se escucha la frecuencia de la senal e ocurrir a si la frecuencia de la PWM fuese mucho mayor? Compru senal ebalo.

16.4. Hojas de datos


Motor de corriente continua Nuestro motor es el 82 861 010.

Cap tulo 16. Motores de corriente continua


D.C. geared motors

213

D.C. geared motors : 0.3 to 430 rpm Gearbox torque ratings from : 0.5 to 2 Nm, high-performance plastic gears s Motors : max. usable power 1 to 3.9 W interference suppression on standard products
s s

Types Applications Nominal voltage


- Blood analysers - Machines for making spectacle lenses - Microvalves for heating systems - Change-giving systems - Packaging machines - Moving light displays - Etc.
12 V 24 V 82 861 015 82 861 016
q

82 861 0

82 861 0

82 841 0 12 V
q q q q q q q q q

82 841 0 24 V
q q q q q q q q q

Output speeds (rpm)


430 215 179 143 108 90 54 49 29 27 22 13 11 8.6 7.2 5.8 5.4 3.6 2.9 1.8 0.90 0.80 0.36

Ratios (i)

Part numbers
82 861 006 82 861 007
q

1
Made to order products, available on request
Motors : - other supply voltages - motors with 2 ball bearings - shaft lengths at front and/or rear - connection by radial tags or leads - specific interference suppression - encoder : 5 or 12 pulses per revolution

10 20 24 30 40 48 80 90 150 160 200 320 375 500 600 750 800 1200 1500 2400 4800 5400 12000

82 861 008 82 861 009


q

82 861 017 82 861 018


q

82 861 010
q q

82 861 019
q q

82 861 011 82 861 012 82 861 013 q

82 861 020 82 861 021 82 861 022 q

q q

q q

82 861 014 q

82 861 023 q

q q

q q

q q

q q

Standard gearbox shaft : see dimensions General characteristics


Motor Gearbox Maximum permitted torque on gearbox for continuous rating (for 1 million revolutions) Axial load (static) Radial load (static) Maximum usable power Maximum usable power Gearbox case temperature rise Weight Output shaft 4 mm 82 860 0 81 021 0 Nm daN daN W W C g 0.5 1 8 3.9 3 50 160
q q q

82 860 0 81 021 0 0.5 1 8 3.9 3 50 160


q q q

82 840 0 81 021 0 0.5 1 8 1 0.9 50 130


q q q

82 840 0 81 021 0 0.5 1 8 1 0.9 50 130


q q q

Options : for standard products non stocked


79 200 967 79 200 779 70 999 421 79 202 573 With magnetic encoder 1 pulse per revolution 6 mm Nominal speed and torque curves The shaded zone represents the operating range of the geared motor. The horizontal line marks the maximum torque available in continuous duty cycle for a given life. For higher torque ratings, service life will be reduced.
3000 1000 500 300 100 30
rpm

Gearboxes : - special shaft - ball bearings - special lubrication - friction clutch - M3 gearbox fixings - other speeds

82 861 5
mN.m

82 861 5
5000 2000 1000 500 200 100 50 20 1 2

mN.m

10

1 23

10 2030 100 200300

rpm
5 10 20 50 100 200 500

Other information
Basic principles : see page 1/7. Motor 82 840 0, 82 860 0 : see page 1/9.

1/22

214 Puente H: L293

Hojas de datos

L293 QUADRUPLE HALF-H DRIVER


SLRS005 SEPTEMBER 1986 REVISED MAY 1990

1-A Output Current Capability Per Driver Pulsed Current 2-A Driver Wide Supply Voltage Range: 4.5 V to 36 V Separate Input-Logic Supply NE Package Designed for Heat Sinking Thermal Shutdown Internal ESD Protection High-Noise-Immunity Inputs Functional Replacement for SGS L293

NE PACKAGE (TOP VIEW)

1, 2EN 1A 1Y HEAT SINK AND GROUND 2Y 2A VCC2

1 2 3 4 5 6 7 8

16 15 14 13 12 11 10 9

VCC1 4A 4Y HEAT SINK AND GROUND 3Y 3A 3, 4EN

description
The L293 is a quadruple high-current half-H driver designed to provide bidirectional drive currents of up to 1 A at voltages from 4.5 V to 36 V. It is designed to drive inductive loads such as relays, solenoids, dc and bipolar stepping motors, as well as other high-current/high-voltage loads in positive-supply applications. All inputs are TTL compatible. Each output is a complete totem-pole drive circuit with a Darlington transistor sink and a pseudo-Darlington source. Drivers are enabled in pairs with drivers 1 and 2 enabled by 1, 2EN and drivers 3 and 4 enabled by 3, 4EN. When an enable input is high, the associated drivers are enabled and their outputs are active and in phase with their inputs. When the enable input is low, those drivers are disabled and their outputs are off and in a high-impedance state. With the proper data inputs, each pair of drivers form a full-H (or bridge) reversible drive suitable for solenoid or motor applications. External high-speed output clamp diodes should be used for inductive transient suppression. A VCC1 terminal, separate from VCC2, is provided for the logic inputs to minimize device power dissipation. The L293 is designed for operation from 0C to 70C.

logic symbol
1A 1, 2EN 2A 3A 3, 4EN 4A 2 1 7 10 9 15 EN EN 14 4Y EN EN 6 2Y 3

1Y

11

3Y

This symbol is in accordance with ANSI/IEEE Std 91-1984 and IEC publication 617-12.

logic diagram
1A 1, 2EN 2A 2 1 7 6 2Y 3 1Y

3A 3, 4EN 4A

10 9 15

11

3Y

14

4Y

FUNCTION TABLE (each driver) INPUTS OUTPUT A H L X EN H H L Y H L Z

H = high-level, L = low-level, X = irrelevant, Z = high-impedance (off) In the thermal shutdown mode, the output is in the high-impedance state regardless of the input levels.

PRODUCTION DATA information is current as of publication date. Products conform to specifications per the terms of Texas Instruments standard warranty. Production processing does not necessarily include testing of all parameters.
POST OFFICE BOX 655303

Copyright 1990, Texas Instruments Incorporated

DALLAS, TEXAS 75265

31

Cap tulo 17 Frecuenc metro/tacometro


La sabidur a nos llega cuando ya no nos sirve de nada Gabriel Garc a M arquez

17.1. Introduccion
y montaje de un frecuenc Se nos pide el diseno metro/tacometro para medir la velocidad de giro de un motor. hardware pasa por incorporar a nuestro microcontrolador adem El diseno as de un display alfanum erico LM1602 para visualizar los resultados, un sensor infrarrojo HA21A como se aprecia en la gura, de forma que el encoder ligado al motor (se pro infrarroja hacia el porcionar a un motor DC) interrumpa con cada diente la transmision fototransistor indic andonos un paso (ver gura inferior)

El sensor deber a ir conectado en la forma indicada en la hoja de datos del sensor HA21A. Un montaje t pico del display, etc. aparece en la gura siguiente

215

216
LCD1
LM016L

Se pide

RV1

VSS VDD VEE

RS RW E 4 5 6

10k 1 2 3 7 8 9 10 11 12 13 14

D0 D1 D2 D3 D4 D5 D6 D7

R1
10k 9 10 1 2 3 4 5 6 7

U2
OSC1/CLKIN OSC2/CLKOUT MCLR/Vpp/THV

20

X1

4 MHz

C2
33pF

C1
33pF

PIC16F876 8 19

VSS VSS

RA0/AN0 RA1/AN1 RA2/AN2/VREFRA3/AN3/VREF+ RA4/T0CKI RA5/AN4/SS RC0/T1OSO/T1CKI RC1/T1OSI/CCP2 RC2/CCP1 RC3/SCK/SCL RC4/SDI/SDA RC5/SDO RC6/TX/CK RC7/RX/DT

RB0/INT RB1 RB2 RB3/PGM RB4 RB5 RB6/PGC RB7/PGD

21 22 23 24 25 26 27 28 11 12 13 14 15 16 17 18

VDD

SEAL

500 Hz

U1
1 + D+ 3

U3:A
4 1 40106 2 SEAL

E HA21A

R2
220

R3
47k

1 - Recibe Luz 0 - No recibe luz

17.2. Se pide
software se pide la cuenta de los eventos utilizando el TMR1 y la En el diseno cuenta del tiempo usando TMR0 y las interrupciones. Se deber a actualizar la salida por el display cada segundo, indicando el numero de pulsos por segundo y el numero de revoluciones por minuto. Inicialmente se pueden medir los pulsos generados por un pulsador o por el gen presente en el entrenador. Solo es necesario tener en cuenta que la erador de senal de salida del mismo sea de 5 voltios y que la frecuencia a medir sea pequena. tension Posteriormente se puede usar el motor de corriente continua al que se le habr a coloca do el encoder y montarlo junto con el tacometro. El control de velocidad del motor DC continua inferior a 12 voltios se puede hacer alimentando el mismo con una tension dar (menor tension a menor velocidad). Coloca un LED que indique mediante un destello cuando la medida es correcta (una vez cada segundo).

Cap tulo 17. Frecuenc metro/tac ometro Dibujo del encoder utilizado en el motor de continua

217

17.3. Cuestiones
hardware del inversor Schmidt Trigger 40106?Por a) Se puede prescindir en el diseno qu e? b) Cual es la frecuencia m axima de respuesta del frecuenc metro? Por qu e? del tacometro? c) Como mejorar as la resolucion Y la frecuencia m axima?

218

Hojas de datos

17.4. Hojas de datos


Fototransistor HA21A
PACKAGE DIMENSIONS
0.972 (24.7) 0.957 (24.3) 0.472 (12.0) 0.457 (11.6) C L 0.249 (6.35) 0.243 (6.15)
+ E D +

DESCRIPTION
The H21A1, H21A2 and H21A3 consist of a gallium arsenide infrared emitting diode coupled with a silicon phototransistor in a plastic housing. The packaging system is designed to optimize the mechanical resolution, coupling efficiency, ambient light

0.133 (3.4) 0.126 (3.2) (2X)

C L 0.39 (1.00) 0.34 (0.85)

0.755 (19.2) 0.745 (18.9)

.073 (1.85) .133 (3.38)

0.129 (3.3) 0.119 (3.0) Optical C L

rejection, cost and reliability. The gap in the housing provides a means of interrupting the signal with an opaque material, switching the output from an ON to an OFF state.

0.433 (11.0) 0.422 (10.7)

SCHEMATIC
1 4

0.125 (3.2) 0.119 (3.0) C L .295 (7.5) .272 (6.9)

0.315 (8.0)

FEATURES
0.110 (2.8) 0.091 (2.3)

Opaque housing Low cost .035 apertures High IC(ON) 1. Derate power dissipation linearly 1.33 mW/C above 25C. 2. RMA flux is recommended. 3. Methanol or isopropyl alcohols are recommended as cleaning agents. 4. Soldering iron tip 1/16 (1.6mm) minimum from housing.
2 3

2 1

3 4

PIN 1 ANODE PIN 2 CATHODE PIN 3 COLLECTOR PIN 4 EMITTER


0.020 (0.51) (SQ)

NOTES: 1. Dimensions for all drawings are in inches (mm). 2. Tolerance of .010 (.25) on all non-nominal dimensions unless otherwise specified.

ABSOLUTE MAXIMUM RATINGS


Parameter Operating Temperature Storage Temperature Soldering Temperature (Iron)(2,3 and 4) Soldering Temperature (Flow)(2 and 3) INPUT (EMITTER) Continuous Forward Current Reverse Voltage Power Dissipation (1) OUTPUT (SENSOR) Collector to Emitter Voltage Emitter to Collector Voltage Collector Current Power Dissipation (TC = 25C)(1)

(TA = 25C unless otherwise specified) Symbol TOPR TSTG TSOL-I TSOL-F IF VR PD VCEO VECO IC PD Rating -55 to +100 -55 to +100 240 for 5 sec 260 for 10 sec 50 6 100 30 4.5 20 150 Unit C C C C mA V mW V V mA mW

Cap tulo 17. Frecuenc metro/tac ometro Inversor Schmidt Trigger 40106

219

CD40106BM CD40106BC Hex Schmitt Trigger

February 1988

CD40106BM CD40106BC Hex Schmitt Trigger


General Description
The CD40106B Hex Schmitt Trigger is a monolithic complementary MOS (CMOS) integrated circuit constructed with N and P-channel enhancement transistors The positive and negative-going threshold voltages VT a and VTb show low variation with respect to temperature (typ 0 0005V C at VDD e 10V) and hysteresis VT a b VTb t 0 2 VDD is guaranteed All inputs are protected from damage due to static discharge by diode clamps to VDD and VSS

Features
Y Y Y

Wide supply voltage range High noise immunity Low power TTL compatibility Hysteresis

Y Y

3V to 15V 0 7 VDD (typ ) Fan out of 2 driving 74L or 1 driving 74LS 0 4 VDD (typ ) 0 2 VDD guaranteed Equivalent to MM54C14 MM74C14 Equivalent to MC14584B

Connection Diagram
Dual-In-Line Package

Switching Time Waveforms

TL F 5985 3

tr e tf e 20 ns

Order Number CD40106B

TL F 59852

Top View

Schematic Diagram

TL F 5985 1

C1995 National Semiconductor Corporation

TL F 5985

RRD-B30M105 Printed in U S A

220

Hojas de datos

Cap tulo 18 Robot Rastreador


La diferencia entre una democracia y una dictadura consiste en que en la democracia puedes votar antes de obedecer las ordenes. C. Bukowski
SENSOR 1 SENSOR 2

111 000 000 111 000 111 000 111 000 111 000 111 000 111 000 111 000 111 000 111

MOTOR 1

111 000 000 111 000 111 000 111 000 111 000 MOTOR 2111 000 111 000 111 000 111 000 111

RUEDA LOCA

18.1. Introduccion
se muestra el esquema de un robot rastreador. Dispone de dos A continuacion ruedas para determinar el sentido de avance (adelante, atr as, derecha e izquierda) y una rueda loca que da estabilidad al conjunto. la placa de control sabiendo que se dispone de una bater Se pide disenar a de 12 y que V incorporada en el robot movil y que los sensores son infrarrojos de reexion servir an para detectar el color blanco o negro. Adem as tenemos los terminales de los dos motores de continua que dar an movimiento al rastreador. Un ejemplo de esquema hardware se muestra en la siguiente gura:

221

222

Introducci on

VEHCULO RASTREADOR
MOTOR IZQUIERDO
D1
1N4004

MOTOR DERECHO
D8
1N4004

D2
1N4004

D5
1N4004

X1 R5
10k

D3
4 MHz 1N4004

+88.8

D4
1N4004

D9
1N4004

+88.8

D6
1N4004

32 11

U7
13 14 1 2 3 4 5 6 7 8 9 10 OSC1/CLKIN OSC2/CLKOUT MCLR/Vpp/THV

U2
RB0/INT RB1 RB2 RB3/PGM RB4 RB5 RB6/PGC RB7/PGD 33 34 35 36 37 38 39 40 15 16 17 18 23 24 25 26 19 20 21 22 27 28 29 30 1 2 3 4 5 6 7 8 ENABLE1 VDD IN1 IN4 OUT1 OUT4 GND GND GND GND OUT2 OUT3 IN2 IN3 VMOTOR ENABLE2 L293 16 15 14 13 12 11 10 9

VDD VDD

U4
7805 1 VI GND VO 3

RA0/AN0 RA1/AN1 RA2/AN2/VREFRA3/AN3/VREF+ RA4/T0CKI RA5/AN4/SS RC0/T1OSO/T1CKI RC1/T1OSI/CCP2 RE0/AN5/RD RC2/CCP1 RE1/AN6/WR RC3/SCK/SCL RE2/AN7/CS RC4/SDI/SDA RC5/SDO RC6/TX/CK RC7/RX/DT RD0/PSP0 RD1/PSP1 RD2/PSP2 RD3/PSP3 RD4/PSP4 RD5/PSP5 RD6/PSP6 RD7/PSP7

BAT1
12V

C1
100uF

U3
1 4 3 CYN70

R1
220

VSS VSS

R3
47k

SENSOR IZQUIERDO

31 12

PIC16F877

U5
1 4 3 CYN70

0 ARRANQUE

R2
220

R4
47k

SENSOR DERECHO

Obs ervese el montaje de los sensores CYN70 y del puente H creado para cada uno 1N4007 o de los motores de continua. Notese que el uso de los diodos de proteccion 1N4004 es imprescindible si se utiliza el integrado L293B. El L293D los lleva integrados. L7805 es necesario para obtener los 5V con los El uso del regulador de tension de 12V puede alimentar direcque alimentamos el microcontrolador, etc. La tension tamente a los motores de continua a trav es de sus respectivos puentes H. El diagrama se muestran a de conexiones del regulador L7805 y su primera hoja de informacion continuacion

Cap tulo 18. Robot Rastreador

223

18.2. Se pide
Para conseguir hacer moverse al robot necesitamos conocer el sentido de giro de ambos motores para conseguir el movimiento deseado: ACCION Avanzar Retroceder Giro derecha Giro izquierda Parada Sentido Motor 1 Sentido Motor 2 Horario Antihorario Antihorario Horario Antihorario Antihorario Horario Horario Habilitaciones Activas Activas Activas Activas Desactivadas

El problema del robot rastreador consiste en que sea capaz de avanzar siguiendo una l nea negra sobre fondo blanco (o blanca sobre fondo negro) y que adem as lo haga lo m as r apido posible. Para ello disponemos de dos sensores situados estrat egicamente de ambas ruedas. El algoritmo a seguir, por tanto, deber en la l nea de separacion a hacer que ambos sensores dieran el valor de lectura coincidente con el color de la l nea. El sensor dar a un 1 logico si la l nea es negra y 0 si es blanca.

La estrategia: Actual Anterior  XX XX XX ACCIN Avanza Gira izquierda Gira derecha  Avanza   Retrocede   Gira izquierda   Gira derecha

Avanza

Retrocede

Giro derecha
Se pide el software de acuerdo con la estrategia indiMontar el circuito necesario y disenar cada.

18.3. Cuestiones
a) Funciona igual el algoritmo si el motor se alimenta a 5V o a 12V? Por qu e? b) Como podr as mejorar la abilidad del algoritmo? Software? Sensores?

224

Hojas de datos

18.4. Hojas de datos


Regulador 7805

www.fairchildsemi.com

MC78XX/LM78XX
3-terminal 1A positive voltage regulator

Features
Output Current up to 1A Output Voltages of 5, 6, 8, 9, 10, 11, 12, 15, 18, 24V Thermal Overload Protection Short Circuit Protection Output Transistor Safe Operating area Protection

Description
The MC78XX/LM78XX series of three-terminal positive regulators are available in the TO-220/D-PAK package and with several fixed output voltages, making them useful in a wide range of applications. Each type employs internal current limiting, thermal shut-down and safe operating area protection, making it essentially indestructible. If adequate heat sinking is provided, they can deliver over 1A output current. Although designed primarily as fixed voltage regulators, these devices can be used with external components to obtain adjustable voltages and currents.

TO-220

1 D-PAK

1 1. Input 2. GND 3. Output

Internal Block Digram

Rev. 5.0
2000 Fairchild Semiconductor International

Cap tulo 18. Robot Rastreador Sensor de infrarrojos CNY70

225

CNY70
Reflective Optosensor with Transistor Output
Description
The CNY70 has a compact construction where the emitting light source and the detector are arranged in the same direction to sense the presence of an object by using the reflective IR beam from the object. The operating wavelength is 950 nm. The detector consists of a phototransistor.

94 9320

Applications
D Opto-electronic scanning and switching devices i.e.,
index sensing, coded disk scanning etc. (optoelectronic encoder assemblies for transmission sensing).

Features
D Compact construction in center-to-center
spacing of 0.1

D No setting required

D High signal output D Low temperature coefficient D Detector provided with optical filter

Pin Connection

White Dot for Collector

95 10930

Top view

TELEFUNKEN Semiconductors Rev. A2, 12-Dec-97

1 (7)

226 Driver semi-puente H L293

Hojas de datos

L293 QUADRUPLE HALF-H DRIVER


SLRS005 SEPTEMBER 1986 REVISED MAY 1990

1-A Output Current Capability Per Driver Pulsed Current 2-A Driver Wide Supply Voltage Range: 4.5 V to 36 V Separate Input-Logic Supply NE Package Designed for Heat Sinking Thermal Shutdown Internal ESD Protection High-Noise-Immunity Inputs Functional Replacement for SGS L293

NE PACKAGE (TOP VIEW)

1, 2EN 1A 1Y HEAT SINK AND GROUND 2Y 2A VCC2

1 2 3 4 5 6 7 8

16 15 14 13 12 11 10 9

VCC1 4A 4Y HEAT SINK AND GROUND 3Y 3A 3, 4EN

description
The L293 is a quadruple high-current half-H driver designed to provide bidirectional drive currents of up to 1 A at voltages from 4.5 V to 36 V. It is designed to drive inductive loads such as relays, solenoids, dc and bipolar stepping motors, as well as other high-current/high-voltage loads in positive-supply applications. All inputs are TTL compatible. Each output is a complete totem-pole drive circuit with a Darlington transistor sink and a pseudo-Darlington source. Drivers are enabled in pairs with drivers 1 and 2 enabled by 1, 2EN and drivers 3 and 4 enabled by 3, 4EN. When an enable input is high, the associated drivers are enabled and their outputs are active and in phase with their inputs. When the enable input is low, those drivers are disabled and their outputs are off and in a high-impedance state. With the proper data inputs, each pair of drivers form a full-H (or bridge) reversible drive suitable for solenoid or motor applications. External high-speed output clamp diodes should be used for inductive transient suppression. A VCC1 terminal, separate from VCC2, is provided for the logic inputs to minimize device power dissipation. The L293 is designed for operation from 0C to 70C.

logic symbol
1A 1, 2EN 2A 3A 3, 4EN 4A 2 1 7 10 9 15 EN EN 14 4Y EN EN 6 2Y 3

1Y

11

3Y

This symbol is in accordance with ANSI/IEEE Std 91-1984 and IEC publication 617-12.

logic diagram
1A 1, 2EN 2A 2 1 7 6 2Y 3 1Y

3A 3, 4EN 4A

10 9 15

11

3Y

14

4Y

FUNCTION TABLE (each driver) INPUTS OUTPUT A H L X EN H H L Y H L Z

H = high-level, L = low-level, X = irrelevant, Z = high-impedance (off) In the thermal shutdown mode, the output is in the high-impedance state regardless of the input levels.

PRODUCTION DATA information is current as of publication date. Products conform to specifications per the terms of Texas Instruments standard warranty. Production processing does not necessarily include testing of all parameters.
POST OFFICE BOX 655303

Copyright 1990, Texas Instruments Incorporated

DALLAS, TEXAS 75265

31

Cap tulo 19 Comunicaciones


La ciencia m as util es aquella cuyo fruto es el m as comunicable Leonardo da Vinci

19.1. Introduccion
Se pide utilizar el puerto serie as ncrono del microcontrolador para as poder controlar el robot de la pr actica anterior de forma inal ambrica.

227

228

Se pide

19.2. Se pide
Fase1 En una primera fase se intentar a comunicar el PC con el microcontrolador de forma que el microcontrolador implemente un protocolo tipo ECHO, devolviendo el valor con 8 bits de enviado por el PC. Se utilizar an diferentes velocidades de transmision, tipo de control de ujo. datos, sin paridad y con 1 bit de stop. No se requerir a ningun Desde el PC se puede utilizar el programa hyperterminal. se puede observar el montaje t A continuacion pico para lograr nuestro objetivo utilizando el componente MAX232 que es un conversor de niveles el ectricos entre TTL y los que utiliza el protocolo RS-232. Notar que el conector DB9 requiere su conexion y RxD, de recepcion, a un cable null modem (en el que las l neas TxD, de transmision, est an cruzadas). Si disponemos de un cable alargador, el conector RS232 cambiar a de macho a hembra y solo tendremos que intercambiar las conexiones de las patillas 2 y 3.

X1 R1
10k 4 MHz 13 14 1 2 3 4 5 6 7 8 9 10 32 11

VDD

C3 U1
OSC1/CLKIN OSC2/CLKOUT MCLR/Vpp/THV

C5
RB0/INT RB1 RB2 RB3/PGM RB4 RB5 RB6/PGC RB7/PGD 33 34 35 36 37 38 39 40 15 16 17 18 23 24 25 26 19 20 21 22 27 28 29 30 100nF VSS

C1
0.1uF

0.1uF

VDD VDD

U2
1 2 3 4 5 6 7 8 C1+ VCC V+ GND C1T1OUT C2+ R1IN C2R1OUT VT1IN T2OUT T2IN R2IN R2OUT MAX232 16 15 14 13 12 11 10 9 RxD_Out TxD_In

J1
1 6 2 7 3 8 4 9 5 DB9 HEMBRA

RA0/AN0 RA1/AN1 RA2/AN2/VREFRA3/AN3/VREF+ RA4/T0CKI RA5/AN4/SS RC0/T1OSO/T1CKI RC1/T1OSI/CCP2 RE0/AN5/RD RC2/CCP1 RE1/AN6/WR RC3/SCK/SCL RE2/AN7/CS RC4/SDI/SDA RC5/SDO RC6/TX/CK RC7/RX/DT RD0/PSP0 RD1/PSP1 RD2/PSP2 RD3/PSP3 RD4/PSP4 RD5/PSP5 RD6/PSP6 RD7/PSP7

C2
0.1uF

C4
0.1uF TxD TTL RxD TTL GND

VSS VSS

El mismo montaje del Bootloader sirve

PIC16F877 31 12

Fase 2 En una segunda fase se pide que el PC env e comandos (v a cable) al microcontrolador que ir a montado sobre el microbot de forma que se pueda controlar el movimiento la tabla siguiente. del mismo, segun Tecla A Z O P Q Accion Avanzar Retroceder Izquierda Derecha Parada

en el PC se har La programacion a en MSDOS utilizando el compilador de Borland (bc). Se adjunta el programa empleado terminal.cpp.

Cap tulo 19. Comunicaciones Listado 19.1: EX/ROBOT COMM/TERMINAL.cpp


#include <dos.h> #include <stdio.h> #include <conio.h>
5

229

#define PORT1 0x3F8 // COM1 0x3F8 // COM2 0x2F8 void main() { int c, ch; outportb(PORT1 + 1, 0); outportb(PORT1 + 3, 0x80); outportb(PORT1 + 0, 0x60); // 115.200 // 56.700 // 38.400 // 19.200 // 9.600 // 4.800 // 2.400 // 1.200 outportb(PORT1 + 1, 0x00); outportb(PORT1 + 3, 0x03); outportb(PORT1 + 2, 0x00); outportb(PORT1 + 4, 0x0b); // // // bps bps bps bps bps bps bps BPS // // // // Turn off interrupts PORT1 Set DLAB Set Baud rate Low byte 0x01 0x02 0x03 0x06 0x0C 0x18 0x30 0X60 Set Baud rate High byte Clear DLAB, 8 bits, no parity, 1 stop bit FIFO control Set DTR, RTS, OUT2

10

15

20

25

30

35

40

printf("\nTerminal sencillo. Pulsa ESC para salir\n"); do { c = inportb(PORT1+5); // Character received ? if(c & 1) { ch=inportb(PORT1); if(ch!=0xf0) { printf(" %x ",ch); fflush(stdout); } } if(kbhit()) { while(kbhit()) ch=getch(); switch(ch) { case O: break; case P: break; case A: break; case Z: break; case Q: break; case : break; } }

45

ch = 0xcc; ch = 0x66; ch = 0x33; ch = 0x55; ch = 0x99; ch = 0xA5;

50

55

60

230
else ch = 0xf0; do /*Nothing*/; while((inport(PORT1 + 5) & 32) == 0);
65

Cuestiones

outport(PORT1,ch); // delay(5); } while (ch != 27); }

// Para que siempre transmita algo

Fase 3 En una tercera fase se pide que el mismo programa funcione de forma inal ambrica, usando un modulo emisor por radiofrecuencia (R.F.) funcionando a 433 MHz desde el PC y un modulo receptor para el PIC. Un esquema de montaje es el siguiente:

X1 R1
10k 4 MHz 13 14 1 2 3 4 5 6 7 8 9 10 32 11

C3
0.1uF 33 34 35 36 37 38 39 40 15 16 17 18 23 24 25 26 19 20 21 22 27 28 29 30

U1
OSC1/CLKIN OSC2/CLKOUT MCLR/Vpp/THV

VDD VDD

RA0/AN0 RA1/AN1 RA2/AN2/VREFRA3/AN3/VREF+ RA4/T0CKI RA5/AN4/SS RC0/T1OSO/T1CKI RC1/T1OSI/CCP2 RE0/AN5/RD RC2/CCP1 RE1/AN6/WR RC3/SCK/SCL RE2/AN7/CS RC4/SDI/SDA RC5/SDO RC6/TX/CK RC7/RX/DT RD0/PSP0 RD1/PSP1 RD2/PSP2 RD3/PSP3 RD4/PSP4 RD5/PSP5 RD6/PSP6 RD7/PSP7

RB0/INT RB1 RB2 RB3/PGM RB4 RB5 RB6/PGC RB7/PGD

C1
0.1uF

U2
1 2 3 4 5 6 7 8 C1+ VCC V+ GND C1T1OUT C2+ R1IN C2R1OUT VT1IN T2OUT T2IN R2IN R2OUT MAX232 16 15 14 13 12 11 10 9 RxD_Out TxD_In

J1
1 6 2 7 3 8 4 9 5 DB9 HEMBRA

C2
0.1uF

C4
0.1uF GND

VSS VSS

U4
RECEPTOR 433 MHZ RxD TTL

TxD TTL

U3
EMISOR SAW 433 MHZ GND ENTRADA ENTRADA B GND

PIC16F877 31 12

VCC GND ANTENA

ANTENA

TEST SALIDA VCC

GND

GND

GND 13

1 2 3

11

13 14 15

1 2 3 4

11

Se debe tener cuidado en conectar una antena con una impedancia de 50 y de la longitud adecuada. En este caso una antena tipo /4 ser a suciente (de 17.3 cm). c = 3 108 = 0,69 433 106

Por tanto /4 = 0,69/4 = 0,173 metros.

19.3. Cuestiones
...

15

VCC

Cap tulo 19. Comunicaciones

231

19.4. Hojas de datos


Transmisor RF

Transmitters Modules

Wireless 2000

SAW RF Transmitter Module


with EXTERNAL ANTENNA
+V (15) SAW OSCILLATOR MATCHING NETWORK

TX-SAW 433/s-Z
RF Output (11)

dBm

3 to 5V

7.5

In Mod. (2)

In Mod. (3)

dBm

5 to 8V
Pin-out
1) Ground 2) Input Mod. 3) Input Mod. 4) Ground 11) Ground 13) Ground 15) +V (3 to 12V)

4
Information subject to change without notice

Variable Supply
dBm

9.5 8 to 12V
434 MHz
Descrizione
Modulo trasmettitore SAW con antenna esterna per applicazioni con modulazione ON-OFF di una portante RF con dati digitali. Conforme alle Normative Europee EN 300 220 ed ETS 300 683 (Compatibilit Elettromagnetica).
0.5

Description
SAW transmitter module with external antenna ideal for applications when you need to modulate ON-OFF a RF carrier with digital signals. In compliance with European Standard EN 300 220 and ETS 300 683 (Electromagnetic Compatibility).

Mechanical Dimensions
38.1 3

Component Side
1 2 3 4 11 13 15

13.2 7 0.25

2.54

Technical Specification
CHARACTERISTICS
VS IS

Ta = 25 C

MIN
35 3.5 7.5 3.5 8 3 VS -20

TYP
58 3.5 4 433.92 7.5 10.5 -50 4 VS

MAX
8 12 7.5 9.5 12 15 4 VS +80

UNIT
Vdc mA MHz dBm dB KHz V C

FC
PERP ES FM LI TOP

Supply Voltage Alimentazione Supply Current Corrente assorbita Working frequency Frequenza di lavoro RF Output power (E.R.P.) Potenza di uscita RF (E.R.P .) RF spurious emission Emissioni RF spurie Square wave modulation Frequenza di modulazione Input logic level Livello logico dingresso Operating temperature range Temperatura di lavoro

Technical Mail : Lab-el@aurel.it


Via Foro dei Tigli, 4 I 47015 Modigliana (FC) Italy Phone : +39-0546941124 Fax : +39-0546941660 http://www.aurel.it E-mail: aurel@aurel.it

232 Receptor RF

Hojas de datos

WIRELESS

434 Mhz Standard (OOK) Receiver


+V (1,15) +V (1,15)

BC-NBK
Data Out (14)

Antenna (3)
RF AMP

AM DET. LF AMP COMP

T.P.(13)

1) +V 2) Ground 3) Antenna 7) Ground 11) Ground 13) Test Point 14) Data Output 15) +V

5V
Descrizione
Ricevitore economico su allumina ad elevata miniaturizzazione. Basso assorbimento, bassa radiazione in antenna ed alta immunit ai disturbi di alimentazione. In accordo con le Normative Europee.

Description
High-miniaturization SIL thick-film hybrid circuit. Low cost, low antenna radiation and high insensitivity to power switching noises. In compliance with European Normative.

Mechanical Dimensions
38.1 5.5

Component Side
1 2 3 7 11 13 14 15

7 0.5 2.54 0.25

Technical Specification
CHARACTERISTICS MIN TYP MAX

Ta = 25 C UNIT

VS IS FW SI BW SO SL HO LO TON TOP

Supply Voltage Alimentazione Supply Current Corrente Assorbita Reception frequency Frequenza di ricezione RF sensitivity Sensibilit RF - 3dB RF Bandwidth Banda passante RF a - 3dB Square wave output Onda quadra in uscita Spectrum emitted level Radiazione in antenna Output high voltage Livello alto duscita Output low voltage Livello basso duscita Switch-on time Tempo di accensione Operating temperature range Temperatura di lavoro

4.5

5 433.92 -97 1.2 -65

5.5 3

2 -60 GND + 0.4 2 +80

VS - 0.4

-20

Vdc mA MHz dBm MHz KHz dBm V V s C

Product Code: 650200208

AUREL S.p.A. Via Foro dei Tigli, 4 I 47015 Modigliana (FC) Italy Phone : +39-0546.941124 Fax : +39-0546.941660
www.aurelwireless.com
This information may be subject to revision without notice. AUREL makes no warranty and assumes no liability in connection with any use of this information. Variazioni senza preavviso delle presenti informazioni non implicano responsabilit da parte AUREL. L'acquirente assume ogni responsabilit derivante dall'uso del prodotto.

WIRELESS

Information subject to change without notice

Pin-out

3 mA max

13.7

Cap tulo 20 LCD Gr aco


Si no puedo dibujarlo es que no lo entiendo Albert Einstein

20.1. Introduccion
Explorando los distribuidores de material electronico para hacer acopio de materiales para el curso venidero y conseguir exprimir al m aximo el presupuesto, encon tr e con gran jubilo por mi parte un LCD gr aco a un precio de risa. Lo cierto es que descubr que algunos grandes distribuidores -l ease RS-Amidata- han decidido (26 de agosto de 2008) bajar los precios a los que nos ten an acostumbrados haci endose real1 mente m as competitivos . El caso es que el unico inconveniente que he encontrado es que funciona a 3.3V. si todos tenemos cuidado!. El display2 en cuestion es de la Pero esto tiene solucion casa DisplayTech y el modelo es el 64128H con un controlador Samsung S6B0724. Necesitaremos un hardware espec co para adaptar las patillas del controlador y la El esquema mostrado a continuacion puede iluminarnos: retroiluminacion.
a la crisis?, en vez de congelarnos el sueldo o mantenerlo una vez m Ser a la solucion as muy por debajo del IPC, espero que s 2 Amidata referencia 1627-1848
1

233

234

Introducci on

J3 J2
5 4 3 2 1 CONN-SIL5 CS RST RS R/W E DB0 DB1 DB2 DB3 DB4 DB5 DB6 DB7 1 2 3 4 5 6 7 8 9 10 11 12 13 3.3V 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

U1
GND 3 2 1 3 VI VO 2 3.3V 5V LD1086V33

LCD1
CS1B RST RS R/W E DB0 DB1 DB2 DB3 DB4 DB5 DB6/SCLK DB7/SDI 3.3V VCI VSS VOUT C4+ C3+ C1C1+ C2+ C2V1 V2 V3 V4 V0 C86 PS 64128H PACKAGE=64128H

CONN-SIL3

C11
0.1uF

J1
8 7 6 5 4 3 2 1 CONN-SIL8

Five Times Boosting Circuit

C10
4.7uF

C9
4.7uF

C8
4.7uF

C7
4.7uF

C6
4.7uF

C5
1uF

C4
1uF

C3
1uF

C2
1uF

C1
1uF

BL1 R1
22R 5V 1 2 A K 64128H_BL PACKAGE=64128H_BL

(5V - 3.2V)/80mA = 22R

donde encontramos el conector J3 que nos permitir a alimentar a 5V y obtener los 3.3V en la patilla del medio para alimentar tanto el display como el PIC al que conectare mos el LCD. El conector J2 nos permitir a llevar las senales de control y el J1 las l neas de datos y comandos. Se ha implementado un acceso en paralelo en vez de serie para poder hacer lecturas de la memoria de datos del LCD. del hardware se puede ver a continuacion: El diseno

Cap tulo 20. LCD Gr aco Para el funcionamiento los comandos se muestran a continuacion:
Table 18. Instruction Table

235

: Don't care Instruction


Display ON / OFF Initial display line Set page address Set column address MSB Set column address LSB Read status Write display data RS 0 0 0 0 0 0 1 RW 0 0 0 0 0 1 0 DB7 1 0 1 0 0 BUSY DB6 0 1 0 0 0 ADC DB5 1 ST5 1 0 0 ON/OFF DB4 0 ST4 1 1 0 RESETB DB3 1 ST3 P3 Y7 Y3 0 DB2 1 ST2 P2 Y6 Y2 0 DB1 1 ST1 P1 Y5 Y1 0 DB0 DON ST0 P0 Y4 Y0 0

Description
Turn on/off LCD panel When DON = 0: display OFF When DON = 1: display ON Specify DDRAM line for COM0 Set page address Set column address MSB Set column address LSB Read the internal status Write data into DDRAM

Write data

Read display data

Read data

Read data from DDRAM Select SEG output direction When ADC = 0: normal direction (SEG0SEG131) When ADC = 1: reverse direction (SEG131SEG0) Select normal / reverse display When REV = 0: normal display When REV = 1: reverse display Select normal/entire display ON When EON = 0: normal display. When EON = 1: entire display ON Select LCD bias Set modify-read mode release modify-read mode Initialize the internal functions Select COM output direction When SHL = 0: normal direction (COM0COM63) When SHL = 1: reverse direction (COM63COM0) Control power circuit operation Select internal resistance ratio of the regulator resistor Set reference voltage mode Set reference voltage register Set static indicator mode Set static indicator register Compound Instruction of display OFF and entire display ON

ADC select

ADC

Reverse display ON / OFF

REV

Entire display ON / OFF LCD bias select Set modify-read Reset modify-read Reset

0 0 0 0 0

0 0 0 0 0

1 1 1 1 1

0 0 1 1 1

1 1 1 1 1

0 0 0 0 0

0 0 0 1 0

1 0 0 1 0

0 1 0 1 1

EON BIAS 0 0 0

SHL select

SHL

Power control Regulator resistor select Set reference voltage mode Set reference voltage register Set static indicator mode Set static indicator register Power save

0 0 0 0 0 0 -

0 0 0 0 0 0 -

0 0 1 1 -

0 0 0 0 -

1 1 0 SV5 1 -

0 0 0 SV4 0 -

1 0 0 SV3 1 -

VC R2 0 SV2 1 -

VR R1 0 SV1 0 S1 -

VF R0 1 SV0 SM S0 -

20.2. Se pide
Montaje basado en PIC que nos permita dibujar en el display gr aco.

20.3. Cuestiones

236

Cuestiones

Cap tulo 21 Conexion al mundo USB


Hay tres clases de personas: las que saben contar y las que no Uno de mi pueblo

21.1. Introduccion
Con la familia de microcontroladores 16F de microchip no se implementa de manera directa el controlador USB dentro del microcontrolador. En la familia 18F s que hay algunos microcontroladores que implementan en controlador USB. Para poder trabajar con el protocolo USB una buena ayuda pueden ser los controladores de FTDI, como por ejemplo el FT232 o el FT2232 que hemos empleado en el siguiente esquema. Este integrado consigue simular dos puertos UART en el PC a trav es del USB y del otro lado del controlador para poder poner nuestro micro. El circuito lo hemos alimentado de manera externa a 5V aunque podr a haberse alimentado del bus USB. Se puede consultar la hoja de datos del FT2232. Esquema hardware

237

238

Introducci on

CU5
0.1uF

0
V+5

RU5
470R

CU4
46 3 42 14 31

CU3
0.1nF

CU2
0.1nF

FT1
ADBUS0 ADBUS1 ADBUS2 ADBUS3 ADBUS4 ADBUS5 ADBUS6 ADBUS7 ACBUS0 ACBUS1 ACBUS2 ACBUS3 SI/WUA BDBUS0 BDBUS1 BDBUS2 BDBUS3 BDBUS4 BDBUS5 BDBUS6 BDBUS7 BCBUS0 BCBUS1 BCBUS2 BCBUS3 SI/WUB PWREN 24 23 22 21 20 19 17 16 15 13 12 11 10 40 39 38 37 36 35 33 32 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8

10uF

AVCC VCC VCC VCCIOA VCCIOB

USB1
GND USBDP USBDM VCC CONECTOR USB USB_DEV_B 4 3 2 1

J1 J5
2 1 TBLOCK-M2

RU6
10k

RU0
27R 6

3V3OUT

RU1
27R

USBDM

J4
CONN-SIL8 1 2 3 4 5 CONN-SIL5

RU2
4k7

USBDP

RU4
1k5

5 4

RSTOUT RESET

J2

43

X1 RU3
10k 44 48 1 2 47

XTIN

CRYSTAL FREQ=6MHz

XTOUT EECS EESK EEDATA TEST

J3
CONN-SIL8 1 2 3 4 5 CONN-SIL5

27pF

27pF

GND GND GND GND

CU0
6

CU1

AGND

30 29 28 27 26 41

6
9 18 25 34 45 FT2232C

8
FILE NAME: DESIGN TITLE:

M_USBe.dsn Esquema Hardware


C:\__\M_USB\M_USBe.dsn
REV:

DATE:

23/05/2008
PAGE:

PATH: BY:

1
J

of

1
9:49:16

Ignacio & Francisco Martin

TIME:

Placa de circuito impreso Con esta dispondremos de todas las patillas disponibles para su uso en una placa de pruebas.

Parte III SOLUCIONES

239

Cap tulo 22 Motores paso a paso


22.1. Solucion
22.1.1. Se pide
1. Encontrar, en el motor paso a paso unipolar proporcionado, cuales son los terminales del mismo (mide la resistencia entre cada dos terminales). El motor puede tener 5 o 6 terminales. En el caso de tener 5 terminales signica que los terminales a y b son el mismo. Los devanados son: Naranja (1a) Rojo (a) Amarillo (2a) Marr on (1b) Verde (b) Negro (2b) La secuencia de conexi on ser a:
Bits[0..3]: Amarillo, Marron, Naranja, Negro; Rojo y Verde a VMotor

Montar el circuito y escribir el programa b asico que sea capaz de hacer girar el motor en sentido horario y antihorario un paso con cada anco de la patilla RA0. del sentido de giro se realizar La seleccion a con la patilla RA3. Listado 22.1: EX/MOTORPASO/MotorStepper.c
2

#include <pic.h> #include "binario.h" __CONFIG(WDTDIS & XT & UNPROTECT & PWRTDIS /* //Paso sencillo. Un devanado cada vez const unsigned char posiciones[]= { B00001000, B00000100, B00000010, B00000001,

& LVPDIS );

241

242
B00001000, B00000100, B00000010, B00000001 }; */ // Pasos con m as par. Dos devanados cada vez const unsigned char posiciones[]= { B00001100, B00000110, B00000011, B00001001, B00001100, B00000110, B00000011, B00001001 }; void main() { unsigned char cuenta = 0; ADCON1 = B00000110; TRISA = B00001111; TRISB = 0;
37

Soluci on

12

17

22

27

32

// PORTA digital // RA0:3 entradas digitales // PORTB salidas digitales

42

// Bucle sin fin while(1) { // Buscar flanco ascendente while(RA0==0); PORTB = posiciones[cuenta & 0x07] << 4; if(RA3 == 1) cuenta++; else cuenta--;

47

// Esperar flanco descendente while(RA0==1); } }

Cap tulo 22. Motores paso a paso

243

2. Poder seleccionar la velocidad de giro del motor. Para ello introduciremos entre del sentido paso y paso un retardo diferente para cada velocidad. La seleccion de giro se realizar a con la patilla RA2 y la velocidad se seleccionar a entre cuatro posibilidades indicadas con RA0 y RA1. Codicar las siguientes velocidades: 00: 50 pasos/segundo 01: 100 pasos/segundo 10: 150 pasos/segundo 11: 200 pasos/segundo Listado 22.2: EX/MOTORPASO/MotorStepper 2.c
#include <pic.h> #include "binario.h" __CONFIG(WDTDIS & XT & UNPROTECT & PWRTDIS
4

& LVPDIS );

// M as par const unsigned char posiciones[]= { B00001100, B00000110, B00000011, B00001100, B00000110, B00000011, }; // Frecuencia = 1/T = 1/(2*Retardo) // Retardo = 1/(2*Frecuencia) // RA0 RA1 Frec. Retardo // 0 0 50 10000 // 0 1 100 5000 // 1 0 150 3333 // 1 1 200 2500 #define Retardo00 10000 #define Retardo01 5000 #define Retardo10 3333 #define Retardo11 2500 volatile unsigned char cuenta = 0; unsigned int PERIODO = Retardo00; void main() { ADCON1 = B00000110; TRISA = B00001111; TRISB = 0;

B00001001, B00001001

14

19

24

29

// PORTA digital // RA0:3 entradas digitales // PORTB salidas digitales

34

T1CON = B00000001; // Habilito TMR1, DIVISOR 1:1 GIE = PEIE = TMR1IE = 1; TMR1H = (65536 - PERIODO) >> 8; TMR1L = (65536 - PERIODO) & 0xFF; // Bucle sin fin while(1); } // Rutina de atenci on de las interrupciones void interrupt ISR(void) { PORTB = posiciones[cuenta & 0x07] << 4; if(RA3 == 1) cuenta++;

39

44

244
else
49

Soluci on
cuenta--;

54

59

if(RA0) { if(RA1) PERIODO = Retardo11; else PERIODO = Retardo10; } else { if(RA1) PERIODO = Retardo01; else PERIODO = Retardo00; } TMR1H = (65536 - PERIODO) >> 8; TMR1L = (65536 - PERIODO) & 0xFF; TMR1IF = 0; }

Cap tulo 22. Motores paso a paso

245

necesitamos conocer cuanto vale el numero 3. Para una mejor realimentacion de pasos por segundo. Se pide enviar por el puerto serie al PC el valor de pasos por segundo. Las patillas RC4 y RC5 decrementar an/incrementar an el retardo entre pasos. Listado 22.3: EX/MOTORPASO/MotorStepper 3.c
2

#include <pic.h> #include "binario.h" #include <stdio.h> #include <string.h> __CONFIG(WDTDIS & XT & UNPROTECT & PWRTDIS & LVPDIS ); // M as par const unsigned char posiciones[]= { B00001100, B00000110, B00000011, B00001001, B00001100, B00000110, B00000011, B00001001 }; /* // Half stepping const unsigned char posiciones[]= { B00001000, B00001100, B00000100, B00000110, B00000010, B00000011, B00000001, B00001001 }; */ volatile unsigned char cuenta = 0; // Frecuencia = 1/T = 1/(2*4000 usec) = 125 Hz unsigned int PERIODO=4000; unsigned char Pinta=1; void main() { char S[10]; unsigned char i; ADCON1 = B00000110; TRISA = B00001111; TRISB = 0; // PORTA digital // RA0:3 entradas digitales // PORTB salidas digitales

12

17

22

27

32

37

42

T1CON = B00000001; // Habilito TMR1, DIVISOR 1:1 GIE = PEIE = TMR1IE = 1; TMR1H = (65536 - PERIODO) >> 8; TMR1L = (65536 - PERIODO) & 0xFF; TRISC6 = 0; TXSTA = 0x24; RCSTA = 0x90; SPBRG = 25; // Bucle sin fin while(1) { if(Pinta) { // // // // TX salida BRGH = 1, 8 bits, as ncrono Activo USART 9600 baudios

47

52

246

Soluci on
sprintf(S,"T = %4d %c %c",PERIODO,10,13); // Ojo ocupa mucho c odigo for(i=0;i<strlen(S);i++){TXREG = S[i]; while(!TRMT);} Pinta = 0; } }; }
62

57

67

// Subrutina de atenci on a las interrupciones void interrupt ISR(void) { PORTB = posiciones[cuenta & 0x07] << 4; if(RA3 == 1) cuenta++; else cuenta--; if(RC4 == 1) {PERIODO --; Pinta = 1;} if(PERIODO<1000) PERIODO=1000; if(RC5 == 1) {PERIODO ++; Pinta = 1;} TMR1H = (65536 - PERIODO) >> 8; TMR1L = (65536 - PERIODO) & 0xFF;

72

77

TMR1IF = 0; }

nominal del motor: usar 5 V. Cuidado con la tension

Cap tulo 22. Motores paso a paso

247

22.1.2. Cuestiones
del motor? Cuantos pasos por vuelta tiene? a) Cu al es la resolucion La resoluci on del motor es de 48 pasos por vuelta. Despu es de la reductora (1:50) se necesitan 2400 pasos para dar una vuelta completa. b) Qu e consumo tiene? De qu e depende? Segun las hojas de datos los drivers de potencia son capaces de proporcionar un m aximo de 500 mA, aunque estas salidas se pueden poner en paralelo (podr amos tener 1 A por devanado). Segun las hojas de datos el motor aguanta 450 mA por fase. El consumo depende de la velocidad de giro y de la carga. A la velocidad m axima y sin carga, medido con un mult metro, consume unos 200 mA estando alimentados dos devanados a la vez. c) Cual es la frecuencia m axima de giro del motor sin que pierda pasos? Segun las hojas de datos unos 200 pasos por segundo. Medido, efectivamente, unos 200 pasos por segundo (sin carga) d) Sabr as calcular el par que tiene a cada velocidad y dibujar la curva par-velocidad? Para ello ser a necesario disponer de una rueda de radio conocido y poner un dinam ometro en el extremo de un hilo enrrollado en la rueda. El montaje es complejo y no lo haremos. e) Recuerdas qu e es el momento de inercia? El momento de inercia1 o inercia rotacional representa la inercia de un cuerpo a rotar; es el valor escalar del momento angular longitudinal de un s olido r gido; es una magnitud que reeja la distribuci on de masas de un cuerpo o un sistema de part culas, respecto de un eje, en un movimiento de rotaci on. El momento de inercia no depende de las fuerzas que intervienen, sino de la geometr a del cuerpo y de la posici on del eje de giro; este concepto desempena un papel an alogo al de la masa inercial en el caso del movimiento rectil neo y uniforme. De manera general se calcula como: I= r2 dm = r2 dV

Este concepto, desempena en el movimiento de rotaci on un papel an alogo al de masa inercial en el caso del movimiento rectil neo y uniforme. (La masa es la resistencia que presenta un cuerpo a ser acelerado en traslaci on y el Momento de Inercia es la resistencia que presenta un cuerpo a ser acelerado en rotaci on). As , por ejemplo, la segunda ley de Newton: a = F/m tiene como equivalente para la rotaci on: M = F r = I donde:
1

Extra do de la Wikipedia

248 M es el momento aplicado al cuerpo, que es una fuerza por una distancia. I es el momento de inercia del cuerpo con respecto al eje de rotaci on y =
d2 dt2

Soluci on

es la aceleraci on angular.

La energ a cin etica de un cuerpo en movimiento con velocidad v es 1/2mv 2 , mientras que 1 la energ a de cin etica de un cuerpo en rotaci on con velocidad angular es 2 I 2 . Donde I es el momento de inercia con respecto al eje de rotaci on. La conservaci on de la cantidad de movimiento o momento lineal tiene por equivalente la conservaci on del momento angular L: L = I El vector momento angular tiene la misma direcci on que el vector velocidad angular .

Cap tulo 23 Termometro digital


23.1. Solucion
23.1.1. Se pide
1. Deberemos congurar el conversor AD y pintar el valor entero que obtengamos, que estar a entre 0 y 65535 (los 10 bits m as signicativos). Listado 23.1: EX/TERMOMETRO/TERMOMETRO1.c
2

#include <pic.h> #include "LCD.h" #include <stdio.h> // Para el PIC16F87x __CONFIG(WDTDIS & XT & UNPROTECT & PWRTDIS & LVPDIS );

void PintaMensaje(unsigned int temp) { unsigned char i=0; char M[16];


12

LCD_Comando(LCDCasa); sprintf(M,"Temp: %7d C",temp); while( M[i]!=0 ) LCD_Caracter( M[i++] );


17

// Pinta

} void main() { ADCON1 = B00000000; // PORTA anal ogico, justif a la izquierda LCD_Port(); // Inicia los puertos LCD_Reset(); // Inicia el LCD ADCON0 = B11000001; // // // // // // // // Configura conversor AD ADCS[1:0] = 11 Oscilador interno de 2 a 6 useg. indep. Fosc CH[2:0] = 000 Canal 0 RA0/AD0 ADGO/DONE = 0 Fin conversion = 0 No usado ADON = 1 Conversor AD habilitado

22

27

32

while(1) {

// Bucle infinito

249

250
ADIF = 0; ADGO = 1; // Borro indicador de fin de conversion // Inicia la conversion AD

Soluci on

37

while(!ADIF); PintaMensaje(ADRESH<<8|ADRESL); }
42

2. Convertiremos el dato entero al dato en grados cent grados y lo pintaremos. Listado 23.2: EX/TERMOMETRO/TERMOMETRO2.c
3

#include <pic.h> #include "LCD.h" #include <stdio.h> // Para el PIC16F87x __CONFIG(WDTDIS & XT & UNPROTECT & PWRTDIS & LVPDIS );

void PintaMensaje(unsigned int temp) { unsigned char i=0; char M[16]; unsigned long t = (temp*5000L)>>16; LCD_Comando(LCDCasa); sprintf(M,"Temp: %7d C",(unsigned int)t); while( M[i]!=0 ) LCD_Caracter( M[i++] ); // Pinta

13

18

} void main() { ADCON1 = B00000000; // PORTA anal ogico, justif. a la izquierda LCD_Port(); // Inicia los puertos LCD_Reset(); // Inicia el LCD ADCON0 = B11000001; // // // // // // // // Configura conversor AD ADCS[1:0] = 11 Oscilador interno de 2 a 6 useg. indep. Fosc CH[2:0] = 000 Canal 0 RA0/AD0 ADGO/DONE = 0 Fin conversion = 0 No usado ADON = 1 Conversor AD habilitado

23

28

33

38

while(1) { ADIF = 0; ADGO = 1;

// Bucle infinito // Borro indicador de fin de conversion // Inicia la conversion AD

while(!ADIF); PintaMensaje(ADRESH<<8|ADRESL); }
43

3. Opcionalmente podremos visualizar la temperatura en grados Kelvin (K = 273,15+ C + 32). C ) y grados Farenheit (F = 9 5 Listado 23.3: EX/TERMOMETRO/TERMOMETRO3.c

Cap tulo 23. Term ometro digital


#include <pic.h> #include "LCD.h" #include <stdio.h> // Para el PIC16F87x __CONFIG(WDTDIS & XT & UNPROTECT & PWRTDIS
7

251

& LVPDIS );

12

void PintaMensaje(unsigned int temp) { unsigned char i=0; char M[16]; unsigned long t = (temp*500L)>>16; LCD_Comando(LCDCasa); sprintf(M,"T= %7d C",(unsigned int)t); while( M[i]!=0 ) LCD_Caracter( M[i++] ); // Pinta

17

22

LCD_Comando(LCDLinea2); i=0; sprintf(M,"T= %7d F",(unsigned int)(t*9/5+32)); while( M[i]!=0 ) LCD_Caracter( M[i++] ); // Pinta } void main() { ADCON1 = B00000000; // PORTA anal ogico, justif. a la izquierda LCD_Port(); // Inicia los puertos LCD_Reset(); // Inicia el LCD ADCON0 = B11000001; // // // // // // // // Configura conversor AD ADCS[1:0] = 11 Oscilador interno de 2 a 6 useg. indep. Fosc CH[2:0] = 000 Canal 0 RA0/AD0 ADGO/DONE = 0 Fin conversion = 0 No usado ADON = 1 Conversor AD habilitado

27

32

37

42

while(1) { ADIF = 0; ADGO = 1;

// Bucle infinito // Borro indicador de fin de conversion // Inicia la conversion AD

47

while(!ADIF); PintaMensaje(ADRESH<<8|ADRESL); } }

4. Convertiremos dos valores de temperatura, a saber, interna y externa, procedentes de dos sensores. Listado 23.4: EX/TERMOMETRO/TERMOMETRO4.c
2

#include <pic.h> #include "LCD.h" #include <stdio.h> // Para el PIC16F87x __CONFIG(WDTDIS & XT & UNPROTECT & PWRTDIS & LVPDIS );

252
void PintaMensaje(unsigned int temp, unsigned int temp2) { unsigned char i=0; char M[16]; unsigned long t = (temp*500L)>>16; LCD_Comando(LCDCasa); sprintf(M,"T1= %7d C",(unsigned int)t); while( M[i]!=0 ) LCD_Caracter( M[i++] ); LCD_Comando(LCDLinea2); i=0; t = (temp2*500L)>>16; sprintf(M,"T2= %7d C",(unsigned int)t); while( M[i]!=0 ) LCD_Caracter( M[i++] ); } void main() { unsigned int t1,t2; // Pinta

Soluci on

12

17

22

// Pinta

27

32

ADCON1 = B00000000; // PORTA anal ogico, justif. a la izquierda LCD_Port(); // Inicia los puertos LCD_Reset(); // Inicia el LCD while(1) // Bucle infinito { ADCON0 = B11000001; // // // // // // // // ADIF = 0; ADGO = 1;

37

42

Configura conversor AD ADCS[1:0] = 11 Oscilador interno de 2 a 6 useg. indep. Fosc CH[2:0] = 000 Canal 0 RA0/AD0 ADGO/DONE = 0 Fin conversion = 0 No usado ADON = 1 Conversor AD habilitado

// Borro indicador de fin de conversion // Inicia la conversion AD

47

while(!ADIF); t1=ADRESH<<8|ADRESL; ADCON0 = B11001001;


52

57

// // // // // // // //

Configura conversor AD ADCS[1:0] = 11 Oscilador interno de 2 a 6 useg. indep. Fosc CH[2:0] = 001 Canal 1 RA1/AD1 ADGO/DONE = 0 Fin conversion = 0 No usado ADON = 1 Conversor AD habilitado

ADIF = 0; ADGO = 1;
62

// Borro indicador de fin de conversion // Inicia la conversion AD

while(!ADIF); t2=ADRESH<<8|ADRESL; PintaMensaje(t1,t2); } }

67

Cap tulo 23. Term ometro digital 5. Calcularemos la m axima, la m nima, el promedio de cada temperatura. Listado 23.5: EX/TERMOMETRO/TERMOMETRO5.c
2

253

#include <pic.h> #include "LCD.h" #include <stdio.h> // Para el PIC16F87x __CONFIG(WDTDIS & XT & UNPROTECT & PWRTDIS & LVPDIS );

unsigned int t1max=0,t1min=65535, t2max=0, t2min=65535; void PintaMensaje(unsigned int temp, unsigned int temp2) { unsigned char i=0; char M[16]; unsigned long t = (temp*500L)>>16; LCD_Comando(LCDCasa);
17

12

sprintf(M,"T1= %7d C",(unsigned int)t); while( M[i]!=0 ) LCD_Caracter( M[i++] ); LCD_Comando(LCDLinea2); i=0; t = (temp2*500L)>>16; sprintf(M,"T2= %7d C",(unsigned int)t); while( M[i]!=0 ) LCD_Caracter( M[i++] ); }
27

// Pinta

22

// Pinta

void main() { unsigned int t1,t2;


32

ADCON1 = B00000000; // PORTA anal ogico, justif. a la izquierda LCD_Port(); // Inicia los puertos LCD_Reset(); // Inicia el LCD while(1) // Bucle infinito { ADCON0 = B11000001; // // // // // // // // ADIF = 0; ADGO = 1;

37

42

Configura conversor AD ADCS[1:0] = 11 Oscilador interno de 2 a 6 useg. indep. Fosc CH[2:0] = 000 Canal 0 RA0/AD0 ADGO/DONE = 0 Fin conversion = 0 No usado ADON = 1 Conversor AD habilitado

47

// Borro indicador de fin de conversion // Inicia la conversion AD

52

while(!ADIF); t1=ADRESH<<8|ADRESL; if(t1<t1min) t1min=t1; if(t1>t1max) t1max=t1; ADCON0 = B11001001; // Configura conversor AD // ADCS[1:0] = 11 Oscilador interno // de 2 a 6 useg. // indep. Fosc // CH[2:0] = 001 Canal 1 RA1/AD1

57

254
// ADGO/DONE = 0 // = 0 // ADON = 1 ADIF = 0; ADGO = 1;
67

Soluci on
Fin conversion No usado Conversor AD habilitado

62

// Borro indicador de fin de conversion // Inicia la conversion AD

while(!ADIF); t2=ADRESH<<8|ADRESL; if(t2<t2min) t2min=t2; if(t2>t2max) t2max=t2; PintaMensaje(t1,t2); } }

72

23.1.2. Cuestiones
a)Se puede ampliar el rango de temperaturas (temperaturas negativas: rango des hardware? de -55o C a 150o C) con alguna modicacion El hardware permite ampliar el rango de temperaturas a temperaturas negativas de hasta -55 o C. Sin embargo el convertido AD integrado en el microcontrolador indica que -se puede consultar en la hoja de datos incluida en el CDROM- que no se puede poner una tensi on de referencia negativa para el convertidor ,Vref inferior a VSS-0.3V, con lo que las posibilidades desaparecen. Deber amos emplear un convertidor AD externo y necesitar amos una fuente de tensi on negativa como se indica en la hoja de datos del LM35 1 de la informacion mostrada? b) Se puede aumentar la resolucion En principio s . Por defecto, sin usar las referencias externas de tensi on para el convertido AD del microcontrolador estaremos empleando un fondo de escala de VCC-VSS voltios (5V en condiciones t picas). Esto signica que el bit menos signicativo de la conversi on equivale a 5V /1024 = 0,0048V , es decir aproximadamente 5 mV o lo que es lo mismo una resoluci on de 0.5o C segun la conversi on de voltaje a grados del LM35. Dado que la resoluci on dada por el sensor a temperatura ambiente es de 0.25 o C podemos anar algo m as. Si ponemos Vref = 0V y Vref + = 2V cumpliendo especicaciones, tendremos una resoluci on en el mejor de los casos de 2V /1024 = 0,0019V . O sea, algo as como 0.019o C. Sin embargo, necesitaremos una referencia externa de 2 V estable y capaz de proporcionar un m aximo de 1000A. c) Porqu e la temperatura mostrada es unas cent esimas de grado superior a la medida con un pol metro directamente en el sensor? Puede deberse a la ausencia del condensador de desacoplo en el diseno montado. De hecho si se retira este condensador (de unos 100 nF) se observar a este efecto, debido a que la senal de tierra se ve afectada por el ruido de conmutaci on digital proveniente del microcontrolador.
Si se coloca una referencia Vref + para reducir el fondo de escala del conversor AD hay que recordar que el fabricante recomienda que la diferencia entre Vref + y Vref sea superior a 2,0 V.
1

Cap tulo 23. Term ometro digital d) Por qu e var a constantemente el valor digitalizado?

255

La digitalizaci on se ve afectada por el ruido digital generado por el propio microcontrolador y por otras fuentes de ruido. Se puede hacer un ltrado por software para evitar este efecto, promediando varias medidas por ejemplo2 . e) Consumo total? Hacemos la medida y nos da .....

Esto es lo que est a haciendo el mult metro empleado en hacer la otra medicion.

256

Soluci on

Cap tulo 24 Generacion de audio


24.1. Solucion
24.1.1. Se pide
Una primera forma con la frecuencia Una forma de generar el sonido consiste en reproducir la senal dada manteniendo durante el primer semi-periodo la patilla de salida en alta y durante el segundo semi-periodo en baja. Para generar toda la escala hemos de ser capaces de temporizar los semi-periodos correspondientes a cada frecuencia lo m as precisamente posible. Nos podemos ayudar de una tabla que contenga los retardos para cada nota. El problema estar a en que necesitaremos retardos de 16 bits. En un primer intento generaremos solo un tono todo el tiempo del mundo Listado 24.1: EX/GEN AUDIO/GEN AUDIO0.c
1

#include <pic.h> #include "binario.h" __CONFIG(WDTDIS & XT & UNPROTECT & PWRTDIS

& LVPDIS );

11

16

21

// Tabla con los semi-retardos en useg #define FACTOR 1000000L/2 const unsigned int SemiRetardos[]={ FACTOR/261.63, // Do4 1915.70 useg FACTOR/293.66, // Re4 FACTOR/329.63, // Mi4 FACTOR/349.23, // Fa4 FACTOR/392.00, // Sol4 FACTOR/440.00, // La4 FACTOR/493.88, // Si4 FACTOR/523.25, // Do5 FACTOR/587.33 // Re5 851.31 useg }; void Retardo(unsigned int useg) { useg-=140; // Para afinar ... por culpa de C no se lo que tarda TMR1H = (65536L-useg)>>8; TMR1L = (65536L-useg); TMR1IF = 0; while(!TMR1IF); // Espera a que desborde }

257

258

Soluci on

26

31

36

41

void main() { unsigned char nota = 0; // Do4 unsigned int semiduracion; TRISB0 = 0; // RB0 es una salida T1CON = B00000001; // 00 // 00 T1CKPS1:0 Preescala = 1:1 // 0 T1OSCEN Oscilador desactivado // 0 /T1SYNC No importa // 0 TMR1CS Reloj interno Fosc/4 // 1 TMR1ON Habilita el temporizador semiduracion = SemiRetardos[nota]; while(1) // Repite para siempre { Retardo(semiduracion); RB0 = 1; Retardo(semiduracion); RB0 = 0; } }

46

En un segundo intento crearemos una funci on que genere un tono durante el tiempo indicado Listado 24.2: EX/GEN AUDIO/GEN AUDIO1.c
#include <pic.h> #include "binario.h" __CONFIG(WDTDIS & XT & UNPROTECT & PWRTDIS
4

& LVPDIS );

14

19

24

// Tabla con los semi-retardos en useg #define FACTOR 1000000L/2 const unsigned int SemiRetardos[]={ FACTOR/261.63, // Do4 1915.70 useg FACTOR/293.66, // Re4 FACTOR/329.63, // Mi4 FACTOR/349.23, // Fa4 FACTOR/392.00, // Sol4 FACTOR/440.00, // La4 FACTOR/493.88, // Si4 FACTOR/523.25, // Do5 FACTOR/587.33 // Re5 851.31 useg }; void Retardo(unsigned int useg) { useg-=140; // Para afinar ... por culpa de C no se lo que tarda TMR1H = (65536L-useg)>>8; TMR1L = (65536L-useg); TMR1IF = 0; while(!TMR1IF); // Espera a que desborde } void TocaNota(unsigned char nota, unsigned int duracion) { // duracion en milesimas de segundo unsigned int semiduracion; int tiempo=0; unsigned int ms = 0; semiduracion = SemiRetardos[nota]; while(ms<=duracion)

29

Cap tulo 24. Generaci on de audio


34

259

{ Retardo(semiduracion); RB0 = 1; Retardo(semiduracion); RB0 = 0; tiempo = tiempo + semiduracion<<1; while(tiempo>1000) {ms++;tiempo=tiempo-1000;} } }

39

44

void main() { TRISB0 = 0; T1CON = B00000001;

49

// // // // // // //

RB0 es una salida 00 00 T1CKPS1:0 Preescala = 1:1 0 T1OSCEN Oscilador desactivado 0 /T1SYNC No importa 0 TMR1CS Reloj interno Fosc/4 1 TMR1ON Habilita el temporizador

54

while(1) { TocaNota(0,200); TocaNota(6,200); } }

// Repite para siempre

59

Finalmente interpretaremos una melod a Listado 24.3: EX/GEN AUDIO/GEN AUDIO2.c


#include <pic.h> #include "binario.h" __CONFIG(WDTDIS & XT & UNPROTECT & PWRTDIS
5

& LVPDIS );

// Notas musicales, todas de la misma duraci on // Almacenadas en la memoria de programa const unsigned char Partitura[]={6,6,7,8,8,7,6,5,4,4,5,6,6,6,5, 5,6,6,7,8,8,7,6,5,4,4,5,6,5,4, 100 }; // Tabla con los semi-retardos en useg #define FACTOR 1000000L/2 const unsigned int SemiRetardos[]={ FACTOR/261.63, // Do4 1915.70 useg FACTOR/293.66, // Re4 FACTOR/329.63, // Mi4 FACTOR/349.23, // Fa4 FACTOR/392.00, // Sol4 FACTOR/440.00, // La4 FACTOR/493.88, // Si4 FACTOR/523.25, // Do5 FACTOR/587.33 // Re5 851.31 useg }; void Retardo(unsigned int useg) { useg-=140; // Para afinar ... por culpa de C no se lo que tarda TMR1H = (65536L-useg)>>8; TMR1L = (65536L-useg); TMR1IF = 0; while(!TMR1IF); // Espera a que desborde }

10

15

20

25

30

260
void TocaNota(unsigned char nota, unsigned int duracion) { // duracion en milesimas de segundo unsigned int semiduracion; int tiempo=0; unsigned int ms = 0; semiduracion = SemiRetardos[nota]; while(ms<=duracion) { Retardo(semiduracion); RB0 = 1; Retardo(semiduracion); RB0 = 0; tiempo = tiempo + semiduracion<<1; while(tiempo>1000) {ms++;tiempo=tiempo-1000;} } } void main() { unsigned char nota; unsigned char i=0; TRISB0 = 0; T1CON = B00000001;

Soluci on

35

40

45

50

55

// // // // // // //

RB0 es una salida 00 00 T1CKPS1:0 Preescala = 1:1 0 T1OSCEN Oscilador desactivado 0 /T1SYNC No importa 0 TMR1CS Reloj interno Fosc/4 1 TMR1ON Habilita el temporizador

60

65

while(1) { nota = Partitura[i++]; // Lee la nota if(nota!=100) TocaNota(nota,250); // Toca la nota else i =0; // Vuelve a empezar } }

Una segunda t ecnica Una segunda manera mucho m as interesante consiste en aplicar la t ecnica DDS (Direct Digital Synthesis) que consiste en generar de forma digital la forma de onda re (fR ) tiene que ser m querida para cada frecuencia. La frecuencia de reproduccion as del doble de la m axima frecuencia a reproducir (criterio de Nyquist). Existir a un acumulador de 16 bits que ser a la fase de la forma de onda sinusoidal a generar. Para generar igual una frecuencia (f ) u otra debo sumarle un desfase en cada punto de reproduccion a 216 f /fR .

Despu es se accede a una tabla de senos en ROM y se saca por el conversor AD. B asicamente se trata de recorrer la tabla del seno m as o menos r apido, dependiendo de la frecuencia de la nota. En nuestro caso y dado que el conversor AD del que

Cap tulo 24. Generaci on de audio

261

el b disponemos es de 1 bit (salida digital) haremos la siguiente aproximacion: t m as signicativo del acumulador es el dato que queremos sacar. Una soluci on interpretando la melod a Listado 24.4: EX/GEN AUDIO/GEN AUDIO3.c
#include <pic.h> __CONFIG(WDTDIS & XT & UNPROTECT & PWRTDIS
4

& LVPDIS );

// Notas musicales, todas de la misma duraci on // Almacenadas en la memoria de programa const unsigned char Partitura[]={6,6,7,8,8,7,6,5,4,4,5,6,6,6,5, 5,6,6,7,8,8,7,6,5,4,4,5,6,5,4, 100 }; // Voy a utilizar una t ecnica denominada DDS // [[Direct Digital Synthesis]] // Existir a una acumulador de 16 bits que ser a la fase de // la forma de onda sinusoidal que quiero generar. Para // generar una frecuencia u otra debo sumarle un desfase // en cada iteraci on del bucle. // As para un DO4 (261.63 Hz), dw = 216*f/fM // dw = 216*261.63/40000 = 428.65 = 428 #define FREQ 22727 const unsigned int Desfase[]={ 65536L*261.63/FREQ, 65536L*293.66/FREQ, 65536L*329.63/FREQ, 65536L*349.23/FREQ, 65536L*392.00/FREQ, 65536L*440.00/FREQ, 65536L*493.88/FREQ, 65536L*523.25/FREQ, 65536L*587.33/FREQ }; // // // // // // // // // Do4 Re4 Mi4 Fa4 Sol4 La4 Si4 Do5 Re5

14

19

24

29

34

39

void Toca(unsigned char nota) { unsigned int Cuenta; static unsigned int Acumulador=0; // Si no fuera static la reiniciar a // todas las veces y se notar a // La duraci on del bucle deber a ser de 1/FREQ // Medido con Proteus paso a paso me sale de 44 useg // luego FREQ = 1/44usec = 22727 // La primera nota que es un Si4 me sale de 489Hz en vez de 494Hz // debido a que no siempre tarda lo mismo el bucle y a la iniciaci on // La duraci on de la nota = VECES/FREQ = 0.25seg => VECES = FREQ/4 for(Cuenta=0; Cuenta<FREQ/4; Cuenta++) { Acumulador = Acumulador + Desfase[nota]; if(Acumulador&0x8000) RB0 = 0; // Como no tengo tabla de senos aproximo else RB0 = 1; // a una se nal cuadrad de la misma frec. } } void main() { unsigned int i; unsigned char nota;

44

49

54

TRISB0 = 0; while(1)

// RB0 es una salida // Repite para siempre

262
{
59

Soluci on

nota = Partitura[i++]; // Toma una nota if(nota!=100) Toca(nota);// Toca la nota else i = 0; // Empieza de nuevo } }

Generar una melod a Tomar como ejemplo los primeros compases del himno de la alegr a mostrados a continuacion:

Si4,4, La4,2, Do5,2, La4,4, Si4,1, Do5,2, Si4,2,

Do5,2, Si4,2, Si4,2, Si4,2, Do5,1, Re5,2, La4,3,

Re5,2, Re5,2, Do5,2, Si4,2, La4,2, Sol4,2, Sol4,2, Si4,4, La4,4, Si4,2, Si4,2, Do5,2, Re5,2, Re5,2, La4,2, Sol4,2, Sol4,2, La4,2, Si4,2, La4,4, Sol4,4, Sol4,2, La4,2, Si4,1, Do5,1, Si4,2, Sol4,2, La4,2, Si4,2, La4,2, Sol4,2, La4,2, Mi4,2, Si4,4, Si4,2, Re5,2, Do5,2, Si4,2, La4,2, Sol4,2, Sol4,2, La4,2, Sol4,1, Sol4,4

1 El formato de los datos mostrados es (NotaOctava, Duracion), donde la duracion equivale aproximadamente a 0,25 segundos (depender a del tempo). Propuesta est Guardar los datos en la EEPROM interna. Una primera aproximacion a en que doble, se duplica). todas las notas duren lo mismo (si hay alguna de duracion Una soluci on interpretando la melod a y empleando la memoria EEPROM Listado 24.5: EX/GEN AUDIO/GEN AUDIO4.c
2

12

#include <pic.h> __CONFIG(WDTDIS & XT & UNPROTECT & PWRTDIS & LVPDIS ); #define BLANCA 8 #define NEGRA 4 #define CORCHEA 2 #define SEMICOR 1 // Notas musicales, todas de la misma duraci on // Almacenadas en la memoria EEPROM __EEPROM_DATA(6,NEGRA, 7,CORCHEA, 8,CORCHEA, 8,CORCHEA __EEPROM_DATA(7,CORCHEA, 6,CORCHEA, 5,CORCHEA, 4,CORCHEA __EEPROM_DATA(4,CORCHEA, 5,CORCHEA, 6,CORCHEA, 6,CORCHEA __EEPROM_DATA(6,CORCHEA, 5,CORCHEA, 5,CORCHEA, 6,CORCHEA __EEPROM_DATA(6,CORCHEA, 7,CORCHEA, 8,CORCHEA, 8,CORCHEA __EEPROM_DATA(7,CORCHEA, 6,CORCHEA, 5,CORCHEA, 4,CORCHEA __EEPROM_DATA(4,CORCHEA, 5,CORCHEA, 6,CORCHEA, 5,CORCHEA __EEPROM_DATA(4,CORCHEA, 100, 0, 0, 0, 0, 0 ); // Voy a utilizar una t ecnica denominada DDS // [[Direct Digital Synthesis]]

); ); ); ); ); ); );

17

Cap tulo 24. Generaci on de audio


// Existir a una acumulador de 16 bits que ser a la fase de // la forma de onda sinusoidal que quiero generar. Para // generar una frecuencia u otra debo sumarle un desfase // en cada iteraci on del bucle. // As para un DO4 (261.63 Hz), dw = 216*f/fM // dw = 216*261.63/40000 = 428.65 = 428 #define FREQ 22727 const unsigned int Desfase[]={ 65536L*261.63/FREQ, 65536L*293.66/FREQ, 65536L*329.63/FREQ, 65536L*349.23/FREQ, 65536L*392.00/FREQ, 65536L*440.00/FREQ, 65536L*493.88/FREQ, 65536L*523.25/FREQ, 65536L*587.33/FREQ }; // // // // // // // // // Do4 Re4 Mi4 Fa4 Sol4 La4 Si4 Do5 Re5

263

22

27

32

37

42

47

void Toca(unsigned char nota, unsigned char n_duracion) { unsigned int Cuenta; unsigned char n; static unsigned int Acumulador=0; // Si no fuera static la reiniciar a // todas las veces y se notar a // La duraci on del bucle deber a ser de 1/FREQ // Medido con Proteus paso a paso me sale de 44 useg // luego FREQ = 1/44usec = 22727 // La primera nota que es un Si4 me sale de 489Hz en vez de 494Hz // debido a que no siempre tarda lo mismo el bucle y a la iniciaci on // La duraci on de la nota = VECES/FREQ = 0.125seg => VECES = FREQ/8 for(n=0;n<n_duracion;n++) for(Cuenta=0; Cuenta<FREQ/8; Cuenta++) { Acumulador = Acumulador + Desfase[nota]; if(Acumulador&0x8000) RB0 = 0; // Como no tengo tabla de senos aproximo else RB0 = 1; // a una se nal cuadrad de la misma frec. } } void main() { unsigned int i; unsigned char nota, duracion; TRISB0 = 0; // RB0 es una salida while(1) // Repite para siempre { nota = EEPROM_READ(i++); // Toma una nota de la EEPROM duracion = EEPROM_READ(i++); // Toma la duraci on de la EEPROM if(nota!=100) Toca(nota,duracion);// Toca la nota else i = 0; // Empieza de nuevo } }

52

57

62

67

72

264

Soluci on

24.1.2. Cuestiones
a) El consumo del circuito depende de la nota que se interprete?Por qu e? Siendo el ciclo de trabajo del 50 % no cabe esperar que el consumo diera segun la nota. cuadrada para que sonaran tonos m b)Como reducir as los armonicos de la senal as puros? Habr a que ltrar la senal. El problema es que el ltro que va bien con una frecuencia puede ir no tan bien con otra.

Cap tulo 25 Motores de corriente continua


25.1. Solucion
25.1.1. Se pide
del software para controlar no solo el puente H que haga girar el motor El diseno en los dos sentidos sino tambi en las rutinas necesarias para controlar la velocidad del de la anchura de los pulsos (PWM). motor empleando la modulacion PWM conseguimos variar la velocidad del motor como si la Con la modulacion efectiva aplicada fuera menor, pero con la ventaja de que la tension aplicada tension cuando la velocidad de giro sea menor. es la nominal lo que nos da el par m aximo aun Adem as nos permitir a hacer girar el motor a una velocidad inferior a la lograda con la umbral de arranque del motor. tension PWM Se usar a el modulo CCP del microcontrolador. La frecuencia de la senal ser a de 1 kHz. Se emplear a una entrada (RA0) para seleccionar el sentido de giro del motor. La patilla RA3 ser a el freno del motor, de forma que cuando se active el motor se frene r apidamente. La patilla RA1 incrementar a en una unidad el ciclo de trabajo, mientras que RA2 lo decrementar a en una unidad. Inicialmente el ciclo de trabajo estar a en el 50 %. Se proporciona un organigrama:

265

266
Motor de continua

Soluci on

   

           

  

! !#$ "

%!

"&

! )   2# 0   1   2  0   1 1 

' (

Periodo TM R2 = (PR2 + 1)*4*Tosc*Pre_Escala_TM R2 = (2 4 9 + 1)*1 u seg * 4 = 1.0 0 m seg (1 k H z)

 

4 !# 56 78 " & 3 1

!# " 19 1

' (

)  1 %  @% B  " && 9 3 

!A

%C D

ST

" 19   4 "R 3 1

% D

UV

B " 19   4 "R 3 1

% 

B D

% 

D

B B E "& )FG E "&

  D

PQ

B    D

HI(   

B E

"

B E 1

"& " 1

)FG E

"&

)FG E

Una primera soluci on: Listado 25.1: EX/MOTORDC/MotorDC 1.c


#include <pic.h> #include "binario.h" __CONFIG(WDTDIS & XT & UNPROTECT & PWRTDIS
5

& LVPDIS );

#define #define #define #define

SENTIDO MAS MENOS PARO

RA0 RA1 RA2 RA3

10

#define POSITIVO RB0 #define NEGATIVO RB1 unsigned char Velocidad;

15

20

void main() { ADCON1 = TRISA = TRISB = TRISC = PR2 TMR2

B00000110; B00001111; 0; 0;

// // // //

PORTA RA0:3 PORTB PORTC

digital entradas digitales salidas digitales salidas

= 249; = 0;

// Periodo se nal PWM // Borro la cuenta

Cap tulo 25. Motores de corriente continua


// 0 = 0 reservado // TOUTPS3:0 = 0000 Post-escala = 1:1 // TMR2ON = 1 TMR2 activo // T2CKPS1:0 = 01 Pre-escala 1:4 // El periodo de TMR2 = (PR2+1)*4*Tosc*Pre-escalaTMR2 // = (249+1)*1e-6 *4 = 1.00 mseg => 1000.00 Hz Velocidad = 124; CCPR1L = Velocidad; // Ciclo trabajo = 50 % = 124/249 // Ignoro 2 LSBits CCP1CON = B00001100; // 00 = 00 reservado // CCP1X,CCP1Y = 00 2 LSBits PWM = 00 // CCP1M3:0 = 1100 Modo PWM while(1) { if(MAS ) {Velocidad++; CCPR1L = Velocidad; while(MAS);} if(MENOS) {Velocidad--; CCPR1L = Velocidad; while(MENOS);} if(PARO ) {POSITIVO = NEGATIVO = 0;} else if(SENTIDO) {POSITIVO = 1; NEGATIVO = 0;} else {POSITIVO = 0; NEGATIVO = 1;} } } T2CON = B00000101;

267

25

30

35

40

Realimentar con el PC a trav es del puerto serie para indicar el ciclo de trabajo de la PWM generada. senal Una segunda soluci on: Listado 25.2: EX/MOTORDC/MotorDC 2.c
1

#include <pic.h> #include "binario.h" #include <stdio.h> #include <string.h> __CONFIG(WDTDIS & XT & UNPROTECT & PWRTDIS #define #define #define #define SENTIDO MAS MENOS PARO RA0 RA1 RA2 RA3

& LVPDIS );

11

#define POSITIVO RB0 #define NEGATIVO RB1 unsigned char Velocidad;


16

void Pinta() { char S[15]; unsigned char i;


21

sprintf(S,"Duty = %4d %c %c",Velocidad*100/250,10,13); for(i=0;i<strlen(S);i++){TXREG = S[i]; while(!TRMT);} }


26

// Ojo ocupa mucho

31

void main() { ADCON1 = TRISA = TRISB = TRISC =

B00000110; B00001111; 0; 0;

// // // //

PORTA RA0:3 PORTB PORTC

digital entradas digitales salidas digitales salidas

TRISC7 = 1;

// RX entrada

268
TXSTA = 0x24; RCSTA = 0x90; SPBRG = 25; PR2 TMR2 T2CON = 249; = 0; = B00000101; // BRGH = 1, 8 bits, as ncrono // Activo USART // 9600 baudios

Soluci on

36

41

46

51

56

// Periodo se nal PWM // Borro la cuenta // 0 = 0 reservado // TOUTPS3:0 = 0000 Post-escala = 1:1 // TMR2ON = 1 TMR2 activo // T2CKPS1:0 = 01 Pre-escala 1:4 // El periodo de TMR2 = (PR2+1)*4*Tosc*Pre-escalaTMR2 // = (249+1)*1e-6 *4 = 1.00 mseg => 1000.00 Hz Velocidad = 124; CCPR1L = Velocidad; // Ciclo trabajo = 50 % = 124/249 // Ignoro 2 LSBits CCP1CON = B00001100; // 00 = 00 reservado // CCP1X,CCP1Y = 00 2 LSBits PWM = 00 // CCP1M3:0 = 1100 Modo PWM while(1) { if(MAS ) {Velocidad++; CCPR1L = Velocidad; while(MAS); Pinta();} if(MENOS) {Velocidad--; CCPR1L = Velocidad; while(MENOS);Pinta();} if(PARO ) {POSITIVO = NEGATIVO = 0;} else if(SENTIDO) {POSITIVO = 1; NEGATIVO = 0;} else {POSITIVO = 0; NEGATIVO = 1;} } }

25.1.2. Cuestiones
del ciclo de trabajo para el que sigue girando el a) Cu al es el valor m as pequeno umbral de arranque del motor? motor? Se ha mejorado la tension Experimentalmente el ciclo es del 10 % Claramente se ha mejorado la tensi on de arranque del motor que ha pasado de ser 5 V a funcionar con 10 V. PWM? Qu b) Se escucha la frecuencia de la senal e ocurrir a si la frecuencia de la PWM fuese mucho mayor? Compru senal ebalo. S , se escucha. No se escuchar a el zumbido si es lo sucientemente elevada.

Cap tulo 26 Frecuenc metro/tacometro


26.1. Solucion
26.1.1. Se pide
software se pide la cuenta de los eventos utilizando el TMR1 y la En el diseno cuenta del tiempo usando TMR0 y las interrupciones. Se deber a actualizar la salida por el display cada segundo, indicando el numero de pulsos por segundo y el numero de revoluciones por minuto. Inicialmente se pueden medir los pulsos generados por un pulsador o por el gen presente en el entrenador. Solo es necesario tener en cuenta que la erador de senal tension de salida del mismo sea de 5 voltios y que la frecuencia a medir sea pequena. Posteriormente se puede usar el motor de corriente continua al que se le habr a coloca do el encoder y montarlo junto con el tacometro. El control de velocidad del motor DC continua inferior a 12 voltios se puede hacer alimentando el mismo con una tension (menor tension dar a menor velocidad). Coloca un LED que indique mediante un destello cuando la medida es correcta (una vez cada segundo). Listado 26.1: EX/FREC/FRECUENCIMETRO.C
#include #include #include #include
5

<pic.h> "binario.h" "lcd_frec.h" <stdio.h> & LVPDIS );

__CONFIG(WDTDIS & XT & UNPROTECT & PWRTDIS

10

// Cuentas para TMR0 // Tiempo = 1.00000 seg = 0.999998 // Tiempo = 250 ns * 4 * ( 252* 128 + 2 ) * 31 = 0.999998 segundos // Escala 1:128, programado en OPTION_REG #define Tmr0Count 256-252 #define Tmr0IntCount 31 volatile int Frecuencia = 1; volatile unsigned char CuentaSeg = 0; void interrupt ISR(void) { CuentaSeg--; if(!CuentaSeg) // Cuando valga cero es que transcurrio un segundo {

15

20

269

270
TMR1ON = 0; // Paro el contaje Frecuencia = (TMR1H<<8) + TMR1L;// Transfiero el dato TMR1H = TMR1L = 0; // Inicio la cuenta TMR1ON = 1; // Reanudo la cuenta CuentaSeg = Tmr0IntCount; // Para contar otro segundo } TMR0 = Tmr0Count; TMR0IF=0; } void Pinta() { char M[16]; unsigned char i=0; LCD_Comando(LCDCasa); sprintf(M,"Frec %5d Hz", Frecuencia); while( M[i]!=0 ) LCD_Caracter( M[i++] );

Soluci on

25

30

35

40

// Pinta

45

i=0; LCD_Comando(LCDLinea2); sprintf(M,"Vel %5d rpm", Frecuencia*60/12); while( M[i]!=0 ) LCD_Caracter( M[i++] ); // Pinta } void main() { ADCON1 = 6; TRISC0 = 1; LCD_Port(); LCD_Reset();

50

// // // //

PORTA digital RC0 entrada Inicia los puertos Inicia el LCD = 1 No pull-up entrada (no usado) // INTEDG = 1 Flanco subida RB0/INT (no usado) // T0CS = 0 Temporizador // T0SE = 1 Flanco bajada RB0(INT (no usado) // PSA = 0 Pre-escala con TMR0 // PS2:PS1=110 Pre-escala = 1:128 // // // // // T1CKPS<1:0> T1OSCEN = 0 /T1SYNC = 0 TMR1CS = 1 TMR1ON = 0 = 00, Pre-escala 1:1 Oscilador externo desactivado No Sincroniza con reloj externo Reloj externo TMR1 desactivado

55

OPTION = B11010110; // /RBPU

60

T1CON = B00000010; // 00 reservado


65

70

75

TMR0 = Tmr0Count; CuentaSeg = Tmr0IntCount; TMR1L = 0; TMR1H = 0; // Inicia la cuenta TMR1ON = 1; T0IE = 1; // Activa interrupcion TMR0 GIE = 1; // Activacion global ints while(1) // Bucle sin fin if( (CuentaSeg==Tmr0IntCount)&&(TMR0>254) ) { Pinta(); RA2 = 1; } else RA2 = 0;

80

Cap tulo 26. Frecuenc metro/tac ometro


85

271

Listado 26.2: EX/FREC/LCD FREC.h


// Fichero LCD.h // Se debe incluir en el fichero en que se vaya a usar, una sola vez #include <pic.h> #include "binario.h" // Definimos las conexiones #define LCD_Data PORTB /* Puerto de datos */ #define LCD_RS RA0 /* Comando o dato */ #define LCD_RW RA1 /* Lectura/Escritura LCD */ #define LCD_E RA2 /* Habilita LCD */ void LCD_Port() { TRISA = TRISA & 0xF8; TRISB = 0; LCD_E = 0; }

10

// RC0..RC2 salidas // PORTB todo salidas

15

26.1.2. Cuestiones
hardware del inversor Schmidt Trigger 40106?Por a) Se puede prescindir en el diseno qu e? No, porque detectar amos mucho ruido. Se pone un disparador Schmidt con hist eresis precisamente para evitar eso. b) Cual es la frecuencia m axima de respuesta del frecuenc metro? Por qu e? La m axima respuesta, segun el temporizador empleado -de 16 bits- ser a de 65535 Hz. Eso con el programa tal cual est a. Segun la hoja de datos del microcontrolador el periodo de entrada m nimo est a -segun versiones- en torno a los 60 ns. del tacometro? c) Como mejorar as la resolucion Y la frecuencia m axima? La resoluci on se podr a mejorar muestreando una mayor cantidad de tiempo y la frecuencia m axima se podr a aumentar encadenando los desbordamientos de TMR1 por interrupciones en otro contador.

272

Soluci on

Cap tulo 27 Robot Rastreador


27.1. Solucion
27.1.1. Se pide
Para conseguir hacer moverse al robot necesitamos conocer el sentido de giro de ambos motores para conseguir el movimiento deseado: ACCION Sentido Motor 1 Sentido Motor 2 Habilitaciones Avanzar Horario Antihorario Activas Retroceder Antihorario Horario Activas Giro derecha Antihorario Antihorario Activas Giro izquierda Horario Horario Activas Parada Desactivadas El problema del robot rastreador consiste en que sea capaz de avanzar siguiendo una l nea negra sobre fondo blanco (o blanca sobre fondo negro) y que adem as lo haga lo m as r apido posible. Para ello disponemos de dos sensores situados estrat egicamente de ambas ruedas. El algoritmo a seguir, por tanto, deber en la l nea de separacion a hacer que ambos sensores dieran el valor de lectura coincidente con el color de la l nea. El sensor dar a un 1 logico si la l nea es negra y 0 si es blanca.

La estrategia: Actual Anterior  XX XX XX ACCIN Avanza Gira izquierda Gira derecha  Avanza   Retrocede   Gira izquierda   Gira derecha

Avanza

Retrocede

Giro derecha
Se pide
273

274

Soluci on

el software de acuerdo con la estrategia indiMontar el circuito necesario y disenar cada. El programa: Listado 27.1: EX/ROBOT/ROBOT LINEA.C
2

#include <pic.h> #include "binario.h" __CONFIG(WDTDIS & XT & UNPROTECT & PWRTDIS & LVPDIS & BORDIS & DEBUGDIS & DPROT );

12

// Motor1,Motor2 //0,0,(Enable,Positivo,Negativo),(Enable,Positivo,Negativo) #define DERECHA B00110110 #define IZQUIERDA B00101101 #define RETROCEDE B00110101 #define AVANZA B00101110 #define PARADA B00000000 // Estados posibles #define DENTRO B00000011 #define FUERA B00000000 #define SALEIZQ B00000010 #define SALEDER B00000001 // Sensores #define SEN_IZQ RC0 #define SEN_DER RC1 #define ARRANQUE RC2 // En robot es activo en baja void main() { unsigned char Estado, EstadoAnterior=DENTRO; unsigned char Parado = 1; volatile unsigned int r; PORTB = 0; TRISB = 0; // PORTB salidas TRISC = B10111111; // PORTC entradas, excepto RC6/TX salida while(1) { if(Parado) { while( ARRANQUE); while(!ARRANQUE); // Espero a soltar Parado = 0; } else if(!ARRANQUE) { while(!ARRANQUE); for(r=0;r<10000;r++) ; PORTB = PARADA; Parado = 1; } if(!Parado) {

17

22

27

32

37

42

47

52

Cap tulo 27. Robot Rastreador


Estado = PORTC & 0x03; switch(Estado) { case DENTRO: PORTB = AVANZA; break; case FUERA: switch(EstadoAnterior) { case FUERA: PORTB = AVANZA; break; case DENTRO: PORTB = RETROCEDE; break; case SALEIZQ: PORTB = DERECHA; break; case SALEDER: PORTB = IZQUIERDA; break; } break; case SALEIZQ: PORTB = DERECHA; break; case SALEDER: PORTB = IZQUIERDA; break; } // Fin del switch EstadoAnterior = Estado; } // Fin del if } // Fin del while }

275

57

62

67

72

77

82

87

27.1.2. Cuestiones
a) Funciona igual el algoritmo si el motor se alimenta a 5V o a 12V? Por qu e? Evidentemente la respuesta de los motores a 12 V es m as r apida que a 5V. Nuestro algoritmo est a muestreando con una determinada cadencia (frecuencia de muestreo), de manera que responder a peor para tensiones altas. b) Como podr as mejorar la abilidad del algoritmo? Software? Sensores? Para mejorar la abilidad podr amos: 1. Hacer que el microcontrolador funcione m as r apido. De esta manera la frecuencia de muestreo ser a mayor y la respuesta de nuestro sistema ser a m as r apida. Cuidado por que el sistema controlado podr a volverse inestable. 2. Aumentar el numero de sensores y situarlos estrat egicamente para obtener con m as antelaci on lo que va a ocurrir. 3. Controlar la velocidad de giro de los motores para un mejor control de la inercia de nuestro sistema. 4. Y muchas otras m as cosas...

276

Soluci on

Cap tulo 28 Comunicaciones


28.1. Solucion
28.1.1. Se pide
Se muestra el programa y un organigrama. Programas Listado 28.1: EX/ROBOT COMM/ROBOT SERIE.c
2

/////////////////////////////////////////////////////////// // ROBOT SERIE /////////////////////////////////////////////////////////// #include <pic.h> #include "binario.h" __CONFIG(WDTDIS & XT & UNPROTECT & PWRTDIS & LVPDIS & BORDIS);

12

// Motor1,Motor2 //0,0,(Enable,Positivo,Negativo),(Enable,Positivo,Negativo) #define DERECHA B00110110 #define IZQUIERDA B00101101 #define RETROCEDE B00110101 #define AVANZA B00101110 #define PARADA B00000000 // Estados posibles #define DENTRO B00000011 #define FUERA B00000000 #define SALEIZQ B00000010 #define SALEDER B00000001 // Sensores #define SEN_IZQ #define SEN_DER #define ARRANQUE RC0 RC1 RC2

17

22

27

// Comandos recibidos // Codifico estos comandos as para la transmisi on inalambrica, que // requiere que el promedio de valores sea constante
32

#define cAVANZA #define cRETROCEDE

B00110011 B01010101

// A en el PC // Z en el PC

277

278
#define #define #define #define cIZQUIERDA cDERECHA cPARADA cAUTO B11001100 B01100110 B10011001 B10100101 // // // // O P Q en en en en el el el el PC PC PC PC

Soluci on

37

42

47

// Para depuraci on /* #define cAVANZA A // A en el PC #define cRETROCEDE Z // Z en el PC #define cIZQUIERDA O // O en el PC #define cDERECHA P // P en el PC #define cPARADA Q // Q en el PC #define cAUTO // en el PC */ void main() { unsigned char Estado, EstadoAnterior=DENTRO; unsigned char Parado = 1; PORTB TRISB TRISC TXSTA = = = = 0; 0; // PORTB salidas B10111111; // PORTC entradas, excepto RC6/TX salida B00100100; // CSRC = 0, en modo asincrono, no importa // TX9 = 0, 8 bits // TXEN = 1, Transmisi on activada // SYNC = 0, Modo Asincrono // 0, reservado // BRGH = 1, Alta velocidad // TRMT = 0, registro de transmisi on, TSR, no vac o // TX9D = 0, no importa // // // // // // // 1200 bps TXSTA.BRGH=1 SPBRG=25 F = 4MHz / (16*(25+1)) = 9615.38 baudios % Error = 0.16 % Ojo! en la simulaci on con Proteus el VTerm hay que ponerlo a 2400 baudios ? para que funcione !!

52

57

62

SPBRG = 207;
67

72

// Para la comunicaci on inalambrica m aximo 1200 bps // TXSTA.BRGH=1 // SPBRG=207


77

82

RCSTA = B10010000; // SPEN // RX9 // SREN // CREN // ADDEN // FERR // OERR // RX9D

= = = = = = = =

1, 0, 0, 1, 0, 0, 0, 0,

Activa la USART 8 bits en as ncrono no influye Recepci on continua activada Desactiva detecci on de direcci on Sin error de trama Sin error de sobreescritura no importa

87

92

while(1) // Respuesta a comandos { while(!RCIF); // Espero mientras no haya comando switch(RCREG) { case cAVANZA: PORTB = AVANZA; break;

Cap tulo 28. Comunicaciones


case cRETROCEDE: PORTB = RETROCEDE; break; case cIZQUIERDA: PORTB = IZQUIERDA; break; case cDERECHA: PORTB = DERECHA; break; case cPARADA: PORTB = PARADA; break; case cAUTO: goto Automatico; } }
112

279

97

102

107

// El goto no est a recomendado en C

117

Automatico: while(1) // Respuesta autom atica { if(Parado) { while(!ARRANQUE); while( ARRANQUE); // Espero a soltar Parado = 0; } if(ARRANQUE) { while( ARRANQUE); PORTB = PARADA; Parado = 1; } if(!Parado) { Estado = PORTC & 0x03; switch(Estado) { case DENTRO: PORTB = AVANZA; break; case FUERA: switch(EstadoAnterior) { case FUERA: PORTB = AVANZA; break; case DENTRO: PORTB = RETROCEDE; break; case SALEIZQ: PORTB = DERECHA; break; case SALEDER: PORTB = IZQUIERDA; break; } break; case SALEIZQ: PORTB = DERECHA; break;

122

127

132

137

142

147

152

157

280
case SALEDER: PORTB = IZQUIERDA; break;
162

Soluci on

} EstadoAnterior = Estado; } } }

Cap tulo 28. Comunicaciones Organigrama


Robot rastreador. Control remoto

281

 

   

  " #   !  $  

 % &'# () 0 " 1  2#   3 4 

)56 76 ' 4 

 % &'# ) 0

" 89 # @ ! 4

8A0A@

`a

No
 0 U V `a  " #  ! ! ! `a  VW'

8ABA@

8AA@

#

8AA@

`a

9 # X ! !

8ACA@

`a

 #

D EF G H I QR P

bc

 " # 0' " 1Y "

(S5S5

7 T 

282

Soluci on

28.1.2. Cuestiones
...

Cap tulo 29 LCD Gr aco


29.1. Solucion
29.1.1. Se pide
Montaje basado en PIC que nos permita dibujar en el display gr aco. Listado 29.1: EX/GRAFICO/SOFTWARE/MAIN.c
//------------------------------------------------------------------------// Demostraci on para LCD Gr afico 12864H (controlador S6B0724) //------------------------------------------------------------------------#include <pic.h> #include "binario.h" #include "lcdgraph.h" unsigned char font; //<= No se por que pero es necesario const char MSG[]={"Hola 123"};
10

int main(int argc, char *argv[]) { unsigned char x,y,i; volatile unsigned int j;
15

TRISB = 0; TRISC = B10000000; lcd_init(); lcd_erase(0x00); lcd_put_char_at(*,8*4,60); lcd_print( MSG,0,8);


25

// Configuro las salidas y entradas

20

lcd_box(0,0,62,127); lcd_circle(31,63,31,0xFF); while(1) { PORTC=PORTC (1<<5); for(j=0;j<30000;j++); } }

30

Listado 29.2: EX/GRAFICO/SOFTWARE/LCDGRAPH.C


///////////////////////////////////////////////////////////

283

284
2

Soluci on

// lcdgraph.c /////////////////////////////////////////////////////////// #include <pic.h> #include "lcdgraph.h" #include "binario.h" #include "font.h" //------------------------------------------------------------------------void lcd_init(void) { int i; TRISB = 0; // initialize the port control lines to the LCD module LCD_RST_ON; // set RST signal high off output LCD_CS_ON; // set chip select high off output LCD_RS_OFF; // set the CD line low as output LCD_E_OFF; LCD_RW_OFF; // reset the LCD controller chip LCD_RST_OFF; // set the reset line low for(i=0; i<10000; i++); // delay for the reset time LCD_RST_ON; // release reset to back high // program the controller operational state lcd_out_ctl(LCD_SET_ADC_NOR); // set ADC normal lcd_out_ctl(LCD_SET_SHL_REV); // set SHL reversed lcd_out_ctl(LCD_SET_BIAS_1); // set for the low bias mode lcd_out_ctl(LCD_PWR_CTL+4); // turn on the VC bit for(i=0; i<5000; i++); // delay for the converter on lcd_out_ctl(LCD_PWR_CTL+6); // now turn on VC+VR bits for(i=0; i<5000; i++); // delay for the regulator on lcd_out_ctl(LCD_PWR_CTL+7); // now turn on the VC+VR+VF lcd_out_ctl(LCD_REG_RESISTOR+4); // set default resistor ratio

12

17

22

27

32

37

lcd_out_ctl(LCD_REF_VOLT_MODE); // prime for the reference voltage lcd_out_ctl(LCD_REF_VOLT_REG+20);// set default reference voltage select for(i=0; i<5000; i++); lcd_out_ctl(LCD_DISP_ON); // delay for power stabilize // put the display on

42

47

52

lcd_out_ctl(LCD_SET_LINE+0); // set line for row 0 of display //lcd_out_ctl(LCD_SET_PAGE+0); // set page 0 //lcd_out_ctl(LCD_SET_COL_HI+0); // set column 0 //lcd_out_ctl(LCD_SET_COL_LO+0); lcd_out_ctl(LCD_SET_MODIFY); // Que al leer no incremente } //------------------------------------------------------------------------// Env a DATO void lcd_out_dat(unsigned char dat) { LCD_RW_OFF; LCD_RS_ON; // select register for data port LCD_CS_OFF; LCD_DATO = dat; LCD_E_ON; LCD_Delay; LCD_E_OFF; // enable interface via chip select

57

62

Cap tulo 29. LCD Gr aco

285

67

LCD_CS_ON; } //------------------------------------------------------------------------// Enva COMANDO void lcd_out_ctl(unsigned char dat) { LCD_RW_OFF; LCD_RS_OFF; // select register for data port LCD_CS_OFF; LCD_DATO = dat; LCD_E_ON; LCD_Delay; LCD_E_OFF; LCD_CS_ON; } //------------------------------------------------------------------------// Lee DATO unsigned char lcd_in_dat() { unsigned char dat; LCD_RW_ON; LCD_RS_ON; // select register for data port LCD_CS_OFF; TRISB=0xFF; // enable interface via chip select // enable interface via chip select

72

77

82

87

92

LCD_E_ON; LCD_Delay; dat = LCD_DATO; LCD_E_OFF; TRISB=0x00; LCD_CS_ON; return dat;


102

97

107

} //------------------------------------------------------------------------/* // Lee COMANDO unsigned char lcd_in_ctl() { unsigned char dat; LCD_RW_ON; LCD_RS_OFF; LCD_CS_OFF; TRISB=0xFF; LCD_E_ON; LCD_Delay; // enable interface via chip select

112

117

dat = LCD_DATO; LCD_E_OFF; TRISB=0x00; LCD_CS_ON; return dat; } */

122

286

Soluci on

127

//------------------------------------------------------------------------void lcd_erase(unsigned char dato) { unsigned char p; unsigned char i; for(p=0; p<9; p++) { lcd_out_ctl(LCD_SET_PAGE+p); // set page lcd_out_ctl(LCD_SET_COL_HI+0); // set column 0 lcd_out_ctl(LCD_SET_COL_LO+0); for(i=0; i<132; i++) lcd_out_dat(dato); // clear the data } } //------------------------------------------------------------------------// Pinta punto void lcd_put_pixel(unsigned char x, unsigned char y) { unsigned char dato; lcd_out_ctl(LCD_SET_PAGE+(x>>3)); // Selecciona la pagina (eje corto) lcd_out_ctl(LCD_SET_COL_HI+(y>>4)); // Selecciona la columna (eje largo) lcd_out_ctl(LCD_SET_COL_LO+(y&15)); dato = lcd_in_dat(); dato = lcd_in_dat(); // Lectura tonta // Lee el dato

132

137

142

147

152

157

lcd_out_dat(dato | (1<<(x&0x07)) ); // A nade el pixel } //------------------------------------------------------------------------void lcd_line(signed char X1,signed char Y1, signed char X2, signed char Y2) { // Bersenhams algorithm int Dx,Dy,incx,incy,xerr,yerr; unsigned char distance,t; Dx = X2 - X1 ; Dy = Y2 - Y1 ; if ( Dx > 0 ) incx = 1; else if (Dx == 0 ) incx = 0; else incx = -1; if ( Dy > 0 ) else if (Dy == 0) else incy = 1;

162

167

172

incy = 0; incy = -1;

if(Dy<0) Dy = - Dy; if(Dx<0) Dx = - Dx;


177

if ( Dx > Dy ) distance = Dx ; else distance = Dy ; yerr = 0; xerr = 0; for(t=0;t<=distance+1;t++) { lcd_put_pixel(X1,Y1); xerr += Dx ; yerr += Dy ;

182

187

Cap tulo 29. LCD Gr aco

287

192

197

202

207

212

217

222

if ( xerr > distance ) { xerr -= distance ; X1 += incx ; if ( X1 < 0 ) X1 = 0 ; // if ( X1 > XMAX ) X1 = XMAX ; } if(yerr > distance ) { yerr -= distance ; Y1 += incy; if ( Y1 < 0 ) Y1 = 0 ; // if ( Y1 > YMAX ) Y1 = YMAX ; } } } //------------------------------------------------------------------------void lcd_box(unsigned char x1, unsigned char y1, unsigned char x2, unsigned char y2) { lcd_line(x1,y1,x2,y1); lcd_line(x2,y1,x2,y2); lcd_line(x2,y2,x1,y2); lcd_line(x1,y2,x1,y1); } //------------------------------------------------------------------------// Algoritmo de Bresenham para circulos // 217 palabras de memoria de programa void lcd_circle(int xc, int yc, int radius, unsigned char cuadrantes) { // Cuadrantes . Si quieres el circulo completo 0xFF // \0x20|0x10/ // \ | / // 0x80\ | / 0x40 //----------------// 0x08/ | \ 0x04 // / | \ // /0x02|0x01\ #define ANCHO 64 #define ALTO 128 signed char x, y, p, a,b, c, d, e, f, g, h; int max=(ANCHO>ALTO)?ANCHO:ALTO;

227

232

if( (xc-radius < 0) || (xc+radius > max) ||(yc-radius < 0) || (yc+radius > max) ) return; x = 0; y = radius; p = 3 - (radius << 1); while (x <= y) { a = xc + x; //8 pixels calculados gracias a la simetria b = yc + y; c = xc - x; d = yc - y; e = xc + y; f = yc + x; g = xc - y; h = yc - x;

237

242

247

288
if(cuadrantes&0x01) lcd_put_pixel(a,b); if(cuadrantes&0x02) lcd_put_pixel(c,d); if(cuadrantes&0x04) lcd_put_pixel(e,f); if(cuadrantes&0x08) lcd_put_pixel(g,f); if(x>0) // evitamos pintar pixels en la misma posicion que otros { if(cuadrantes&0x10) lcd_put_pixel(a,d); if(cuadrantes&0x20) lcd_put_pixel(c,b); if(cuadrantes&0x40) lcd_put_pixel(e,h); if(cuadrantes&0x80) lcd_put_pixel(g,h); } if(p < 0) p += (x++ << 2) + 6; else p += ((x++ - y--) << 2) + 10;

Soluci on

252

257

262

} return; } //------------------------------------------------------------------------267

void lcd_put_char_at(char a, char x, unsigned char y) { // 0..63 unsigned char i;


272

0..127

lcd_out_ctl(LCD_SET_PAGE+((63-x)>>3)); // Selecciona la p gina (eje corto) lcd_out_ctl(LCD_SET_COL_HI+(y>>4)); // Selecciona la columna (eje largo) lcd_out_ctl(LCD_SET_COL_LO+(y&15)); if( (a<32)||(a>128)) return; for(i=0;i<8;i++) lcd_out_dat(font2[(a-32)*8+i]); } //------------------------------------------------------------------------void lcd_print(const char *txt, char x, unsigned char y) { int t=0; while(txt[t]) { lcd_put_char_at(txt[t++],x,y); x+=8; } } //-------------------------------------------------------------------------

277

282

287

Listado 29.3: EX/GRAFICO/SOFTWARE/LCDGRAPH.H


#include <pic.h> //------------------------------------------------------------------------#define LCD_DATO PORTB #define CS RC0 #define RST RC1 #define RS RC2 #define RW RC3 #define EN RC4 #define #define #define #define #define #define #define LCD_RST_ON LCD_RST_OFF LCD_CS_ON LCD_CS_OFF LCD_RS_ON LCD_RS_OFF LCD_E_ON RST=1 RST=0 CS=1 CS=0 RS=1 RS=0 EN=1

14

Cap tulo 29. LCD Gr aco


#define LCD_E_OFF #define LCD_RW_ON #define LCD_RW_OFF #define LCD_Delay
24

289
EN=0 RW=1 RW=0 asm("nop");asm("nop");

19

29

34

39

44

49

54

//------------------------------------------------------------------------/* command function equates for S6B0724 LCD Display Controller */ #define LCD_DISP_OFF 0xAE /* turn LCD panel OFF */ #define LCD_DISP_ON 0xAF /* turn LCD panel ON */ #define LCD_SET_LINE 0x40 /* set line for COM0 (6 lsbs = ST5:ST4:ST3:ST2:ST1: #define LCD_SET_PAGE 0xB0 /* set page address (4 lsbs = P3:P2:P1:P0) */ #define LCD_SET_COL_HI 0x10 /* set column address (4 lsbs = Y7:Y6:Y5:Y4) */ #define LCD_SET_COL_LO 0x00 /* set column address (4 lsbs = Y3:Y2:Y1:Y0) */ #define LCD_SET_ADC_NOR 0xA0 /* ADC set for normal direction */ #define LCD_SET_ADC_REV 0xA1 /* ADC set for reverse direction */ #define LCD_DISP_NOR 0xA6 /* normal pixel display */ #define LCD_DISP_REV 0xA7 /* reverse pixel display */ #define LCD_EON_OFF 0xA4 /* normal display mode */ #define LCD_EON_ON 0xA5 /* entire dsplay on */ #define LCD_SET_BIAS_0 0xA2 /* set LCD bias select to 0 */ #define LCD_SET_BIAS_1 0xA3 /* set LCD bias select to 1 */ #define LCD_SET_MODIFY 0xE0 /* set modfy read mode */ #define LCD_CLR_MODIFY 0xEE /* clear modify read mode */ #define LCD_RESET 0xE2 /* soft reset command */ #define LCD_SET_SHL_NOR 0xC0 /* set COM direction normal */ #define LCD_SET_SHL_REV 0xC8 /* set COM direction reverse */ #define LCD_PWR_CTL 0x28 /* set power control (3 lsbs = VC:VR:VF) */ #define LCD_REG_RESISTOR 0x20 /* set regulator resistor (3 lsbs = R2:R1:R0) */ #define LCD_REF_VOLT_MODE 0x81 /* set ref. volt. mode (first of dual command) */ #define LCD_REF_VOLT_REG 0x00 /* set ref. volt. reg. (6 lsbs = SV5:SV4:SV3:SV2:SV #define LCD_ST_IND_MODE_0 0xAC /* set static indicator mode to 0 */ #define LCD_ST_IND_MODE_1 0xAD /* set static indicator mode to 1 */ #define LCD_ST_IND_REG 0x00 /* set static indicator reg. (2 lsbs = S1:S0) */ #define LCD_NOP 0xE3 /* LCD controller NOP command */ #define LCD_TEST_CMD_1 0xF0 /* LCD Test Instruction 1.. do not use */ #define LCD_TEST_CMD_2 0x90 /* LCD Test Instruction 2.. do not use */

59

64

69

74

/* LCD screen and bitmap image array consants */ #define X_BYTES 128 #define Y_BYTES 8 #define SCRN_LEFT 0 #define SCRN_TOP 0 #define SCRN_RIGHT 127 #define SCRN_BOTTOM 63 //------------------------------------------------------------------------extern void lcd_init(void); extern void lcd_out_dat(unsigned char dat); extern void lcd_out_ctl(unsigned char dat); void lcd_erase(unsigned char dato); void lcd_put_pixel(unsigned char x, unsigned char y); void lcd_line(signed char X1,signed char Y1, signed char X2, signed char Y2); void lcd_circle(int xc, int yc, int radius, unsigned char cuadrantes); void lcd_box(unsigned char x1,unsigned char y1, unsigned char x2, unsigned char y2) void lcd_put_char_at(char a, char x, unsigned char y); void lcd_print(const char *txt, char x, unsigned char y); //-------------------------------------------------------------------------

29.1.2. Cuestiones

290

Soluci on

Parte IV Ap endices

291

Ap endice A Ficheros cabecera


Son los cheros donde se denen los nombres de los registros y sus campos para resulte mucho m que la programacion as sencilla y no tengamos que memorizar posi ciones de memoria o de bits. Tan solo deberemos recordar o consultar su mnemonico y utilizarlo.

A.1. Fichero de cabecera en ensamblador: P16F877.inc


Cuando escribamos programas en ensamblador deberemos incluir el siguiente chero de deniciones (si el microcontrolador es un 16F877, claro est a): Listado A.1: EX/INC/P16F877.INC
1

LIST ; P16F877.INC Standard Header File, Version 1.00 NOLIST

Microchip Technology, Inc.

; This header file defines configurations, registers, and other useful bits of ; information for the PIC16F877 microcontroller. These names are taken to match ; the data sheets as closely as possible. ; Note that the processor must be selected before this file is ; included. The processor may be selected the following ways:

11

16

; ; ; ; ;

1. Command line switch: C:\ MPASM MYFILE.ASM /PIC16F877 2. LIST directive in the source file LIST P=PIC16F877 3. Processor Type entry in the MPASM full-screen interface

21

;========================================================================== ; ; Revision History ; ;========================================================================== ;Rev: Date: Reason:

26

;1.12 ; ;1.00

01/12/00 Changed some bit names, a register name, configuration bits to match datasheet (DS30292B) 08/07/98 Initial Release

31

;========================================================================== ; ; Verify Processor ; ;========================================================================== IFNDEF __16F877 MESSG "Processor-header file mismatch. ENDIF Verify selected processor."

36

;==========================================================================

293

294
41

Fichero de cabecera en ensamblador: P16F877.inc

; ; Register Definitions ; ;========================================================================== W F EQU EQU H0000 H0001

46

;----- Register Files-----------------------------------------------------51

56

61

66

71

76

81

INDF TMR0 PCL STATUS FSR PORTA PORTB PORTC PORTD PORTE PCLATH INTCON PIR1 PIR2 TMR1L TMR1H T1CON TMR2 T2CON SSPBUF SSPCON CCPR1L CCPR1H CCP1CON RCSTA TXREG RCREG CCPR2L CCPR2H CCP2CON ADRESH ADCON0 OPTION_REG TRISA TRISB TRISC TRISD TRISE PIE1 PIE2 PCON SSPCON2 PR2 SSPADD SSPSTAT TXSTA SPBRG ADRESL ADCON1 EEDATA EEADR EEDATH EEADRH

EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU

H0000 H0001 H0002 H0003 H0004 H0005 H0006 H0007 H0008 H0009 H000A H000B H000C H000D H000E H000F H0010 H0011 H0012 H0013 H0014 H0015 H0016 H0017 H0018 H0019 H001A H001B H001C H001D H001E H001F H0081 H0085 H0086 H0087 H0088 H0089 H008C H008D H008E H0091 H0092 H0093 H0094 H0098 H0099 H009E H009F H010C H010D H010E H010F H018C H018D

86

91

96

101

106

EECON1 EECON2
111

;----- STATUS Bits -------------------------------------------------------IRP RP1 RP0 NOT_TO NOT_PD Z DC EQU EQU EQU EQU EQU EQU EQU H0007 H0006 H0005 H0004 H0003 H0002 H0001

116

Cap tulo A. Ficheros cabecera


C
121

295
EQU H0000

;----- INTCON Bits -------------------------------------------------------GIE PEIE T0IE INTE RBIE T0IF INTF RBIF EQU EQU EQU EQU EQU EQU EQU EQU H0007 H0006 H0005 H0004 H0003 H0002 H0001 H0000

126

131

;----- PIR1 Bits ---------------------------------------------------------PSPIF ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF EQU EQU EQU EQU EQU EQU EQU EQU H0007 H0006 H0005 H0004 H0003 H0002 H0001 H0000

136

141

;----- PIR2 Bits ---------------------------------------------------------146

EEIF BCLIF CCP2IF

EQU EQU EQU

H0004 H0003 H0000

;----- T1CON Bits --------------------------------------------------------151

156

T1CKPS1 T1CKPS0 T1OSCEN NOT_T1SYNC T1INSYNC T1SYNC TMR1CS TMR1ON

EQU EQU EQU EQU EQU EQU EQU EQU

H0005 H0004 H0003 H0002 H0002 H0002 H0001 H0000

; Backward compatibility only

;----- T2CON Bits --------------------------------------------------------161

166

TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON T2CKPS1 T2CKPS0

EQU EQU EQU EQU EQU EQU EQU

H0006 H0005 H0004 H0003 H0002 H0001 H0000

;----- SSPCON Bits -------------------------------------------------------171

176

WCOL SSPOV SSPEN CKP SSPM3 SSPM2 SSPM1 SSPM0

EQU EQU EQU EQU EQU EQU EQU EQU

H0007 H0006 H0005 H0004 H0003 H0002 H0001 H0000

181

;----- CCP1CON Bits ------------------------------------------------------CCP1X CCP1Y CCP1M3 CCP1M2 CCP1M1 CCP1M0 EQU EQU EQU EQU EQU EQU H0005 H0004 H0003 H0002 H0001 H0000

186

;----- RCSTA Bits --------------------------------------------------------191

196

SPEN RX9 RC9 NOT_RC8 RC8_9

EQU EQU EQU EQU EQU

H0007 H0006 H0006 H0006 H0006

; Backward compatibility only ; Backward compatibility only ; Backward compatibility only

296
SREN CREN ADDEN FERR OERR RX9D RCD8 EQU EQU EQU EQU EQU EQU EQU

Fichero de cabecera en ensamblador: P16F877.inc


H0005 H0004 H0003 H0002 H0001 H0000 H0000

201

; Backward compatibility only

;----- CCP2CON Bits ------------------------------------------------------206

211

CCP2X CCP2Y CCP2M3 CCP2M2 CCP2M1 CCP2M0

EQU EQU EQU EQU EQU EQU

H0005 H0004 H0003 H0002 H0001 H0000

;----- ADCON0 Bits -------------------------------------------------------216

221

ADCS1 ADCS0 CHS2 CHS1 CHS0 GO NOT_DONE GO_DONE ADON

EQU EQU EQU EQU EQU EQU EQU EQU EQU

H0007 H0006 H0005 H0004 H0003 H0002 H0002 H0002 H0000

226

;----- OPTION_REG Bits ----------------------------------------------------NOT_RBPU INTEDG T0CS T0SE PSA PS2 PS1 PS0 EQU EQU EQU EQU EQU EQU EQU EQU H0007 H0006 H0005 H0004 H0003 H0002 H0001 H0000

231

236

;----- TRISE Bits --------------------------------------------------------IBF OBF IBOV PSPMODE TRISE2 TRISE1 TRISE0 EQU EQU EQU EQU EQU EQU EQU H0007 H0006 H0005 H0004 H0002 H0001 H0000

241

246

;----- PIE1 Bits ---------------------------------------------------------PSPIE ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE EQU EQU EQU EQU EQU EQU EQU EQU H0007 H0006 H0005 H0004 H0003 H0002 H0001 H0000

251

256

;----- PIE2 Bits ---------------------------------------------------------261

EEIE BCLIE CCP2IE

EQU EQU EQU

H0004 H0003 H0000

;----- PCON Bits ---------------------------------------------------------266

NOT_POR NOT_BO NOT_BOR

EQU EQU EQU

H0001 H0000 H0000

;----- SSPCON2 Bits -------------------------------------------------------271

GCEN ACKSTAT ACKDT

EQU EQU EQU

H0007 H0006 H0005

Cap tulo A. Ficheros cabecera


ACKEN RCEN PEN RSEN SEN EQU EQU EQU EQU EQU H0004 H0003 H0002 H0001 H0000

297

276

281

;----- SSPSTAT Bits ------------------------------------------------------SMP CKE D I2C_DATA NOT_A NOT_ADDRESS D_A DATA_ADDRESS P I2C_STOP S I2C_START R I2C_READ NOT_W NOT_WRITE R_W READ_WRITE UA BF EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU H0007 H0006 H0005 H0005 H0005 H0005 H0005 H0005 H0004 H0004 H0003 H0003 H0002 H0002 H0002 H0002 H0002 H0002 H0001 H0000

286

291

296

301

;----- TXSTA Bits --------------------------------------------------------306

311

CSRC TX9 NOT_TX8 TX8_9 TXEN SYNC BRGH TRMT TX9D TXD8

EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU

H0007 H0006 H0006 H0006 H0005 H0004 H0002 H0001 H0000 H0000

; Backward compatibility only ; Backward compatibility only

; Backward compatibility only

316

;----- ADCON1 Bits -------------------------------------------------------ADFM PCFG3 PCFG2 PCFG1 PCFG0 EQU EQU EQU EQU EQU H0007 H0003 H0002 H0001 H0000

321

;----- EECON1 Bits -------------------------------------------------------326

331

EEPGD WRERR WREN WR RD

EQU EQU EQU EQU EQU

H0007 H0003 H0002 H0001 H0000

336

;========================================================================== ; ; RAM Definition ; ;========================================================================== __MAXRAM __BADRAM __BADRAM __BADRAM H1FF H8F-H90, H95-H97, H9A-H9D H105, H107-H109 H185, H187-H189, H18E-H18F

341

346

;========================================================================== ; ; Configuration Bits ; ;========================================================================== _CP_ALL _CP_HALF _CP_UPPER_256 EQU EQU EQU H0FCF H1FDF H2FEF

351

298
_CP_OFF _DEBUG_ON _DEBUG_OFF _WRT_ENABLE_ON _WRT_ENABLE_OFF _CPD_ON _CPD_OFF _LVP_ON _LVP_OFF _BODEN_ON _BODEN_OFF _PWRTE_OFF _PWRTE_ON _WDT_ON _WDT_OFF _LP_OSC _XT_OSC _HS_OSC _RC_OSC LIST EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU H3FFF H37FF H3FFF H3FFF H3DFF H3EFF H3FFF H3FFF H3F7F H3FFF H3FBF H3FFF H3FF7 H3FFF H3FFB H3FFC H3FFD H3FFE H3FFF

Fichero de cabecera en lenguaje C: pic.h

356

361

366

371

A.2. Fichero de cabecera en lenguaje C: pic.h


las opciones de compilacion otro chero a incluir Este chero seleccionar a segun que en el caso de los micros estudiados ser a: Listado A.2: EX/INC/pic1687x.h
2

/* * * * * * * * * * */

Header file for the Microchip PIC 16F870 PIC 16F871 PIC 16F872 chip PIC 16F873 chip PIC 16F874 chip PIC 16F876 chip PIC 16F877 chip Midrange Microcontroller || defined(_16F877) || defined(_16F871)

12

#if defined(_16F874) #define __PINS_40 #endif


17

22

27

32

37

42

static volatile unsigned static volatile unsigned static volatile unsigned static volatile unsigned static unsigned static volatile unsigned static volatile unsigned static volatile unsigned #ifdef __PINS_40 static volatile unsigned static volatile unsigned #endif static unsigned static volatile unsigned static volatile unsigned static volatile unsigned static volatile unsigned static volatile unsigned static volatile unsigned static volatile unsigned static volatile unsigned #if !defined(_16F870) && static volatile unsigned static volatile unsigned #endif static volatile unsigned static volatile unsigned static volatile unsigned

char char char char char char char char char char

INDF @ 0x00; TMR0 @ 0x01; PCL @ 0x02; STATUS @ 0x03; FSR @ 0x04; PORTA @ 0x05; PORTB @ 0x06; PORTC @ 0x07; PORTD PORTE @ 0x08; @ 0x09;

char PCLATH @ 0x0A; char INTCON @ 0x0B; char PIR1 @ 0x0C; char PIR2 @ 0x0D; char TMR1L @ 0x0E; @ 0x0F; char TMR1H char T1CON @ 0x10; char TMR2 @ 0x11; char T2CON @ 0x12; !defined(_16F871) char SSPBUF @ 0x13; char SSPCON @ 0x14; char char char CCPR1L @ 0x15; CCPR1H @ 0x16; CCP1CON @ 0x17;

Cap tulo A. Ficheros cabecera


#ifndef _16F872 static volatile unsigned static volatile unsigned static volatile unsigned #if !defined(_16F870) && static volatile unsigned static volatile unsigned static volatile unsigned #endif #endif static volatile unsigned static volatile unsigned /* bank 1 registers */ static unsigned static volatile unsigned static volatile unsigned static volatile unsigned #ifdef __PINS_40 static volatile unsigned static volatile unsigned #endif static volatile unsigned static volatile unsigned static volatile unsigned #if !defined(_16F870) && static volatile unsigned #endif static volatile unsigned #if !defined(_16F870) && static volatile unsigned static volatile unsigned #endif #ifndef _16F872 static volatile unsigned static volatile unsigned #endif static volatile unsigned static volatile unsigned /* bank 2 registers */ static volatile unsigned static volatile unsigned static volatile unsigned static volatile unsigned

299

47

52

char RCSTA @ 0x18; char TXREG @ 0x19; char RCREG @ 0x1A; !defined(_16F871) char CCPR2L @ 0x1B; char CCPR2H @ 0x1C; char CCP2CON @ 0x1D; char char char char char char ADRESH ADCON0 bank1 bank1 bank1 bank1 @ 0x1E; @ 0x1F; @ @ @ @ 0x81; 0x85; 0x86; 0x87;

57

62

OPTION TRISA TRISB TRISC

char bank1 TRISD char bank1 TRISE char bank1 PIE1 char bank1 PIE2 char bank1 PCON !defined(_16F871) char bank1 SSPCON2

@ 0x88; @ 0x89; @ 0x8C; @ 0x8D; @ 0x8E; @ 0x91;

67

72

char bank1 PR2 @ 0x92; !defined(_16F871) char bank1 SSPADD @ 0x93; char bank1 SSPSTAT @ 0x94; char bank1 TXSTA char bank1 SPBRG char bank1 ADRESL char bank1 ADCON1 char char char char bank2 bank2 bank2 bank2 EEDATA EEADR EEDATH EEADRH @ 0x98; @ 0x99; @ 0x9E; @ 0x9F; @ @ @ @ 0x10C; 0x10D; 0x10E; 0x10F;

77

82

87

92

/* bank 3 registers */ static volatile unsigned char bank3 EECON1 static volatile unsigned char bank3 EECON2 /* STATUS bits static volatile static volatile static volatile static volatile static volatile static volatile static volatile static volatile /* static static static static static static /* static static static static static static static static */ bit bit bit bit bit bit bit bit

@ 0x18C; @ 0x18D;

97

102

IRP @ (unsigned)&STATUS*8+7; RP1 @ (unsigned)&STATUS*8+6; RP0 @ (unsigned)&STATUS*8+5; TO @ (unsigned)&STATUS*8+4; PD @ (unsigned)&STATUS*8+3; ZERO @ (unsigned)&STATUS*8+2; DC @ (unsigned)&STATUS*8+1; CARRY @ (unsigned)&STATUS*8+0; RA5 RA4 RA3 RA2 RA1 RA0 RB7 RB6 RB5 RB4 RB3 RB2 RB1 RB0 */ @ (unsigned)&PORTA*8+5; @ (unsigned)&PORTA*8+4; @ (unsigned)&PORTA*8+3; @ (unsigned)&PORTA*8+2; @ (unsigned)&PORTA*8+1; @ (unsigned)&PORTA*8+0; */ @ (unsigned)&PORTB*8+7; @ (unsigned)&PORTB*8+6; @ (unsigned)&PORTB*8+5; @ (unsigned)&PORTB*8+4; @ (unsigned)&PORTB*8+3; @ (unsigned)&PORTB*8+2; @ (unsigned)&PORTB*8+1; @ (unsigned)&PORTB*8+0;

107

PORTA bits volatile bit volatile bit volatile bit volatile bit volatile bit volatile bit PORTB bits volatile bit volatile bit volatile bit volatile bit volatile bit volatile bit volatile bit volatile bit

112

117

122

300
/* static static static static static static static static /* #ifdef static static static static static static static static PORTC bits volatile bit volatile bit volatile bit volatile bit volatile bit volatile bit volatile bit volatile bit PORTD bits __PINS_40 volatile bit volatile bit volatile bit volatile bit volatile bit volatile bit volatile bit volatile bit */ @ (unsigned)&PORTC*8+7; @ (unsigned)&PORTC*8+6; @ (unsigned)&PORTC*8+5; @ (unsigned)&PORTC*8+4; @ (unsigned)&PORTC*8+3; @ (unsigned)&PORTC*8+2; @ (unsigned)&PORTC*8+1; @ (unsigned)&PORTC*8+0; */ RD7 RD6 RD5 RD4 RD3 RD2 RD1 RD0 @ @ @ @ @ @ @ @ (unsigned)&PORTD*8+7; (unsigned)&PORTD*8+6; (unsigned)&PORTD*8+5; (unsigned)&PORTD*8+4; (unsigned)&PORTD*8+3; (unsigned)&PORTD*8+2; (unsigned)&PORTD*8+1; (unsigned)&PORTD*8+0;

Fichero de cabecera en lenguaje C: pic.h

127

RC7 RC6 RC5 RC4 RC3 RC2 RC1 RC0

132

137

142

147

/* PORTE bits static volatile bit RE2 static volatile bit RE1 static volatile bit RE0 #endif

*/ @ (unsigned)&PORTE*8+2; @ (unsigned)&PORTE*8+1; @ (unsigned)&PORTE*8+0;

152

157

/* INTCON bits */ static volatile bit GIE @ (unsigned)&INTCON*8+7; static volatile bit PEIE @ (unsigned)&INTCON*8+6; static volatile bit T0IE @ (unsigned)&INTCON*8+5; static volatile bit INTE @ (unsigned)&INTCON*8+4; static volatile bit RBIE @ (unsigned)&INTCON*8+3; static volatile bit T0IF @ (unsigned)&INTCON*8+2; static volatile bit INTF @ (unsigned)&INTCON*8+1; static volatile bit RBIF @ (unsigned)&INTCON*8+0; // alternate definitions static volatile bit TMR0IE @ (unsigned)&INTCON*8+5; static volatile bit TMR0IF @ (unsigned)&INTCON*8+2; /* PIR1 bits */ #ifdef __PINS_40 static volatile bit PSPIF @ (unsigned)&PIR1*8+7; #endif static volatile bit ADIF @ (unsigned)&PIR1*8+6; #ifndef _16F872 static volatile bit RCIF @ (unsigned)&PIR1*8+5; static volatile bit TXIF @ (unsigned)&PIR1*8+4; #endif #if !defined(_16F870) && !defined(_16F871) static volatile bit SSPIF @ (unsigned)&PIR1*8+3; #endif static volatile bit CCP1IF @ (unsigned)&PIR1*8+2; static volatile bit TMR2IF @ (unsigned)&PIR1*8+1; static volatile bit TMR1IF @ (unsigned)&PIR1*8+0; /* PIR2 bits */ static volatile bit EEIF @ (unsigned)&PIR2*8+4; #if !defined(_16F870) && !defined(_16F871) static volatile bit BCLIF @ (unsigned)&PIR2*8+3; #ifndef _16F872 static volatile bit CCP2IF @ (unsigned)&PIR2*8+0; #endif #endif /* T1CON bits static volatile static volatile static volatile static volatile static volatile static volatile /* T2CON bits static volatile static volatile static volatile static volatile */ bit bit bit bit bit bit */ bit bit bit bit T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 @ @ @ @ @ @ @ @ @ @ (unsigned)&T1CON*8+5; (unsigned)&T1CON*8+4; (unsigned)&T1CON*8+3; (unsigned)&T1CON*8+2; (unsigned)&T1CON*8+1; (unsigned)&T1CON*8+0; (unsigned)&T2CON*8+6; (unsigned)&T2CON*8+5; (unsigned)&T2CON*8+4; (unsigned)&T2CON*8+3;

162

167

172

177

182

187

192

197

Cap tulo A. Ficheros cabecera


static volatile bit TMR2ON @ (unsigned)&T2CON*8+2; static volatile bit T2CKPS1 @ (unsigned)&T2CON*8+1; static volatile bit T2CKPS0 @ (unsigned)&T2CON*8+0; /* SSPCON bits */ #if !defined(_16F870) && !defined(_16F871) static volatile bit WCOL @ (unsigned)&SSPCON*8+7; static volatile bit SSPOV @ (unsigned)&SSPCON*8+6; static volatile bit SSPEN @ (unsigned)&SSPCON*8+5; static volatile bit CKP @ (unsigned)&SSPCON*8+4; static volatile bit SSPM3 @ (unsigned)&SSPCON*8+3; static volatile bit SSPM2 @ (unsigned)&SSPCON*8+2; static volatile bit SSPM1 @ (unsigned)&SSPCON*8+1; static volatile bit SSPM0 @ (unsigned)&SSPCON*8+0; #endif /* CCP1CON bits */ static volatile bit CCP1X @ (unsigned)&CCP1CON*8+5; static volatile bit CCP1Y @ (unsigned)&CCP1CON*8+4; static volatile bit CCP1M3 @ (unsigned)&CCP1CON*8+3; static volatile bit CCP1M2 @ (unsigned)&CCP1CON*8+2; static volatile bit CCP1M1 @ (unsigned)&CCP1CON*8+1; static volatile bit CCP1M0 @ (unsigned)&CCP1CON*8+0; /* RCSTA bits #ifndef _16F872 static volatile static volatile static volatile static volatile static volatile static volatile static volatile static volatile #endif */ bit bit bit bit bit bit bit bit SPEN RX9 SREN CREN ADDEN FERR OERR RX9D @ @ @ @ @ @ @ @ (unsigned)&RCSTA*8+7; (unsigned)&RCSTA*8+6; (unsigned)&RCSTA*8+5; (unsigned)&RCSTA*8+4; (unsigned)&RCSTA*8+3; (unsigned)&RCSTA*8+2; (unsigned)&RCSTA*8+1; (unsigned)&RCSTA*8+0;

301

202

207

212

217

222

227

232

237

242

/* CCP2CON bits */ #if !defined(_16F870) && !defined(_16F871) && !defined(_16F872) static volatile bit CCP2X @ (unsigned)&CCP2CON*8+5; static volatile bit CCP2Y @ (unsigned)&CCP2CON*8+4; static volatile bit CCP2M3 @ (unsigned)&CCP2CON*8+3; static volatile bit CCP2M2 @ (unsigned)&CCP2CON*8+2; static volatile bit CCP2M1 @ (unsigned)&CCP2CON*8+1; static volatile bit CCP2M0 @ (unsigned)&CCP2CON*8+0; #endif /* ADCON0 bits static volatile bit static volatile bit static volatile bit static volatile bit static volatile bit static volatile bit static volatile bit /* OPTION bits */ static bank1 bit static bank1 bit static bank1 bit static bank1 bit static bank1 bit static bank1 bit static bank1 bit static bank1 bit /* static static static static static static /* static static static static static */ ADCS1 ADCS0 CHS2 CHS1 CHS0 ADGO ADON @ @ @ @ @ @ @ (unsigned)&ADCON0*8+7; (unsigned)&ADCON0*8+6; (unsigned)&ADCON0*8+5; (unsigned)&ADCON0*8+4; (unsigned)&ADCON0*8+3; (unsigned)&ADCON0*8+2; (unsigned)&ADCON0*8+0;

247

252

257

262

RBPU @ (unsigned)&OPTION*8+7; INTEDG @ (unsigned)&OPTION*8+6; T0CS @ (unsigned)&OPTION*8+5; T0SE @ (unsigned)&OPTION*8+4; PSA @ (unsigned)&OPTION*8+3; PS2 @ (unsigned)&OPTION*8+2; PS1 @ (unsigned)&OPTION*8+1; PS0 @ (unsigned)&OPTION*8+0; */ bit bit bit bit bit bit */ bit bit bit bit bit TRISA5 TRISA4 TRISA3 TRISA2 TRISA1 TRISA0 TRISB7 TRISB6 TRISB5 TRISB4 TRISB3 @ @ @ @ @ @ @ @ @ @ @ (unsigned)&TRISA*8+5; (unsigned)&TRISA*8+4; (unsigned)&TRISA*8+3; (unsigned)&TRISA*8+2; (unsigned)&TRISA*8+1; (unsigned)&TRISA*8+0; (unsigned)&TRISB*8+7; (unsigned)&TRISB*8+6; (unsigned)&TRISB*8+5; (unsigned)&TRISB*8+4; (unsigned)&TRISB*8+3;

267

TRISA bits volatile bank1 volatile bank1 volatile bank1 volatile bank1 volatile bank1 volatile bank1 TRISB bits volatile bank1 volatile bank1 volatile bank1 volatile bank1 volatile bank1

272

277

302
static volatile bank1 bit static volatile bank1 bit static volatile bank1 bit
282

Fichero de cabecera en lenguaje C: pic.h


TRISB2 TRISB1 TRISB0 TRISC7 TRISC6 TRISC5 TRISC4 TRISC3 TRISC2 TRISC1 TRISC0 @ (unsigned)&TRISB*8+2; @ (unsigned)&TRISB*8+1; @ (unsigned)&TRISB*8+0; @ @ @ @ @ @ @ @ (unsigned)&TRISC*8+7; (unsigned)&TRISC*8+6; (unsigned)&TRISC*8+5; (unsigned)&TRISC*8+4; (unsigned)&TRISC*8+3; (unsigned)&TRISC*8+2; (unsigned)&TRISC*8+1; (unsigned)&TRISC*8+0;

287

/* static static static static static static static static #ifdef /* static static static static static static static static /* static static static static

TRISC bits volatile bank1 volatile bank1 volatile bank1 volatile bank1 volatile bank1 volatile bank1 volatile bank1 volatile bank1 __PINS_40 TRISD bits volatile bank1 volatile bank1 volatile bank1 volatile bank1 volatile bank1 volatile bank1 volatile bank1 volatile bank1 TRISE bits volatile bank1 volatile bank1 volatile bank1 volatile bank1

*/ bit bit bit bit bit bit bit bit */ bit bit bit bit bit bit bit bit */ bit bit bit bit

292

297

302

TRISD7 TRISD6 TRISD5 TRISD4 TRISD3 TRISD2 TRISD1 TRISD0

@ @ @ @ @ @ @ @

(unsigned)&TRISD*8+7; (unsigned)&TRISD*8+6; (unsigned)&TRISD*8+5; (unsigned)&TRISD*8+4; (unsigned)&TRISD*8+3; (unsigned)&TRISD*8+2; (unsigned)&TRISD*8+1; (unsigned)&TRISD*8+0;

307

IBF @ (unsigned)&TRISE*8+7; OBF @ (unsigned)&TRISE*8+6; IBOV @ (unsigned)&TRISE*8+5; PSPMODE @ (unsigned)&TRISE*8+4; TRISE2 TRISE1 TRISE0 @ (unsigned)&TRISE*8+2; @ (unsigned)&TRISE*8+1; @ (unsigned)&TRISE*8+0;

312

static volatile bank1 bit static volatile bank1 bit static volatile bank1 bit #endif /* PIE1 bits */ #ifdef __PINS_40 static volatile bank1 #endif static volatile bank1 #ifndef _16F872 static volatile bank1 static volatile bank1 #endif static volatile bank1 static volatile bank1 static volatile bank1 static volatile bank1 /* PIE2 bits static volatile static volatile #ifndef _16F872 static volatile #endif

317

bit bit bit bit bit bit bit bit

PSPIE ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE EEIE BCLIE CCP2IE

@ (unsigned)&PIE1*8+7; @ (unsigned)&PIE1*8+6; @ (unsigned)&PIE1*8+5; @ (unsigned)&PIE1*8+4; @ @ @ @ (unsigned)&PIE1*8+3; (unsigned)&PIE1*8+2; (unsigned)&PIE1*8+1; (unsigned)&PIE1*8+0;

322

327

*/ bank1 bit bank1 bit bank1 bit

@ (unsigned)&PIE2*8+4; @ (unsigned)&PIE2*8+3; @ (unsigned)&PIE2*8+0;

332

337

/* PCON bits */ static volatile bank1 bit static volatile bank1 bit /* SSPCON2 bits */ #if !defined(_16F870) static volatile bank1 static volatile bank1 static volatile bank1 static volatile bank1 static volatile bank1 static volatile bank1 static volatile bank1 static volatile bank1 #endif /* SSPSTAT bits #if !defined(_16F870) static volatile bank1 static volatile bank1 static volatile bank1

POR @ (unsigned)&PCON*8+1; BOR @ (unsigned)&PCON*8+0;

342

347

&& !defined(_16F871) bit GCEN @ (unsigned)&SSPCON2*8+7; bit ACKSTAT @ (unsigned)&SSPCON2*8+6; bit ACKDT @ (unsigned)&SSPCON2*8+5; bit ACKEN @ (unsigned)&SSPCON2*8+4; bit RCEN @ (unsigned)&SSPCON2*8+3; bit PEN @ (unsigned)&SSPCON2*8+2; bit RSEN @ (unsigned)&SSPCON2*8+1; bit SEN @ (unsigned)&SSPCON2*8+0; */ && !defined(_16F871) bit STAT_SMP @ (unsigned)&SSPSTAT*8+7; bit STAT_CKE @ (unsigned)&SSPSTAT*8+6; bit STAT_DA @ (unsigned)&SSPSTAT*8+5;

352

Cap tulo A. Ficheros cabecera


357

303
STAT_P STAT_S STAT_RW STAT_UA STAT_BF @ @ @ @ @ (unsigned)&SSPSTAT*8+4; (unsigned)&SSPSTAT*8+3; (unsigned)&SSPSTAT*8+2; (unsigned)&SSPSTAT*8+1; (unsigned)&SSPSTAT*8+0;

362

static static static static static #endif

volatile volatile volatile volatile volatile

bank1 bank1 bank1 bank1 bank1 */ bank1 bank1 bank1 bank1 bank1 bank1 bank1 */ bank1 bank1 bank1 bank1 bank1 */ bank3 bank3 bank3 bank3 bank3

bit bit bit bit bit

367

372

/* TXSTA bits #ifndef _16F872 static volatile static volatile static volatile static volatile static volatile static volatile static volatile #endif /* ADCON1 bits static volatile static volatile static volatile static volatile static volatile /* EECON1 bits static volatile static volatile static volatile static volatile static volatile

bit bit bit bit bit bit bit

CSRC @ (unsigned)&TXSTA*8+7; TX9 @ (unsigned)&TXSTA*8+6; TXEN @ (unsigned)&TXSTA*8+5; SYNC @ (unsigned)&TXSTA*8+4; BRGH @ (unsigned)&TXSTA*8+2; TRMT @ (unsigned)&TXSTA*8+1; TX9D @ (unsigned)&TXSTA*8+0;

377

bit bit bit bit bit bit bit bit bit bit

ADFM PCFG3 PCFG2 PCFG1 PCFG0

@ @ @ @ @

(unsigned)&ADCON1*8+7; (unsigned)&ADCON1*8+3; (unsigned)&ADCON1*8+2; (unsigned)&ADCON1*8+1; (unsigned)&ADCON1*8+0;

382

387

EEPGD @ (unsigned)&EECON1*8+7; WRERR @ (unsigned)&EECON1*8+3; WREN @ (unsigned)&EECON1*8+2; WR @ (unsigned)&EECON1*8+1; RD @ (unsigned)&EECON1*8+0;

392

#if defined(_16F870) || defined(_16F871) || defined(_16F872) #define EEPROM_SIZE 64 #elif defined(_16F873) || defined(_16F874) #define EEPROM_SIZE 128 #else #define EEPROM_SIZE 256 #endif /* macro versions of EEPROM write and read */ #define EEPROM_WRITE(addr, value) while(WR)continue;\ EEADR=(addr);EEDATA=(value); \ EECON1&=0x7F;CARRY=0;if(GIE)CARRY=1;GIE=0; \ WREN=1;EECON2=0x55;EECON2=0xAA;WR=1;WREN=0; \ if(CARRY)GIE=1 #define EEPROM_READ(addr) ((EEADR=(addr)),(EECON1&=0x7F),(RD=1),EEDATA)

397

402

407

412

417

/* macro versions of Flash read and write */ #define FLASH_WRITE(addr, value) EEADR=((addr)&0xff); EEADRH=((addr)>>8); \ EEDATH=((value)>>8); \ EEDATA=((value)&0xff); \ EEPGD = 1; \ WREN=1; \ EECON2 = 0x55; \ EECON2 = 0xaa; \ WR=1; \ asm("nop"); \ asm("nop"); \ WREN=0 #define FLASH_READ(addr) EEADR=((addr)&0xff); EEADRH=((addr)>>8); \ WREN=0; \ EEPGD = 1; \ RD=1; \ asm("nop"); \ asm("nop"); \ ((EEDATH << 8) | EEDATA) /* library function versions */ \

422

427

432

extern void eeprom_write(unsigned char addr, unsigned char value); extern unsigned char eeprom_read(unsigned char addr); #define CONFIG_ADDR 0x2007

304

Fichero de cabecera en lenguaje C: pic.h

437

/*osc configurations*/ #define RC 0x3FFF #define HS 0x3FFE #define XT 0x3FFD #define LP 0x3FFC /*watchdog*/ #define WDTEN #define WDTDIS /*power up timer*/ #define PWRTEN #define PWRTDIS

// // // //

resistor/capacitor high speed crystal/resonator crystal/resonator low power crystal/resonator // enable watchdog timer // disable watchdog timer // enable power up timer // disable power up timer // enable brown out reset // disable brown out reset

442

0x3FFF 0x3FFB 0x3FF7 0x3FFF

447

452

/*brown out reset*/ #define BOREN 0x3FFF #define BORDIS 0x3FBF

/*Low Voltage Programmable*/ #define LVPEN 0x3FFF // low voltage programming enabled #define LVPDIS 0x3F7F // low voltage programming disabled
457

462

/*data code protected*/ #define DP 0x3EFF // protect data code // alternately #define DPROT 0x3EFF // use DP #define DUNPROT 0x3FFF // use UNPROTECT /* Flash memory write enable/protect */ #define WRTEN 0x3FFF /* flash memory write enabled */ #define WRTDIS 0x3DFF /* flash memory write protected/disabled */

467

/*debug option*/ #define DEBUGEN #define DEBUGDIS


472

0x37FF 0x3FFF

// debugger enabled // debugger disabled /* protect program code */ /* do not protect the code */ */ */

/*code protection*/ #define PROTECT 0x0FCF #define UNPROTECT 0x3FFF

477

#if !defined(_16F870) && !defined(_16F871) #define PROTECT_TOP 0x2FEF /* protects top 256 bytes, 1F00h to 1FFFh #define PROTECT50 0x1FDF /* protects upper half of address space /* 1000h to 1FFFh (pic16f887/876) */ /* 0800h to 0FFFh (pic16f874/873) */ #endif

Ap endice B Bancos de registros


Vision general
File Address Indirect addr.(*) TMR0 PCL STATUS FSR PORTA PORTB PORTC PORTD (1) PORTE (1) PCLATH INTCON PIR1 PIR2 TMR1L TMR1H T1CON TMR2 T2CON SSPBUF SSPCON CCPR1L CCPR1H CCP1CON RCSTA TXREG RCREG CCPR2L CCPR2H CCP2CON ADRESH ADCON0 00h 01h 02h 03h 04h 05h 06h 07h 08h 09h 0Ah 0Bh 0Ch 0Dh 0Eh 0Fh 10h 11h 12h 13h 14h 15h 16h 17h 18h 19h 1Ah 1Bh 1Ch 1Dh 1Eh 1Fh 20h Indirect addr.(*) 80h OPTION_REG 81h PCL 82h STATUS 83h FSR 84h TRISA 85h TRISB 86h TRISC 87h TRISD (1) 88h TRISE (1) 89h PCLATH 8Ah INTCON 8Bh PIE1 8Ch PIE2 8Dh PCON 8Eh 8Fh 90h 91h SSPCON2 PR2 92h SSPADD 93h SSPSTAT 94h 95h 96h 97h 98h TXSTA 99h SPBRG 9Ah 9Bh 9Ch 9Dh ADRESL 9Eh 9Fh ADCON1 A0h General Purpose Register 80 Bytes accesses 70h-7Fh 7Fh Bank 0 Bank 1 Indirect addr.(*) 100h 101h TMR0 102h PCL 103h STATUS 104h FSR 105h 106h PORTB 107h 108h 109h 10Ah PCLATH 10Bh INTCON 10Ch EEDATA EEADR 10Dh 10Eh EEDATH 10Fh EEADRH 110h 111h 112h 113h 114h 115h 116h General 117h Purpose 118h Register 119h 16 Bytes 11Ah 11Bh 11Ch 11Dh 11Eh 11Fh 120h Indirect addr.(*) OPTION_REG PCL STATUS FSR TRISB 180h 181h 182h 183h 184h 185h 186h 187h 188h 189h 18Ah 18Bh 18Ch 18Dh 18Eh 18Fh 190h 191h 192h 193h 194h 195h 196h 197h 198h 199h 19Ah 19Bh 19Ch 19Dh 19Eh 19Fh 1A0h General Purpose Register 80 Bytes accesses 70h - 7Fh Bank 3

PCLATH INTCON EECON1 EECON2 Reserved(2) Reserved(2)

General Purpose Register 16 Bytes

General Purpose Register 96 Bytes

EFh F0h FFh

General Purpose Register 80 Bytes accesses 70h-7Fh Bank 2

16Fh 170h 17Fh

1EFh 1F0h 1FFh

Unimplemented data memory locations, read as 0. * Not a physical register. Note 1: These registers are not implemented on 28-pin devices. 2: These registers are reserved, maintain these registers clear.

305

306 Banco 0 de registros


TABLE 2-1:
Addres s
Bank 0 00h(4) 01h 02h(4) 03h(4) 04h(4) 05h 06h 07h 08h(5) 09h(5) 0Ah(1,4) 0Bh(4) 0Ch 0Dh 0Eh 0Fh 10h 11h 12h 13h 14h 15h 16h 17h 18h 19h 1Ah 1Bh 1Ch 1Dh 1Eh 1Fh INDF TMR0 PCL STATUS FSR PORTA PORTB PORTC PORTD PORTE PCLATH INTCON PIR1 PIR2 TMR1L TMR1H T1CON TMR2 T2CON SSPBUF SSPCON CCPR1L CCPR1H CCP1CON RCSTA TXREG RCREG CCPR2L CCPR2H CCP2CON ADRESH ADCON0 Addressing this location uses contents of FSR to address data memory (not a physical register) Timer0 modules register Program Counter's (PC) Least Significant Byte IRP RP1 RP0 TO PD Z DC C 0000 0000 0000 0000 xxxx xxxx uuuu uuuu 0000 0000 0000 0000 0001 1xxx 000q quuu xxxx xxxx uuuu uuuu --0x 0000 --0u 0000 xxxx xxxx uuuu uuuu xxxx xxxx uuuu uuuu xxxx xxxx uuuu uuuu RE2 RE1 RE0 ---- -xxx ---- -uuu ---0 0000 ---0 0000 0000 000x 0000 000u 0000 0000 0000 0000 -r-0 0--0 -r-0 0--0 xxxx xxxx uuuu uuuu xxxx xxxx uuuu uuuu TMR1CS TMR1ON --00 0000 --uu uuuu 0000 0000 0000 0000 TOUTPS1 CKP TOUTPS0 SSPM3 TMR2ON T2CKPS1 T2CKPS0 -000 0000 -000 0000 xxxx xxxx uuuu uuuu SSPM2 SSPM1 SSPM0 0000 0000 0000 0000 xxxx xxxx uuuu uuuu xxxx xxxx uuuu uuuu CCP1M3 ADDEN CCP1M2 FERR CCP1M1 OERR CCP1M0 RX9D --00 0000 --00 0000 0000 000x 0000 000x 0000 0000 0000 0000 0000 0000 0000 0000 xxxx xxxx uuuu uuuu xxxx xxxx uuuu uuuu CCP2M3 CCP2M2 GO/ DONE CCP2M1 CCP2M0 --00 0000 --00 0000 xxxx xxxx uuuu uuuu CHS1 CHS0 ADON 0000 00-0 0000 00-0

SPECIAL FUNCTION REGISTER SUMMARY


Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Value on: POR, BOR Value on all other resets (2)

Name

Indirect data memory address pointer PORTA Data Latch when written: PORTA pins when read PORTB Data Latch when written: PORTB pins when read PORTC Data Latch when written: PORTC pins when read PORTD Data Latch when written: PORTD pins when read GIE PSPIF(3) PEIE ADIF (6) T0IE RCIF

Write Buffer for the upper 5 bits of the Program Counter INTE TXIF EEIF RBIE SSPIF BCLIF T0IF CCP1IF INTF TMR2IF RBIF TMR1IF CCP2IF

Holding register for the Least Significant Byte of the 16-bit TMR1 register Holding register for the Most Significant Byte of the 16-bit TMR1 register WCOL T1CKPS1 T1CKPS0 T1OSCEN T1SYNC Timer2 modules register TOUTPS3 TOUTPS2 SSPOV SSPEN Synchronous Serial Port Receive Buffer/Transmit Register Capture/Compare/PWM Register1 (LSB) Capture/Compare/PWM Register1 (MSB) SPEN RX9 CCP1X SREN CCP1Y CREN

USART Transmit Data Register USART Receive Data Register Capture/Compare/PWM Register2 (LSB) Capture/Compare/PWM Register2 (MSB) CCP2X CCP2Y A/D Result Register High Byte ADCS1 ADCS0 CHS2

Cap tulo B. Bancos de registros Banco 1 de registros


TABLE 2-1:
Addres s
Bank 1 80h(4) 81h 82h(4) 83h
(4)

307

SPECIAL FUNCTION REGISTER SUMMARY (CONTINUED)


Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Value on: POR, BOR Value on all other resets (2)

Name

INDF OPTION_R EG PCL STATUS FSR TRISA TRISB TRISC TRISD TRISE PCLATH INTCON PIE1 PIE2 PCON SSPCON2 PR2 SSPADD SSPSTAT TXSTA SPBRG ADRESL ADCON1

Addressing this location uses contents of FSR to address data memory (not a physical register) RBPU INTEDG T0CS T0SE PSA PS2 PS1 PS0

0000 0000 0000 0000 1111 1111 1111 1111 0000 0000 0000 0000

Program Counters (PC) Least Significant Byte IRP RP1 RP0 TO PD Z DC C

0001 1xxx 000q quuu xxxx xxxx uuuu uuuu --11 1111 --11 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111

84h(4) 85h 86h 87h 88h(5) 89h(5) 8Ah(1,4) 8Bh(4) 8Ch 8Dh 8Eh 8Fh 90h 91h 92h 93h 94h 95h 96h 97h 98h 99h 9Ah 9Bh 9Ch 9Dh 9Eh 9Fh

Indirect data memory address pointer PORTA Data Direction Register PORTB Data Direction Register PORTC Data Direction Register PORTD Data Direction Register IBF GIE PSPIE Unimplemented Unimplemented GCEN ACKSTAT ACKDT ACKEN RCEN PEN RSEN SEN Timer2 Period Register Synchronous Serial Port (I2C mode) Address Register SMP CKE D/A P S R/W UA BF Unimplemented Unimplemented Unimplemented CSRC TX9 TXEN SYNC BRGH TRMT TX9D Baud Rate Generator Register Unimplemented Unimplemented Unimplemented Unimplemented A/D Result Register Low Byte ADFM PCFG3 PCFG2 PCFG1 PCFG0
(3)

OBF PEIE ADIE (6)

IBOV T0IE RCIE

PSPMODE

PORTE Data Direction Bits

0000 -111 0000 -111 ---0 0000 ---0 0000 0000 000x 0000 000u 0000 0000 0000 0000 -r-0 0--0 -r-0 0--0 ---- --qq ---- --uu

Write Buffer for the upper 5 bits of the Program Counter INTE TXIE EEIE RBIE SSPIE BCLIE T0IF CCP1IE INTF TMR2IE POR RBIF TMR1IE CCP2IE BOR

0000 0000 0000 0000 1111 1111 1111 1111 0000 0000 0000 0000 0000 0000 0000 0000

0000 -010 0000 -010 0000 0000 0000 0000 0--- 0000 0--- 0000

xxxx xxxx uuuu uuuu

308 Bancos 2 y 3 de registros


TABLE 2-1:
Addres s
Bank 2 100h(4) 101h 102h(4) 103h(4) 104h(4) 105h 106h 107h 108h 109h 10Ah(1,4) 10Bh(4) 10Ch 10Dh 10Eh 10Fh Bank 3 180h(4) 181h 182h(4) 183h(4) 184h(4) 185h 186h 187h 188h 189h 18Ah(1,4) 18Bh(4) 18Ch 18Dh 18Eh 18Fh INDF OPTION_R EG PCL STATUS FSR TRISB PCLATH INTCON EECON1 EECON2 Addressing this location uses contents of FSR to address data memory (not a physical register) RBPU INTEDG T0CS T0SE PSA PS2 PS1 PS0 0000 0000 0000 0000 1111 1111 1111 1111 0000 0000 0000 0000 PD Z DC C 0001 1xxx 000q quuu xxxx xxxx uuuu uuuu PEIE T0IE Write Buffer for the upper 5 bits of the Program Counter INTE RBIE WRERR T0IF WREN INTF WR RBIF RD INDF TMR0 PCL STATUS FSR PORTB PCLATH INTCON EEDATA EEADR EEDATH EEADRH Addressing this location uses contents of FSR to address data memory (not a physical register) Timer0 modules register Program Counter's (PC) Least Significant Byte IRP RP1 RP0 TO PD Z DC C 0000 0000 0000 0000

SPECIAL FUNCTION REGISTER SUMMARY (CONTINUED)


Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Value on: POR, BOR Value on all other resets (2)

Name

xxxx xxxx uuuu uuuu 0000 0000 0000 0000 0001 1xxx 000q quuu xxxx xxxx uuuu uuuu

Indirect data memory address pointer Unimplemented PORTB Data Latch when written: PORTB pins when read Unimplemented Unimplemented Unimplemented GIE PEIE T0IE Write Buffer for the upper 5 bits of the Program Counter INTE RBIE T0IF INTF RBIF

xxxx xxxx uuuu uuuu

---0 0000 ---0 0000 0000 000x 0000 000u xxxx xxxx uuuu uuuu xxxx xxxx uuuu uuuu xxxx xxxx uuuu uuuu xxxx xxxx uuuu uuuu

EEPROM data register EEPROM address register EEPROM data register high byte EEPROM address register high byte

Program Counter's (PC) Least Significant Byte IRP RP1 RP0 TO

Indirect data memory address pointer Unimplemented PORTB Data Direction Register Unimplemented Unimplemented Unimplemented GIE EEPGD

1111 1111 1111 1111

---0 0000 ---0 0000 0000 000x 0000 000u x--- x000 x--- u000 ---- ---- ---- ---0000 0000 0000 0000 0000 0000 0000 0000

EEPROM control register2 (not a physical register) Reserved maintain clear Reserved maintain clear

Legend:

= unknown,

= unchanged,

= value depends on condition, - = unimplemented read as 0, r = reserved.

Ap endice C Juego de instrucciones


TABLE 13-2:
Mnemonic, Operands

PIC16CXXX INSTRUCTION SET


Description Cycles 14-Bit Opcode MSb BYTE-ORIENTED FILE REGISTER OPERATIONS Add W and f AND W with f Clear f Clear W Complement f Decrement f Decrement f, Skip if 0 Increment f Increment f, Skip if 0 Inclusive OR W with f Move f Move W to f No Operation Rotate Left f through Carry Rotate Right f through Carry Subtract W from f Swap nibbles in f Exclusive OR W with f Bit Clear f Bit Set f Bit Test f, Skip if Clear Bit Test f, Skip if Set Add literal and W AND literal with W Call subroutine Clear Watchdog Timer Go to address Inclusive OR literal with W Move literal to W Return from interrupt Return with literal in W Return from Subroutine Go into standby mode Subtract W from literal Exclusive OR literal with W 1 1 1 1 1 1 1(2) 1 1(2) 1 1 1 1 1 1 1 1 1 1 1 1 (2) 1 (2) 1 1 2 1 2 1 1 2 2 2 1 1 1 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0111 0101 0001 0001 1001 0011 1011 1010 1111 0100 1000 0000 0000 1101 1100 0010 1110 0110 dfff dfff lfff 0xxx dfff dfff dfff dfff dfff dfff dfff lfff 0xx0 dfff dfff dfff dfff dfff LSb ffff ffff ffff xxxx ffff ffff ffff ffff ffff ffff ffff ffff 0000 ffff ffff ffff ffff ffff Status Affected Notes

ADDWF ANDWF CLRF CLRW COMF DECF DECFSZ INCF INCFSZ IORWF MOVF MOVWF NOP RLF RRF SUBWF SWAPF XORWF BCF BSF BTFSC BTFSS ADDLW ANDLW CALL CLRWDT GOTO IORLW MOVLW RETFIE RETLW RETURN SLEEP SUBLW XORLW Note 1:

f, d f, d f f, d f, d f, d f, d f, d f, d f, d f f, d f, d f, d f, d f, d f, b f, b f, b f, b k k k k k k k k k

C,DC,Z Z Z Z Z Z Z Z Z

1,2 1,2 2 1,2 1,2 1,2,3 1,2 1,2,3 1,2 1,2

C C C,DC,Z Z

1,2 1,2 1,2 1,2 1,2 1,2 1,2 3 3

BIT-ORIENTED FILE REGISTER OPERATIONS 01 01 01 01 00bb 01bb 10bb 11bb bfff bfff bfff bfff ffff ffff ffff ffff C,DC,Z Z TO,PD Z

LITERAL AND CONTROL OPERATIONS 11 11 10 00 10 11 11 00 11 00 00 11 11 111x 1001 0kkk 0000 1kkk 1000 00xx 0000 01xx 0000 0000 110x 1010 kkkk kkkk kkkk 0110 kkkk kkkk kkkk 0000 kkkk 0000 0110 kkkk kkkk kkkk kkkk kkkk 0100 kkkk kkkk kkkk 1001 kkkk 1000 0011 kkkk kkkk

TO,PD C,DC,Z Z

When an I/O register is modified as a function of itself ( e.g., MOVF PORTB, 1), the value used will be that value present on the pins themselves. For example, if the data latch is 1 for a pin configured as input and is driven low by an external device, the data will be written back with a 0. 2: If this instruction is executed on the TMR0 register (and, where applicable, d = 1), the prescaler will be cleared if assigned to the Timer0 Module. 3: If Program Counter (PC) is modified or a conditional test is true, the instruction requires two cycles. The second cycle is executed as a NOP.

309

Indice alfab etico


Direccionamiento, 33 Memoria, 25 de Datos, 26 de Programa, 25 Patillaje, 20 Pin /MCLR, 61, 116, 121 /SS=0, 98 OSC1, 115 OSC2, 115 RA0, 35, 63 RA0/AN0, 36, 65 RA1, 35, 63 RA1/AN1, 36, 65 RA2, 35, 63 RA2/AN2, 65 RA2/AN2/VREF-, 36 RA2/VREF-, 63 RA3, 35, 63 RA3/AN3, 65 RA3/AN3/VREF+, 36 RA3/VREF+, 63 RA4, 35 RA4/T0CKI, 29, 36, 53, 55 RA5, 35, 63 RA5/AN4, 65 RA5/SS, 95, 97, 103 RA5/SS/AN4, 36 RB0, 39, 121 RB0/INT, 2830, 39, 54, 119 RB1, 39 RB2, 39 RB3, 39 RB3/PGM, 39, 122 RB4, 29, 30, 39, 119, 121 RB5, 29, 30, 39 RB6, 29, 30, 39, 122 RB6/PGC, 39, 40 RB7, 29, 30, 39, 119, 121, 122 RB7/PGD, 39, 40 RC0, 42 RC0/T1OSO, 59 RC0/T1OSO/T1CKI, 42, 58, 59 RC1/CCP2, 7680, 82 RC1/T1OSI, 59 RC1/T1OSI/CCP2, 42, 59 RC2/CCP1, 42, 7680, 82, 83 RC3/SCK, 9598, 103, 104 RC3/SCK/SCL, 42 RC3/SCL, 95, 105 RC4/SDA, 95, 105 RC4/SDI, 95, 97 RC4/SDI/SDA, 42 RC5/SDO, 42, 95, 97 RC6/CK, 93 RC6/TX, 89 RC6/TX/CK, 42, 85, 89 RC7, 42 RC7/DT, 93 RC7/RX/DT, 42, 85, 87, 89, 91 RD0, 45 RD0/PSP0, 45 RD1/PSP1, 45 RD2/PSP2, 45 RD3/PSP3, 45 RD4/PSP4, 45 RD5/PSP5, 45 RD6/PSP6, 45 RD7, 45 RD7/PSP7, 45 RE0, 47, 49, 63 RE0/AN5, 65 RE0/RD, 49 RE0/RD/AN5, 47 RE1, 47, 63 RE1/AN6, 65 RE1/WR, 49 RE1/WR/AN6, 47 RE2, 47, 49, 63 RE2/AN7, 65 RE2/CS, 49 RE2/CS/AN7, 47 VDD, 63 VSS, 63 Prestaciones, 17 Puerto A, 35 Puerto B, 39 Puerto C, 42 Puerto D, 45

310

INDICE ALFABETICO
Puerto E, 47 Puerto paralelo esclavo, 49 Registro ADCON0, 65 ADCON1, 65 ADRESH, 64 ADRESL, 64 CCP1CON, 76 CCP2CON, 76 CCPR1H, 76 CCPR1L, 76 CCPR2H, 76 CCPR2L, 76 CCPxCON, 76 EEADR, 69 EEADRH, 69 EECON1, 70 EECON2, 70 EEDATA, 69 EEDATH, 69 INTCON, 29 OPTION REG, 28, 54 PC, 33 PCL, 33 PCLATH, 33 PCON, 32 PIE1, 30 PIE2, 31 PIR1, 30 PIR2, 32 PR2, 62 RCREG, 85 RCSTA, 86 SPBRG, 87 SSPADD, 109 SSPBUF, 102 SSPCON, 103 SSPCON2, 110 SSPSTAT, 104 STATUS, 28 T1CON, 58 T2CON, 62 TMR0, 54 TMR1H, 57 TMR1L, 57 TMR2, 62 TRISA, 35 TRISB, 39 TRISC, 42 TRISD, 45 TRISE, 50 TXREG, 85 TXSTA, 85

311

312

INDICE ALFABETICO

Listados
4.1. EX/AD.c . . . . . . . . . . . . . . . . . . . . . 6.1. EX/EX CAPTURA/CAPTURA.C . . . . . . . 6.2. EX/EX COMPARACION/COMPARA.C . . 6.3. EX/EX PWM/PWM.C . . . . . . . . . . . . . 7.1. EX/EX TX ASINC/TX ASINC.C . . . . . . . 7.2. EX/EX RX ASINC/RX ASINC.c . . . . . . . 8.1. EX/EX TX SPI/TX SPI.c . . . . . . . . . . . . 8.2. EX/EX TXRX SPI/P SPI.c . . . . . . . . . . . 8.3. EX/EX TXRX SPI/P SPI Slave.c . . . . . . . 8.4. EX/EX TX I2C/TX I2C.c . . . . . . . . . . . . 11.1. EX/BOOT/BOOTLDR 16F877.asm . . . . . . 11.2. EX/BOOT/BOOTLDR 16F877.asm . . . . . . 14.1. EX/TERMOMETRO/TERMOMETRO0.c . . 14.2. EX/TERMOMETRO/LCD.h . . . . . . . . . . 19.1. EX/ROBOT COMM/TERMINAL.cpp . . . . 22.1. EX/MOTORPASO/MotorStepper.c . . . . . . 22.2. EX/MOTORPASO/MotorStepper 2.c . . . . 22.3. EX/MOTORPASO/MotorStepper 3.c . . . . 23.1. EX/TERMOMETRO/TERMOMETRO1.c . . 23.2. EX/TERMOMETRO/TERMOMETRO2.c . . 23.3. EX/TERMOMETRO/TERMOMETRO3.c . . 23.4. EX/TERMOMETRO/TERMOMETRO4.c . . 23.5. EX/TERMOMETRO/TERMOMETRO5.c . . 24.1. EX/GEN AUDIO/GEN AUDIO0.c . . . . . 24.2. EX/GEN AUDIO/GEN AUDIO1.c . . . . . 24.3. EX/GEN AUDIO/GEN AUDIO2.c . . . . . 24.4. EX/GEN AUDIO/GEN AUDIO3.c . . . . . 24.5. EX/GEN AUDIO/GEN AUDIO4.c . . . . . 25.1. EX/MOTORDC/MotorDC 1.c . . . . . . . . 25.2. EX/MOTORDC/MotorDC 2.c . . . . . . . . 26.1. EX/FREC/FRECUENCIMETRO.C . . . . . . 26.2. EX/FREC/LCD FREC.h . . . . . . . . . . . . 27.1. EX/ROBOT/ROBOT LINEA.C . . . . . . . . 28.1. EX/ROBOT COMM/ROBOT SERIE.c . . . . 29.1. EX/GRAFICO/SOFTWARE/MAIN.c . . . . 29.2. EX/GRAFICO/SOFTWARE/LCDGRAPH.C 29.3. EX/GRAFICO/SOFTWARE/LCDGRAPH.H A.1. EX/INC/P16F877.INC . . . . . . . . . . . . . A.2. EX/INC/pic1687x.h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 78 80 83 90 92 98 100 102 111 162 162 198 202 229 241 243 245 249 250 250 251 253 257 258 259 261 262 266 267 269 271 274 277 283 283 288 293 298

313

314

LISTADOS

Bibliograf a
[1] PIC16F84A Datasheet. Microchip, 1998. DS35007A. [2] PIC16F87X Datasheet. Microchip, 1998. DS30292B. [3] In-Circuit Serial Programming for PIC16F8X FLASH MCUs. DS30262C. Microchip, 2000.

[4] Jos e Mar a Angulo Amus ategui and Ignacio Angulo. Microcontroladores PIC, 1a a parte, 4 Ed. Mc-Graw-Hill, 2007. ISBN: 9788448156473. [5] Jos e Mar a Angulo Amusategui, Aritza Etxebarria, Ignacio Angulo, and Iv an Trueba. Microcontroladores dsPIC. Diseno pr actico de aplicaciones. Mc-Graw-Hill, 2006. ISBN: 9788448151560. [6] Jos e Mar a Angulo Amus ategui, Aritza Etxebarr a, Ignacio Angulo, and Iv an Trueba. Microcontroladores dsPIC. Diseno pr actico de aplicaciones. Mc-Graw-Hill, 2006. ISBN: 9788448151560. [7] Angulo Usategui, Mart n Cuenca, and Angulo Mart nez. Microcontroladores PIC: la soluci on en un chip. Paraninfo, 1998. ISBN 8428323712. [8] Benson. PICn up the pace. Square One Electronics, 1999. ISBN 0965416216. [9] Dogan Ibrahim. Advanced PIC Microcontroller Projects in C: From USB to RTOS with the PIC18F Series. Newnes, 2008. ISBN: 978-0-7506-8611-2. [10] Lucio Di Jasio. Programming 16-bit Microcontrollers in C: Learning to Fly the PIC24. Newnes, 2007. ISBN: 978-0-7506-8292-3. [11] Lucio Di Jasio. Programming 32-bit Microcontrollers in C: Exploring the PIC32. Newnes, 2008. ISBN: 978-0-7506-8709-6. [12] Enrique Mandado P erez. Microcontroladores PIC : sistema integrado para el aprendizaje. Marcombo, 2007. ISBN: 978-84-267-1431-2. [13] Fernando ; Lopez P erez Lucas J. Palacios Municio, Enrique ; Remiro Dom nguez. Microcontrolador PIC16F84: Desarrollo de proyectos. Ra-Ma, 2005. ISBN: 978-84-7897691-1. [14] Peatman. Design with PIC microcontrollers. Paraninfo, 1997. ISBN 0137592590. [15] M. Predko. Programming and customizing the PIC microcontroller. Tab Electronics, 1997. ISBN 007913646X. [16] Stevens. Serial PICn. Square One Electronics, 1999. ISBN 0965416224. 315

316

BIBLIOGRAFIA

[17] Tavernier. Microcontroladores PIC. Paraninfo, 1997. ISBN 8428323739. [18] Jos e Mar a Angulo Usategui, Susana Romero Yesa, and Ignacio Angulo Mart nez. a Microcontroladores PIC 2 Parte. PIC 16F87X. Diseno pr actico de aplicaciones. McGraw-Hill, 2006. ISBN: 9788448146276. [19] Tim Wilmshurst. Designing Embedded Systems with PIC Microcontrollers: Priciples and Applications. Newnes, 2008. ISBN 978-0-7506-6755-5.

You might also like