La descarga está en progreso. Por favor, espere

La descarga está en progreso. Por favor, espere

mc Programación Microcontroladores Familia de Rango Medio

Presentaciones similares


Presentación del tema: "mc Programación Microcontroladores Familia de Rango Medio"— Transcripción de la presentación:

1 mc Programación Microcontroladores Familia de Rango Medio
Programación PIC® Avanzada Rango Medio Programación Microcontroladores Familia de Rango Medio Configuración de Periféricos Programación Assembler mc

2 Al finalizar esta clase usted podrá:
Objectivos Al finalizar esta clase usted podrá: – Entenderá los Periféricos básicos y los registros asociados a los mismos “Metiendo Mano”usted experimentará la Incialización de los periféricos del Rango Medio. Podrá implementar periféricos no cubiertos aquí Entenderá las interrupciones y el polling Escriba su propio código de aplicación

3 Idealmente usted debe estar familiarizado con lo siguiente:
Para conseguir lo mejor de esta clase Idealmente usted debe estar familiarizado con lo siguiente: Programación Assembler Principios de la Familia de Rango Medio y Set de Instrucciones Organización de la Memoria de Datos y Programa MPLAB Microchip ICD2 debugger

4 Agenda Discución sobre los Periféricos:
Breve revisión de la Arquitectura del Rango Medio, Set de Instrucciones y Herramientas Interrupciones sobre los PIC de Rango Medio – Laboratorio de Interrupciones Discución sobre los Periféricos: – Puertos I/O – Timers Timer0 Timer1 – Timer1 Laboratorio Timer2 – Timer2 Laboratorio

5 Agenda (cont.) Módulo (CCP) Captura / Comparación / PWM
– PWM y Salida del Compare Laboratorios Comparador Analógicos Conversor Analógico Digital (ADC) – ADC Laboratorio UART direccionable (AUSART) I2C con el Puerto Serie Sincrónico Master – I2C Basado en un Sensor de Temperatura Laboratorio Concluciones y preguntas adicionales

6 mc Familia de Rango Medio Arquitectura Básica y Herramientas de
Programación PIC® Avanzada Rango Medio Familia de Rango Medio Arquitectura Básica y Herramientas de Desarrollo mc

7 PIC Rango Medio Diagrama en Bloques STATUS PROGRAM COUNTER
8-bit value from instruction REGISTER Pages of Program Memory MUX Bancos de Memoria de Datos ADC ALU TIMER0 14-bits INSTRUCTION REGISTER WORKING REGISTER AUSART MSSP PERIFERICOS

8 Memoria de PROGRAMA Maximo 8K words Reset Vector at 0000h
– (8K x 14 bits/word)/1 byte = 14Kbytes de memoria Reset Vector at 0000h – Contador de Programa (PC)irá a esta dirección sobre el RESET Interrupt Vector h 0005h 07FFh 0800h 0FFFh Page 0 Page 1 1000h 17FFh 1800h 1FFFh Interrupt Vector at 0004h – Contador de Programa (PC) irá a esta dirección sobre cualquier interrupción Page 2 Page 3

9 13-bit PC 8 Niveles de Stack OPCODE(11-bits) PCH P i Paging bits bit
Contador de Programa (PC) y Stack PCLATH 13-bit PC – PCL ALU result (8-bits) or PCH<12:8> PCL CALL, RETURN, – RETFIE, RETLW Stack Level 1 Especifica la Página en Memoria de Programa 8 Niveles de Stack – almacena el contenido del PC PUSHES Stack Level 8 – CALL/Interrupt Memoria de PC<12:0> OPCODE(11-bits) PCH P i Paging bits bit Actualización desde PCLATH POPS RETURN, RETFIE,RETLW Programa

10 Mapa de Memoria de SFR Datos 000h Special Function Registers 01Fh
0A0h 128 Bytes General Purpose Registers General Purpose Registers General Purpose Registers General Purpose Registers 0EFh 0FFh 16Fh 17Fh 1EFh 1FFh Shared Bank1 Shared Bank2 Shared Bank3 07Fh Bank k0

11 Registros de Funciones
Especiales (SFRs) Condepto de Archivo de Registros Acceso a cualquier registro Algunos Registros se repiten en todos los bancos (PCLATH, INTCON, etc.) PORTB PORTC PORTD PORTE PCLATH INTCON PIR1 PIR2 06h 07h 08h 09h 0Ah 0Bh 0Ch 0Dh TRISB TRISC TRISD TRISE PCLATH INTCON PIE1 PIE2 86h 87h 88h 89h 8Ah 8Bh 8Ch 8Dh Bank0 Bank1

12 Registro STATUS Contiene: RP1 RP0 RP1 RP0 BANK0 BANK1 IRP RP1 RP0 TO
PD Z DC C RP1 RP0 RP1 RP0 1 BANK0 BANK1 Contiene: – Estado Artmético de la ALU – El estado del RESET – Bit selectores del Banco de memoria BANK2 BANK3 Bit Indirect Register Bank Select : (usados para direcciionamiento Indirecto) 1 = Bank 2,3 0 = Bank 0,1

13 35 instrucciones de palabra simple
PIC16 Set de Instrucciones 35 instrucciones de palabra simple Todas se ejecutan en un ciclo escepto los saltos Byte Oriented Operations Bit Oriented Operations addwf andwf clrf clrw f,d f f,d d f - Add W and f AND W with f Clear f Clear W bcf bsf btfsc btfss f,b f f,b b Bit Clear f Bit Set f Bit Test f, Skip if Clear Bit Test f, Skip if Set comf f,d Complement f Literal and Control Operations decf decfsz incf incfsz iorwf movf movwf nop rlf rrf subwf swapf xorwf f,d f f,d d f - Decrement f Decrement f, Skip if 0 Increment f Increment f 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 addlw andlw call clrwdt goto iorlw movlw retfie retlw return sleep sublw xorlw k - 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

14 mc mc Herramientas de Desarrollo
Programación PIC® Avanzada Rango Medio Herramientas de Desarrollo mc mc

15 MPLAB IDE MPLAB® IDE (Integrated Development Environment)
Integrates different Microchip and third party tools Code Editor Cross Compilers Assemblers Simulators, In-Circuit Debuggers, Emulators Programmers

16 MPLAB IDE MPLAB® IDE (Integrated Development Environment)
Integrates different Microchip and third party tools Code Editor Cross Compilers Assemblers Simulators, In-Circuit Debuggers, Emulators Programmers

17 MPLAB® ICD 2 es un programador-- debugger de bajo costo.
ICD 2 (Debugger In Circuit ) MPLAB® ICD 2 es un programador-- debugger de bajo costo. Lee/Escribe el espacio de memoria y areas EEDATA de los PIC Programa bits de Configuración Debugging in circuit Borrado de Memoria de Programa con verificación

18 PICDEM® 2 Plus Board 18, 28 and 40- Herramienta PICDEM2 16 x 2 LCD
Module Analog Pot 9V to 5V regulator RS232 Connecto r LEDs 18, 28 and 40- pin DIP sockets Push button Switches ICD Connecto r Piezo Buzzer I2C Based Temp Sensor

19 Programación PIC® Avanzada Rango Medio
Interrupciones mc

20 Querer a menudo que el procesador realizara una tarea si ocurre un
Interrupciones y Polling Querer a menudo que el procesador realizara una tarea si ocurre un acontecimiento específico Dos métodos para comprobar si ha ocurrido este acontecimiento: Polling (Interrogación): Comprueba continuamente para saber si hay acontecimiento en varios puntos en el código Interrupts: “INTERRUPTS”El programa principal pasa a la subrutina de interrupción cuando ocurre un evento

21 Polling NO bsf PORTA,1 ;Set bit 1 of ;PORTA RA<1> = 1
btfss INTCON,TMR0IF ;Check Timer0 ;interrupt flag ;in “INTCON” ;register and ;skip the next ;instruction if ;it is set TMR0IF = 1 ?? YES NO goto $-1 ;Go to ;previous RA<1> = 0 ;instruction bcf PORTA,1 ;Clear bit of ;PORTA

22 Interrupciones Reset ;========================= int_vector code 004h
goto Start no interrupt Reset ;========================= int_vector code h Main program execution Interrupt Service Routine (ISR) ;return from retfie instruction interrupt flag set retfie ;interrupt ;========================= Execute ISR at address 004h main_prog code Start ;start label for main code end Main program code

23 Habilitando Interrupciones
El Procesador debe saber que interrupciones serán habilitadas Un número de registros con los bits de habilitación de interrupciones hacen esto: Control de Interrupciones (INTCON) Habilitador de Interrupción de Periféricos 1 (PIE1) Habilitador de Interrupción de Periféricos 2 (PIE2)

24 Lógica de Interrupción
TMR0IE TMR0IF INTE INTF RBIE RBIF TMR2IE TMR2IF ADIE ADIF Otros Periféricos Interrupt GIE PEIE

25 (Corazón de las Interrupciones)
Registro INTCON (Corazón de las Interrupciones) Setea el uso de cualquier interrupción interrupcioón por Periféricos EnableBits Description GIE Global Interrupt Enable PEIE Peripheral Interrupt Enable TMRIE Timer0 Interrupt Enable INTE External Interrupt Enable RBIE PORTB change Interrupt Enable GIE PEIE TMR0IE INTE RBIE TMR0IF INTF RBIF FlFlagBitsBit DDescriptioniti TMR0IF Timer0 Overflow Interrupt Flag INTF RB0/INT External Interrupt Flag RBIF PORTB Change Interrupt Flag Flags avisan de la interrupción producida!

26 Habilitando el nucleo de las
interrupciones Int_vect CODE 004h ;clear external interrupt ;flag to enable ;further interrupts bcf INTCON,INTF <ISR code> retfie “goto $” address Program Counter Stack INTCON Main CODE Start 0 1 GIE 0 1 INTE 0 1 INTF <code to set up PORTB > ; initialize INTCON clrf INTCON ;enable an external ;interrupt on the INT pin bsf INTCON,INTE ;enable global interrupts bsf INTCON,GIE ; sit here and loop forever goto $

27 Interrupción de Periféricos
Dos registros Habilitan interrupción desde Periféricos – Peripheral Interrupt Enable 1 (PIE1) – Peripheral Interrupt Enable 2 (PIE2) Dos registros muestran la petición para una interrupción (Flags) – Peripheral Interrupt Request 1 (PIR1) – Peripheral Interrupt Request 2 (PIR2) *Los Flags se activaran incluso si no estan habilitadas las interrupciones!!

28 PIE1 Register (Peripheral Interrupt Enables)
RegistrosPIE1 y PIR1 * PIE1 Register (Peripheral Interrupt Enables) ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE PIR1 Register (Peripheral Interrupt Requests) ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF Enable Flag Condition ADIE ADIF ADCconversioncomplete RCIE RCIF AUSARTreceivebufferisfull TXIE TXIF AUSARTtransmitbufferisfull SSPIE SSPIF 2 ICorSPIInterrupt CCP1IE CCP1IF Timer1registercaptureorcomparematch TMR2IE TMR2IF Timer2valueandPR2periodvaluematch TMR1IE TMR1IF Timer1registerghasoverflowed *Check individualmente los data sheets para localizar los bits

29 PIE2 Register (Interrupt Enables)
Registros PIE2 y PIR2 * PIE2 Register (Interrupt Enables) OSCFIE C2IE C1IE EEIE BCLIE ULPWUIE CCP2IE PIR2 Register (Interrupt Flags) OSCFIF C2IF C1IF EEIF BCLIF ULPWUIF CCP2IF Enable Flag Condition OSCFIE OSCFIF SystemOscillatorFailed C2IE C2IF Comparator2outputchanged C1IE C1IF CComparator1t1outputttchangedhd EEIE EEIF Writeoperationcompleted BCLIE BCLIF 2 BuscollisionoccurredinMSSPICmode ULPWUIE ULPWUIF Wake-upconditionoccurred CCP2IE CCP2IF Timer1CaptureporComparepmatchoccurred * Check individualmente los data sheets para localizar los bits

30 Habilitando la interrupción de un
periférico (Timer 1) 004h Int_vect CODE “goto $” address Program Counter Stack banksel PIR1 bcf PIR1, TMR1IF <ISR code> retfie INTCON GIE PEIE Main Start CODE banksel bcf PIR1 PIR1,TMR1IF banksel bsf PIE1 PIE,TMR1IE PIE1 1 bsf INTCON,PEIE bsf INTCON,GIE <code to set up Timer1> ; sit here and loop forever goto $ TMR1IE 0 1 TMR1IF PIR1 Timer1 Overflow!

31 Latencia de Interrupción:
Tiempo desde que se produce la interrupción y el PC direcciona 0004h Interrupción sincrónica (typ. Inter.) latencia es de 3 ciclos de instrucción (Tcy) Interrupción asincrónica (typically external) latencia es de 3 – 3.75 cyclos de instrucción

32 Durante una interrupción solo es salvado el contexto:
Salvando el contexto Durante una interrupción solo es salvado el contexto: Solo es salvado el PC (sobre el stack) Registros son cambiados en la rutina de interrupción. Deben ser salvados los registros: Working (W) Status PCLATH (Program Counter Latch High) Registros definidos por el usuario

33 Los microcontroladores del PIC de Rango medio tratan todas las
Prioridad de interrupción Los microcontroladores del PIC de Rango medio tratan todas las interrupciones con la misma prioridad El usuario debe hacer lo siguiente: Determine la fuente de interrupción Determine el orden en el cual las interrupciones son atendidas.

34 Ejemplo de Prioridad de
Interrupciones 0x ;interrupt vector location INT_VECTOR CODE ;Save context movwf swapf temp_w STATUS,w temp_status ;save WREG ;movf affects Z bit, ;use swapf instead ;save STATUS register ;Check flags in order of priority btfsc call Restore_context: swapf movwf movf retfie INTCON,RBIF PORTB_ISR PIR1,TMR2IF Timer2_ISR PIR2,TMR1IF Timer1_ISR temp_status,w STATUS temp_w,w ;PORTB change? ;Timer2 interrupt? ;Timer1 interrupt? ;restore STATUS reg ;restore WREG ;return from interrupt

35 Programación PIC® Avanzada Rango Medio
Periféricos mc

36 Periféficos del Rango medio
I/O Ports Timers (0, 1, 2) Capture/Compare/PWM Comparadores ADC AUSART I2C y SPI Serial Interfaz

37 Alta capacidad de corriente 25mA
I/O Revisión Hasta 35 ports I/O multiplexados con funciones de Periféricos Alta capacidad de corriente 25mA Manipulación directa de bits en un ciclo Todos los I/O tienen protección ESD Despues del Reset: Los pines con capacidad analógica estan activos Los pines I/O Digitales son configurados como entradas

38 Cada PORT (A, B, C, D, E) tiene un tiene un
Registro PORTx y TRISx Cada PORT (A, B, C, D, E) tiene un tiene un registro de dirección TRISx PORTB Register RB7 RB6 RB5 RB4 RB3 RB2 RB1 RB0 Dato Configura Dirección del Dato PORTB Tri-State Register (TRISB) TRISB7TRISB6TRISB5TRISB4TRISB3TRISB2TRISB1TRISB0 1 = corresponding PORTB pin is an INPUT 0 = corresponding PORTB pin is an OUTPUT

39 Configurando entradas analógicas como digitales
I/O’s con capacidades analógicas por default son analógicas sobre el reset

40 Port Configuration Bits
Configurando entradas analógicas como digitales Para configurar las entradas analógicas como digitales existen 2 vías: 1) Registro Selectros Analógico (ANSEL and ANSELH) Fara dispositivos con > 8 pines analógicos O 2)Registro ADC Control 1 (ADCON1) Para dispositivos con < 8 pines analógicos Analog Select Register (ANSEL) ANS7 ANS6 ANS5 ANS4 ANS3 ANS2 ANS1 ANS0 Analog Select High Register (ANSELH) ANS13 ANS12 ANS11 ANS10 1 = Pin assigned as Analog Input 0 = Digital I/O ANS9 ANS8 Port Configuration Bits ADC Control Register 1 (ADCON1) ADFM ADCS2 PCFG3 PCFG2 PCFG1 PCFG0

41 Configurando entradas analógicas para
Digital PCFG AN7 AN6 AN5 AN4 AN3 AN2 AN1 Vdd AN0 <3:0> Port Configuration Bits ADC Control Register 1 (ADCON1) ADFM ADCS2 PCFG3 PCFG2 PCFG1 PCFG0

42 Inicializando Digital I/O
Inicialización PORTB – RB4 a RB7 como entrada Digital – RB0 a RB3 como salida Digital ; configure PORTB for digital banksel clrf PORTB ANSELH ;Go to bank containing PORTB register ;Initialize PORTB data ;Go to bank containing ANSELH register ;Set as all digital ; Set up direction of each PORTB pin banksel movlw movwf TRISB b’ ’ ;Go to bank containing TRISB register ;Move value to set TRISB<7:4> high and ;TRISB<3:0> low into W register ;Move value in W into TRISB

43 1 1 RB3 RB4 Opciones PORTB Interrupción & Pull-Up
Todos los pines del PORTB tiene interrupción por cambio y Pull UP Registro del Pull-Up PORTB (WPUB) 1 WPUB7 WPUB6 WPUB5 WPUB4 WPUB3 WPUB2 WPUB1 WPUB0 1 = Pull-up enabled Dispositivos sin registro WPUB 0 = Pull-up disabled usan bit RBPU en el OPTION Interrupción sobre Cambio PORTB Registro (IOCB) IOCB7 IOCB6 IOCB5 IOCB4 ICOB3 IOCB2 IOCB1 IOCB0 1 = Interrupt-on-change enabled Los dispositivos sin IOCB 0 = Interrupt-on-change disabled HIGH LOW Registro de Control de Interrupción (INTCON) GIE PEIE TMR0IE INTE RBIE TMR0IF INTF RBIF *PORTB debe primero ser leído/ser escrito y entonces RBIF se puede borrado por software RB3 RB4 1 confían en bit de RBIE en INTCON

44 g Timers mc

45 Timers son usados para:
tiempo de referencia para eventos contar el número de eventos generaciáon de formas de onda etc... PIC16F877 tiene3 timers Timer0 Timer1 Timer2

46 Timer Comparación TIMER0 TIMER1 TIMER2 SIZE OF REGISTER CLOCK SOURCE
8-bits (TMR0) Fosc/4 16-bits (TMR1H:TMR1L) Fosc/4 8-bits (TMR2) Fosc/4 (Internal) CLOCK SOURCE (External ) CLOCK SCALING AVAILABLE (Resolution) INTERRUPT EVENT and FLAG LOCATION CAN WAKE PIC FROM SLEEP? T0CKI pin Prescaler 8-bits (1:2 1:256) On overflow FFh 00h (TMR0IF in INTCON) NO T1CKI pin or Timer 1 oscillator (T1OSC) Prescaler 3-bits (÷1,÷2,÷4,÷8) On overflow FFFFh h (TMR1IF in PIR1) YES None Prescaler (1:1,1:4,1:8) Postscaler (1:1 1:16) TMR2 matches PR2 (TMR2IF in PIR2) NO

47 Timer 0 Diagrama en Bloques
DATA BUS Fosc/4 8 synchronize T0CKI pin Watchdog Timer OPTION register scaled clock prescaler TMR0 PS2 PS1 PS0 TMR0 RATE 1:2 1 1:4 1:8 1:16 1:32 1:64164 1:128 1:256 WDT out RBPU INTEDG TOCS TOSE PSA PS2 PS1 PS0 Prescaler Rate Select Bits Prescaler Assignment 1= prescaler assigned to WDT 0= prescaler assigned to Timer Source Edge Select 1 = increment TMR0 on high-to-low transition 0 = increment TMR0 on low-to-high transition TMR0 Clock Source Select 1 = TOCK1, 0 = Fosc/4

48 Timer 0 Diagrama en Bloques
DATA BUS Fosc/4 8 synchronize T0CKI pin scaled clock prescaler TMR0 Watchdog Timer INTCON register TMR0IF • Si la fuente de clock es externa puede sincronizarse (TOCKI) para el clock interno • Timer 0 es de lectura y escritura •Timer 0 el flag es seteado sobre undesborde del TMR0 (FF to 00)

49 Timer0 Inicialización 0 1 0 1 0 1 0 1 0 1 0 1 1 0 0 1 01 Timer0
incrementing ;Make sure the Timer0 count ;register (TMR0) is clear banksel TMR0 clrf TMR0 TMR0 INTCON Flag on overflow ;Clear Timer0 interrupt flag bcf INTCON,TMR0IF ;Setup the Option register to 01 TMR0IF ;increment Timer0 from internal ;clock with a prescaler of 1:16 banksel OPTION_REG movlw b’ ’ This interrupt flag will set on Timer0 overflow even if interrupts are disabled movwf OPTION_REG OPTION_REG TOCS PSA PS<2:0> Prescaler Assignment (External or Internal) (WDT or TMR0) ;The TMR0 interrupt is disabled, do ;polling on the flag bit (TMR0IF) btfss INTCON,TMR0IF goto $-1 <continue> Selects Timer 0 Prescaler Clock Source value = 1:16

50 Timer1 Diagrama en Bloques
T1OSI T1OS0 T1 OSC synchronize prescaler Fosc/4 T1CKI pin Timer1 Control Register (T1CON) TMR1H TMR1L Enable TMR1ON T1GINV TMR1GE T1CKPS1T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON T1CKPS1 T1CKPS0 scale 1 1:8 1:4 1:2 1:1 Timer1 On 1 = Enable Timer1 LP Oscillator Enable 1 = T1OSC selected 0 = T1CKI can be used Clock Source Select 1 = External (T1CKI) 0 = Internal (FOSC/4)

51 Timer1 Diagrama en Bloques
T1OSI T1OS0 T1 OSC synchronize prescaler Fosc/4 T1CKI pin Timer1 Control Register (T1CON) TMR1H TMR1L Enable TMR1ON T1GINV TMR1GE T1CKPS1T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON Timer1 Gate Enable and Timer1 Gate Invert are available on some devices Timer1 External Clock Input Synchronization 1 = do not synchronize external clock input 0 = synchronize external clock input with internal clock (Fosc/4)

52 PIR1 PIE1 Main Code ;Start by clearing the Timer1 interrupt flag
Timer1 Setup de Interrupción TMR1H TMR1L Main Code ;Start by clearing the Timer1 interrupt flag banksel PIR1 bcf PIR1, TMR1IF ;Enable Timer1 interrupt banksel PIE1 bsf PIE1, TMR1IE PIR1 PIE1 01 TMR1IF 1 TMR1IE ;Enable Global and Peripheral Interrupts bsf INTCON, PEIE INTCON, GIE INTCON 1 1 GIE PEIE

53 0 0 1 1 0 0 0 1 0 Timer1 Inicialización TMR1H banksel TMR1H clrf TMR1H
;Make sure the TMR1 registers are clear banksel TMR1H clrf TMR1H clrf TMR1L ;Make sure the TMR1IF flag in PIR1 ;is cleared banksel PIR1 bcf PIR1,TMR1IF ;Setup T1CON register for internal clock ;with 1:8 prescaler, Timer1 is stopped ;and T1 osc is disabled movlw b’ ’ PIR1 (Peripheral Interrupt Request) TMR1IF movwf T1CON T1CON (Timer1 Control) ;Start Timer1 incrementing bsf T1CON, TMR1ON ;The TMR1 interrupt is disabled, do ;polling on the Timer1 flag bit btfss PIR1, TMR1IF goto $-1 Input clock prescale bits (T1CKPS<1:0>) TMR1ON Clock source select bit (TMR1CS) Timer1 oscillator enable bit (T1OSCEN)

54 Timer2 Diagrama en Block
TMR2 OUTPUT Postscaler 1: :16 TMR2 COMPARATOR Prescaler 1:1, 1:4, 1:16 Fosc/4 PR2 Timer2 Control Register (T2CON) TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON T2CKPS1 T2CKPS0 Timer2 ON 1 = Timer2 enabled T2CKPS1 T2CKPS2 Scale 1:1 1 1:4 X 1:16

55 Timer2 Diagrama en Block
TMR2 OUTPUT Fosc/4 TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 SCALE 1:1 1 1:2 1:3 1:4 1:5 1:6 1:7 1:8 1:9 1:10 1:11 1:12 1:13 1:14 1:15 1:16 Postscaler 1: :16 COMPARATOR Timer2 Control Register (T2CON) TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON T2CKPS1 T2CKPS0 Timer2 ON 1 = Timer2 enabled T2CKPS1 T2CKPS2 Scale 1:1 1 1:4 X 1:16

56 Timer2 Diagrama en Block
Start Timer2 Counting TMR2 COMPARATOR TMR2 OUTPUT Postscaler 1: :16 Prescaler 1:1, 1:4, 1:16 Fosc/4 PR2 Load Period Register PIR1 1 TMR2IF Flag set on first match with postscaler = 1:1 Timer2 Control Register (T2CON) TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON T2CKPS1 T2CKPS0

57 PIE1 (Peripheral Interrupt Enable) TMR2IE
Timer2 Incrementing TMR2 (Timer2 Counter) ;Disable the Timer2 interrupts in the PIE1 ;register. Make sure the Timer2 interrupt ;flag in PIR1 is cleared. banksel PIE1 bcf PIE1,TMR2IE banksel PIR1 bcf PIR1,TMR2IF ;Setup T2CON register for Postscaler = 1:15, ;Prescaler = 1:16, Timer2 off movlw b’ ’ movwf T2CON ;Make sure the TMR2 register is clear banksel TMR2 clrf TMR2 ;Load the Period register banksel PR2 movlw b’ ’ movwf PR2 ;Start Timer2 incrementing g PIE1 (Peripheral Interrupt Enable) TMR2IE PIR1 (Peripheral Interrupt Request) 01 TMR2IF Flag is set T2CON (Timer2 Control) banksel bsf T2CON T2CON,TMR2ON ;The Timer2 interrupt is disabled, do ;polling on the Timer2 interrupt flag btfss PIR1,TMR2IF goto $-1 TMR2ON Prescaler = 1:16 (T2CKPS<1:0>) Postscaler = 1:15 (TOUTPS<3:0>)

58 g Módulo Capture/Compare/PWM mc

59 * Modulo interfaces con Timers 1 y 2
Captura/Compara/PWM Captura – Temporiza la duración de un evento externo aplicado a una entrada Compara – Cambia un pin de salida o genera una interrupción cuando una cantidad de tiempo especificado ha pasado Pulso modulado en ancho(PWM) – Crea una señal de indas cuadrada de frecuencia fija y período variable Provee características mejoradas para la conexión de varios puentes * Modulo interfaces con Timers 1 y 2

60 CCP Registro de Control
CCP1 Control Register (CCP1CON) P1M P1M CCP1X CCP1Y CCP1M3 CCP1M2 CCP1M1 CCP1M0 BIT FUNCTION CCP1M<3:0>CCP1M3:0 CCPModeSelectBitsconfigurethemoduleasInputCapture, OOutputttCompare,CorPWM CCP1<X:Y> PWMdutycycle2LSB’s(8MSB’slocatedinCCPR1L) P1M<1:0> ThesePWMoutputconfigurationbitsareavailableforEnhanced CCP(ECCP)modulesonly.Theyprovidehalf-bridgeorfull-bridge outputsteeringcontrol.

61 CCP Registro de Control
CCP1 Control Register (CCP1CON) P1M P1M CCP1X CCP1Y CCP1M3 CCP1M2 CCP1M1 CCP1M0 CCPxM CCPxM2 CCPxM1 CCPxM0 CCPModeSelected FUNCTION Capture/Compare/PWMoff(resetsCCPmodule) 1 Unused(reserved) PWM1duty 20 (8MSB’sComparelocatedmode,intoggleCCPR1L)outputonmatch Capturemode,everyfallingedge Capturemode,everyrisingedge Capturemode,every16thrisingedge Comparemode,setoutputonmatch Comparemode,clearoutputonmatch CComparemode,generatesoftwarefinterruptonmatch Comparemode,triggerspecialevent x PWMmode

62 Modo Captura TMR1L TMR1H CCPRxH CCPRxL Prescaler CCPxIF in PIRx
÷1 1, 4 4, 16 Edge Detect and CCPxIF in PIRx TMR1L Single Buffered CCPx TMR1H System Clock (Fosc) CCPRxH CCPRxL P1M1 P1M0 CCP1X CCP1Y CCP1M3 CCP1M2 CCP1M1 CCP1M0 CCPxCON

63 Captura Inicialización
TMR1H TMR1L TIMER1 INCREMENTING!! CCPR1H CCP1 ;Turn off CCP module banksel CCP1CON clrf CCP1CON ;Make sure Timer1 is off bcf T1CON,TMR1ON nd ;Clear Timer1 registers Rising Edge clrf TMR1H clrf TMR1L Pin 01 0 Current Timer10 Value th rd st Detected!! ;Disable all interrupts for CCP bcf PIR1,CCP1IF banksel PIE1 bcf PIE1,CCP1IE ;Set CCP1 pin for input bsf TRISC,2 ;Set Capture for every 4th rising edge banksel CCP1CON CCPR1L PIR1 CCP1CON Captured! 01 CCP1IF 1 0 0 1 movlw movwf b’ ’ CCP1CON ;Start Timer1 incrementing bsf T1CON,TMR1ON ;Test the interrupt flag for capture btfss PIR1,CCP1IF goto $-1 T1CON 0 1 TMR1ON

64 enabled)SpecialEvent
Modo Compara TMR1H TMR1L CCPxIF in PIRx COMPARATOR NO CCPxM3 CCPxM2 CCPxM1 CCPxM0 MODE 1 = SetoutputonOUTPUTmatch(CCPxIFisset) Clearoutputonmatch(CCPxIFisset) Generatesoftwareinterruptonmatch (CCPxIFissetCCP1pinunaffected) CCPRxL Triggerspecialevent (CCPxIFisset,CCP1resetsTMR1or TMR2andstartsanA/Dconversionif enabled)SpecialEvent Trigger P1M1 P1M0 CCP1X CCP1Y CCP1M3CCP1M2CCP1M1CCP1M0

65 1 0 1 0 1 0 Compara Inicialización banksel CCP1CON clrf CCP1CON
;Turn off the CCP module banksel CCP1CON clrf CCP1CON ;Turn off Timer1 bcf T1CON,TMR1ON ;Clear Timer1 result registers clrf TMR1H TMR1H clrf TMR1L ;Disable CCP1 interrupt and make sure ;its flag is clear banksel PIE1 bcf PIE1,CCP1IE banksel PIR1 bcf PIR1,CCP1IF ;Make CCP1 pin output CCPR1H CCPR1L banksel bcf TRISC TRISC,2 T1CON ;Initialize Compare to set output on match banksel CCP1CON 1 0 movlw b’ ’ movwf CCP1CON ;Load Compare value into CCPR1H:CCPR1L TMR1ON CCP1CON banksel movlw CCPR1H b’ ’ 1 0 movwf CCPR1H clrf CCPR1L ;Start Timer1 incrementing bsf T1CON,TMR1ON ;Test CCP1IF for Timer1 match with CCPR1x PIR1 1 0 btfss goto PIR1,CCP1IF $-1 CCP1IF

66 Modo PWM Genera un pulso modulado en su ancho
(PWM) sobre los pines CCP1 y CCP2 El Duty cycle, periodo y resolucion estan determinados por los siguientes registros Register Description PR2 PeriodRegister T2CON Timer2Control CCPRCCPRxLL 2DDutytCCyclelRRegistersit CCPxCON 2CCPControlRegisters

67 PWM Diagrama en Block CCPR1L VALUE CCPR1H COMPARATOR TMR2 = CCPR1H
Period 1 Period 2 CCPR1L VALUE CCP1<X:Y> DOUBLE BUFFER CCPR1H LATCH 10 COMPARATOR Period Start CCP1 Output Pin TMR2 = CCPR1H 10 TMR2incrementing 8 R Latch S Reset to 0’s 0 1 CCP1 pin (1) COMPARATOR TMR2 = PR2 8 PR2 Note (1): TMR2 is concatenated with the 2-bit FOSC, or 2-bits from Prescaler to create 10-bit time base

68 0 0 0 0 0 1 0 0 PWM Inicialización TMR2 0 0 0 1 1 1 1 1
;Turn off CCP1 pin by setting TRISC bit HIGH banksel TRISC bsf TRISC, ;configure pin as input PR2 ;Clear Timer banksel TMR2 clrf TMR2 ;Set up Period and Duty CCPR1L Cycle movlw movwf b’ ’ PR2 b’ ’ CCPR1L ; ;Load a Period Value ;Load Duty Cycle Value CCP1CON duty cycle PWM Mode LSBs CCP1M <3:0> CCP1<X:Y> ;Configure CCP module for PWM ;and LSB’s of Duty Cycle = b’10’ movlw b’ ’ movwf CCP1CON ;Turn CCP1 pin back on (make it an output) T2CON banksel TRISC bcf TRISC,2 ;Start the PWM by turning on Timer2 ;Configure Prescaler and Postscaler to 1:1) movlw b’ ’ movwf T2CON Prescaler bits TOUTPS<3:0> Prescaler bits T2CKPS<1:0> TMR2ON

69 g Comparadores mc

70 Módulo Comparador: Compara una voltaje analógico de entrada
Comparadores Revisión Módulo Comparador: Compara una voltaje analógico de entrada con una referencia y genera un estado de salida Vref Vin + Comp - Vout Analog Input (Vi in) Reference Voltage (Vref) Output (Vout)

71 El Voltaje de referencia puede ser:
Voltaje de Refencia del Comparador El Voltaje de referencia puede ser: – Externo desde un pin de un dispositivo – Internamente generado por el Generador de Refencia interno Provee 16 Voltaje seleccionables desde ) a 75% de VDD Algunos dispositivos tienen refencia fija (0.6V) – Independiente de VDD VREF+ VRSS = 1 VRR 8R R R R R VRSS = 0 V To Comparators and ADC Module CVREF VROE 8R CVREF DD 15 VREN VREF- VRSS = 1 VRSS = 0 4 VR<3:0>

72 Comparador Interrupciones
Una interrupción ocurre cuando cambia la salida de un comparador – Algunos dispositivos comparten un Flag para ambos comparadores – Lgunos Dipositivos tienen Flags independientes Debe leer la salida del comparador antes de borrar el flags de interrupción – Las salidas se encuentran en el registro de control del comparador (CMCON o CMxCON0)

73 Comparadores y Modo Sleep
Comparadores permanecen activos en modo Sleep – Una cambio en una salida del comparador despierta al nucleo Despues de un despertar , la instrucción siguiente a la instrucción SLEEP o un Servicio de Interrupción (ISR) es ejecutado

74 g Conversor Analógico a Digital (ADC) mc mc

75 Módulo conversor ADC Convierte una señal analógica de entrada en un
ADC Revisión Módulo conversor ADC Convierte una señal analógica de entrada en un valor binario de 8 o 10-bit Voltaje de refencia interno o externo seleccionable Una interrupción puede ser generada después que ha finalizado una conversión La interruopción puede despertar al PIC del SLEEP ADC Analog Input Digital Output

76 ADC Control Register 0 (ADCON0)
ADC Registro de control El ADC tiene implementado 2 registros de control – ADCON0 y ADCON1 – Dispositivos con > 8 entradas analógicas no tienen los mismos bits mostrados abajo ADC Control Register 0 (ADCON0) ADCS1 ADCS0 CHS2 CHS1 CHS0 GO/DONE ADON BIT FUNCTION ADCS<1:0> A/DConversionClockSelectbits UUsewithithADCS2iinADCON1 CHSxbits AnalogChannelSelectbits GO/DONE 1=A/DConversioninprogress 0=A/DConversioniscompleted ADON EnablestheADCmodule

77 ADC Control Register 1 (ADCON1)
ADC Registro de control El ADC tiene implementado 2 registros de control – ADCON0 y ADCON1 – Dispositivos con > 8 entradas analógicas no tienen los mismos bits mostrados abajo ADC Control Register 1 (ADCON1) ADFM ADCS2 PCFG3 PCFG2 PCFG1 PCFG0 BIT FUNCTION ADFM ADCResultRegistersFormatbit 1=RightJustified,0=LeftJustified ADCS2 A/DConversionClockSelectbit UsewithADCS<1:0>inADCON0 PCFG<3:0> PortConfigurationBits ConfiguresI/Oasanalogordigital

78 10 bit ADC el reultado es almacenado en dos registros
ADCRegistro de Resultado 10 bit ADC el reultado es almacenado en dos registros ADRESH y ADRESL Justificado a la Izquierda o a la Derecha Determinado por el Bit Selector de Formato (ADFM) en el registro ADCON1 ADRESH MSB ADRESL LSB Justificado a la Izquierda (ADFM = 0) ADRESH ADRESL MSB LSB Justificado a la derecha (ADFM = 1)

79 Diagrama del Módulo ADC
Conversion clock scaler Fosc VREF+ pin Start Conversion Conversion Complete ADRESH ADRESL Left Justified Right Justified VREF- AN0 AN1 AN2 AN3 AN4 AN5 AN6 AN7 ADC Holding Capacitor ADCON0 ADCS1 ADCS0 CHS2 CHS1 CHS0 GO/DONE ADON Vss ADCON1 ADFM ADCS2 PCFG3 PCFG2 PCFG1 PCFG0

80 Diagrama del Módulo ADC
PCFG AN7 AN6 AN5 AN4 AN3 AN2 AN1 Vdd AN0 <3:0> Fosc clock scaler Conversion Port Config Bits VREF+ pin Start Conversion Conversion Complete ADRESH ADRESL Left Justified Right Justified VREF- AN0 AN1 AN2 AN3 AN4 AN5 AN6 AN7 ADC Holding Capacitor ADCON0 ADCS1 ADCS0 CHS2 CHS1 CHS0 GO/DONE 0 1 ADON Vss ADCON1 ADFM ADCS2 1 0 PCFG3 PCFG2 PCFG1 PCFG0

81 Timing consideraciones para el ADC
Cuando un canal A-a-Des seleccionadolleva un tiempo para que el capacitor de HOLD sea cargado Todas las conversiones de 10 bit llevan 11 cyclos para completarse El usuario debe seleccionar la sincronización apropiada del ADC basada en la frecuencia de reloj de sistema

82 g UART Direccionable (AUSART) mc mc

83 AUSART Revisión Comunicaciones I/O serie con Periféricos
– Antiguamente se la denominaba Unidad de Comunicaciones Serie(SCI) Funciones Principales: – Puede ser sincrónica o asincrónica – Puede recibir y transmitir Full-duplex asincrónica transmite y recibe Half-duplex sincrónica Master o eslave Ciomunmente usada – RS-232 para comunicarse con la PC Necesita Driver para RS-232 Características Mejoradas(EUSART) permite interface con un sistema de bus Red de Area Local (LIN)

84 AUSART Registros Registro generador de Baud rate
– SPBRG (8 bit para AUSART) – SPBRG y SPBRGH (16 bit para EUSART) Transmisor status y control – TXSTA Receptor status y control – RCSTA Transmisor Regitro data – TXREG Receptor Registro data – RCREG

85 Registro TXSTA CSRC TX9 TXEN SYNC SENB BRGH TRMT TX9D Bit Function
ClockSourceSelect 1=MasterMode(clockgeneratedinternallyfromBRG) 0=SlaveMode(clockfromexternalsource) TX9 Ninthbittransmissionenable TXEN TransmitEnablebit,1=Txenabled,0=Txdisabled SYNC AUSARTMode,1=SynchronousMode,0=AsynchronousMode SENB ForEUSARTonly 1=Sendsyncbreakcharacterbit 0=Syncbreaktransmissioniscompleted BRGH BBauddRRatetSSelect,lt1=HiHighhSSpeed,d0=LLowSSpeedd TRMT TransmitShiftRegister(TSR)status 1=TSRempty,0=TSRisfull TX9D Ninthbitoftransmitdata

86 Registro RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D Bit Function
SerialPortEnable 1=Serialportenabled(configuresRX/DTandTX/CKpinsasserialportpins) 0=Serialportdisabled RX9 1=Enable99-bitbitdatareception,0=88-bitbitdata SREN Synchronousmode(Master),1=enablesingleRx,0=disablesingleRx CREN ContinuousReceiveEnable,1=enable,0=disable ADDEN AddressDetectEnablebit 1=enable(enableinterruptandloadtheRxbufferwhenRSR<9>isset) th 0=disableanduse9bitforparity FERR 1=framingerroroccurred(Stopbitnotdetected) OERR 1=Overrunerroroccurred(FIFOwasstillfullwhenotherdatawas loaded) RX9D Ninthbitofreceiveddata

87 Transmisor Diagrama en Bloques
DATA BUS TXIE TXREG Interrupt TXIF Set TXIF LSB Clear TXIF Pin Buffer and Control SPEN MSB TXEN TX/DT pin Transmit Shift Register (TSR) Enables Serial Port Baud Rate Generator TRMT TX9D TX9 Ninth data bit Set TRMT bit Indica registro de desplazamiento esta vacio Clear TMRT bit TSR tiene datos en él

88 RX/DT pin Data Bus Receptor Diagrama en Block Enable Serial Port SPEN
Receive Shift Register (RSR) STOP RX/DT pin Pin Buffer and Control Data Recovery START RX9 Baud Rate Generator FIFO Set RCIF flag Clear RCIF flag RCIE RCREG RX9D RCIF Interrupt Data Bus

89 g MASTER SYNCHRONOUS SERIAL PORT (MSSP) mc

90 Cubriremos solo Modo I2C
MSSP Revisión El MSSP puede operar en uno de estos dos modos: – SPI (Serial Peripheral Interface) Usa 3 pins – Serial Data Out (SDO) – Serial Data In (SDI) – Serial Clock (SCK) – I2C (Inter-Integrated Circuit) Modo Full Master Modo Slave (con dirección de llamada general) Usa 2 pins – Serial Clock (SCL) – Serial Data (SDA) El Registro de Control MSSP (SSPCON) determina en qué modo usted está. Cubriremos solo Modo I2C

91 I Condiciones Condiciones : 2C ACKNOWLEDGE (A) REINICIA (R)
– START (S) – STOP (P) SDA SCL SDA released LOW while SCL is still HIGH pulled Stop condition quickly during followed LOW clock condition of SCL SDA SDA goes LOW by a9th Start pulse ACKNOWLEDGE (A) REINICIA (R) NEGATIVO o NO -ACKNOWLEDGE (N)

92 Leer un IC EEPROM Externo
+5V SCL SDA MASTER WRITE ADDRESS READ GOTO STOP DATA MODE BUSY BUSY PIC EEPROM RESTART ADDRESS LISTEN LISTEN EEPROM DATA LISTEN Esclavo SLAVE STOP ACK NACK MEMORY START ACK ADDRESS

93 1 of 3: MSSP Status Register (SSPSTAT)
2 1 of 3: MSSP Status Register (SSPSTAT) SMP CKE D/A P S R/W UA BF CONTROL BITS DETECTION BITS (FLAGS) CKE 2 NotusedinICmode BF TheSSPBUFregisterisfull

94 2 of 3: MSSP Control Register 1 (SSPCON)
WCOL SSPOV SSPEN CKP SSPM3 SSPM2 SSPM1 SSPM0 CONTROL BITS DETECTION BITS (FLAGS) BIT FUNCTION WCOL WriteCollisionDetected SSPOV AwritetotheSSPBUFbeforepreviousvalueprocessed SSPEN EnablesMSSPmodule CKP Enablesclock SSPM3 ModeSelectBit SSPM2 SSPM1 SSPM0

95 MSSP Registros de Control
(I C mode) 2 SSPM3 SSPM2 SSPM1 SSPM0 Mode SPIMastermode,clock=FOSC/4 1 SPIMastermode,clock=FOSC/16 SPIMastermode,clock=FOSC/64 SPIMastermode,clock=TMR2output/2 SPISlavemode,,clock=SCKpin,p,SSppincontrolenabled BIT SPISlavemode,clock=SCKpin,SSpincontroldisabled, SScanbeusedasFUNCTIONI/Opin WCOL1 I2CSlaveWritemode,Collision7-bitaddressDetected I2CSlavemode,10-bitaddress I2CMastermode,clock=FOSC/(4*(SSPADD+1)) Reserved I2CfirmwarecontrolledModeSelectMasterBitmode(Slaveidle) I2CSlavemode,7-bitaddresswithStartandStopbit interruptsenabled I2CSlavemode,10-bitaddresswithStartandStopbit

96 3 of 3: MSSP Control Register 2 (SSPCON2)
GCEN ACKSTAT ACKDT ACKEN RCEN PEN RSEN SEN CONTROL BITS DETECTION BITS (FLAGS) BIT FUNCTION GCEN Generatesaninterruptpwhenacallisreceived(slave(mode)) ACKSTAT 0=Acknowledgereceivedfromslave(transmitmode) ACKDT 0=ACK1=NACK(receivemode) ACKEN InitiateACK/NACKcondition(TransmitsACKDTbit) RCEN Enablesreceivemode PEN InitiatesIititaSTOPconditionditi RSEN InitiatesaRESTARTcondition SEN InitiatesInitatesaaSTARTSTARTconditioncondition

97 Registro Buffer contiene el datoTx y Rx
Tx/Rx Buffer (SSPBUF) Registro Buffer contiene el datoTx y Rx SSPBUF interfaces para el registro de desplazamiento (SSPSR) pra desplazar el dato de salida Cuando se llena, el bit Buffer Full (BF) en el registro SSPSTAT es seteado Cualquier escritura al SSPBUF durante la Tx/Rx del dato es ignorada, y el bit detector colision de escritura (WCOL) del SSPCON es seteado

98 Dirección (SSPADD) Modo Slave: Modo Master: 4×(SPADD+1) BAUD RATE =
I2C Registro de Dirección (SSPADD) Modo Slave: Contiene la dirección del PICSlave Comparado contra el valor recibido Modo Master: Usado para calcular la velocidad de clock(BAUD rate) del sistema I2C. Fosc 4×(SPADD+1) BAUD RATE = *NOTE: FOSC es la frecuencia del oscilador NO el clock de la instrucción TCY

99 El flag interruptor del MSSP (SSPIF) es
MSSP Interrupciones El flag interruptor del MSSP (SSPIF) es seteado en el PIR1 register con los siguientes eventos: Condición START Condición STOP Tx or Rx completa Petición de transmisión Condición RESTART

100 Fuentes Visite www.microchip.com para: – 24/7 Soporte técnico
– Application Notes – Web Seminars – Codigo ejemplo – Datasheets – y Mucho mas!

101


Descargar ppt "mc Programación Microcontroladores Familia de Rango Medio"

Presentaciones similares


Anuncios Google