ELE3312 - Microcontrôleurs et applications Notes de cours
Transcription
ELE3312 - Microcontrôleurs et applications Notes de cours
ELE3312 - Microcontrôleurs et applications Notes de cours Félix Chénier Première édition 9 mai 2007 2 Table des matières 1 2 Acétates 5 1.1 Cours 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.2 Cours 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1.3 Cours 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 1.4 Cours 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 1.5 Cours 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 1.6 Cours 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 1.7 Cours 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 1.8 Cours 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 Exercices 83 2.1 AVR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 2.1.1 Révision des nombres binaires . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 2.1.2 Jeu d’instructions, Entrées/Sorties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 2.1.3 Registre d’état . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 2.1.4 Branchements conditionnels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 2.1.5 Pile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 2.1.6 Mémoires . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 2.1.7 Compteurs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 2.1.8 Adressage indirect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 2.1.9 Problème d’intégration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 PIC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 2.2.1 Entrées/Sorties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 2.2.2 Compteurs et interruptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 2.2.3 Adressage indirect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 2.2.4 Convertisseur analogique/numérique . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 2.2.5 Problème d’intégration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 2.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 2.4 Communication série . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 2.4.1 SPI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 2.4.2 UART . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 2.2 3 TABLE DES MATIÈRES 4 3 Solutions aux exercices 4 Spécifications du AVR ATmega8515 de Atmel 95 117 4.1 Pinout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 4.2 Schéma-bloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 4.3 Registre d’état (SREG) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 4.4 Registres, pointeur de pile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 4.5 Mémoire vive (SRAM) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 4.6 Mémoire programmable (EEPROM) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 4.7 Vecteurs d’interruptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 4.8 Ports d’entrées/sorties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 4.9 Interruptions externes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 4.10 Compteur à 8 bits avec PWM/CTC (Timer 0) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 4.11 Compteur à 16 bits (Timer 1) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 4.12 Module de communication SPI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158 4.13 Résumé des registres d’entrées/sorties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 4.14 Résumé du jeu d’instructions AVR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 5 Spécifications du PIC16F676 de Microchip 171 5.1 Pinout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172 5.2 Schéma-bloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 5.3 Organisation de la mémoire . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175 5.4 Registre d’état (STATUS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 5.5 Compteur de programme, pile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 5.6 Adressage indirect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 5.7 Port A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 5.8 Port C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186 5.9 Timer 0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 5.10 Timer 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191 5.11 Comparateur . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195 5.12 Convertisseur analogique-numérique . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 5.13 Interruptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 5.14 Résumé du jeu d’instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 Chapitre 1 Acétates 1.1 Cours 1 2 5 CHAPITRE 1. ACÉTATES 6 4 ATmega8515 Port B Port A Port D Port C 6 1.1. COURS 1 7 x = A, B, C ou D Exemple 1 8 interrupteurs logiques (0/1) sont connectés sur le port B. On veut sortir l'état de ces interrupteurs sur le port C. 7 Utilisation des résistances pull-up Exemple 2 8 interrupteurs normaux sont connectés entre le port B et la masse. On veut sortir l'état de ces interrupteurs sur le port C : Si l'interrupteur est appuyé, le bit correspondant du port C doit être à 1 Si l'interrupteur est relâché, le bit correspondant du port C doit être à 0 8 CHAPITRE 1. ACÉTATES 8 Accès aux registres et aux périphériques clr Rd Rd = 0x00 ser Rd Rd = 0xFF ldi Rd, K Rd = K mov Rd, Rr Rd = Rr out P, Rr P = Rr in Rd, P Rd = P Exemple : Traduire l'exemple 1 sur les ports d'entrée/sortie en code assembleur 10 12 1.1. COURS 1 9 .macro [nom de la macro] instruction instruction instruction ... .endmacro 13 CHAPITRE 1. ACÉTATES 10 1.2 Cours 2 2 4 1.2. COURS 2 11 Base Décimal Hexadécimal Syntaxe AVR nombre 0xnb $nb Syntaxe PIC nombre 0xnb $nb 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 A 11 B 12 C 13 D 14 E 15 F etc. etc. 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 Binaire 0bnombre B'nombre' 0 0 0 0 0 1 0 1 1 0 1 0 1 1 1 1 0 0 0 0 0 1 0 1 1 0 1 0 1 1 1 1 etc. 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 5 7 CHAPITRE 1. ACÉTATES 12 10 1.2. COURS 2 13 11 12 CHAPITRE 1. ACÉTATES 14 On désire programmer un compteur synchronisé sur la pin 0 du port A. Le compteur doit compter jusqu'à 10 et revenir à 0 ensuite. On doit lire la valeur du compteur sur le port B. La valeur initiale du compteur doit être à 0. 13 14 1.2. COURS 2 15 16 Initialisation du pointeur de pile : ldi out ldi out r16, spl, r16, sph, low(RAMEND) r16 high(RAMEND) r16 Fonctions affectant le pointeur de pile : rcall, ret push, pop 17 CHAPITRE 1. ACÉTATES 16 19 20 1.2. COURS 2 17 Écriture d'un caractère ou d'une commande 1. Enable = 1 2. RW = 0 (Write) 3. RS = 0/1 (Commande/Caractère) 4. Data = Caractère à écrire 5. Enable = 0 (Front descendant) Lecture du busy flag 1. Enable = 0 2. RW = 1 (Read) 3. RS = 0 (Read Address Counter + Busy Flag) 4. Enable = 1 (Front montant) 5. Lire le busy flag (bit 7 de data) 21 Résumé d'une écriture et lecture du busy flag 22 CHAPITRE 1. ACÉTATES 18 1.3 Cours 3 Contenu du cours AVR Accès à la mémoire vive (SRAM) Accès à la mémoire de programme (Flash) Accès à l'EEPROM Adressage indirect PIC de Microchip Jeu d'instruction des PIC Accumulateur Banques de mémoire Manipulation du compteur de programme 2 Instructions de précompilation .eseg .db 0x0A 0x0B .org 0x0008 .db 0x1A 0x1B .cseg .org 0x0000 rjmp RESET TABLE: .db 0x2A 0x2B .dw 0x3A3B RESET: rjmp RESET 4 1.3. COURS 3 19 Accès à la SRAM sur AVR Instructions ld, st Exemple : Souris optique On désire enregistrer l'image (16x16) provenant d'un senseur optique de souris dans la SRAM du uC (à partir de l'adresse 0x60). Le senseur communique de façon sérielle, et renvoie un bit à chaque coup d'horloge (on a scanné toute l'image en 256 coups d'horloge). L'horloge est le bit 0 du port A, les valeurs en 8 bits des intensités lumineuses sont branchées sur le port B. 5 Accès à la mémoire de programme Directive de précompilateur : .db, .dw Instruction : lpm Attention : Le compteur de programme ne doit jamais se trouver dans un espace de données ! Exemple : Écrire un programme simple qui écrit séquentiellement et sans relâche la suite 0x12, 0x35, 0x8F et 0xFA sur le port B. 6 CHAPITRE 1. ACÉTATES 20 Accès à l'EEPROM sur AVR 7 Adressage de la mémoire Adressage de la mémoire de programme : - Absolu L'adresse est inscrite dans l'opcode - Relatif Une valeur relative sur l'adresse fixe est inscrite dans l'opcode - Indirect L'adresse d'un registre est inscrite dans l'opcode. C'est ce registre qui pointe vers une adresse de la mémoire de programme. Adressage de la mémoire de données : - Absolu L'adresse est inscrite dans l'opcode - Indirect L'adresse d'un registre est inscrite dans l'opcode. 8 1.3. COURS 3 21 Adressage indirect de la mémoire sur AVR Exemple : Un AVR possède quatre ports de 8 bits configurés en entrée. Une opération nécessite la lecture d'un des ports, ainsi que sa sauvegarde dans r17, selon la valeur du registre r16 : r16 = 0 : On veut lire le port A r16 = 3 : On veut lire le port B r16 = 6 : On veut lire le port C r16 = 9 : On veut lire le port D Écrire le programme nécessaire à la lecture du bon port à l'aide de l'adressage indirect. 9 PIC16F675 de Microchip : Particularités Un seul registre : le registre accumulateur Usage quasi constant de la RAM Très léger set d'instructions (35 instructions contre plus de 120 pour le AVR) 4 clocks par cycle RAM séparée en banques Accès direct au compteur de programme 11 CHAPITRE 1. ACÉTATES 22 Accumulateur W 12 Instructions du PIC : transfert de données movlw k Move Literal to W Exemple : Mettre 15 dans l'accumulateur movlw 15 movwf f Move W to file Exemple : Déplacer le contenu de l'accumulateur à l'adresse mémoire 0x20 movwf 0x20 movf f, d Move File to Destination *d = [f, w] Exemple : Déplacer le contenu de la mémoire de 0x20 à l'accumulateur movf 0x20, w Note sur la macro movfw : movfw f Move File to Accumulator Exemple : Déplacer le contenu de la mémoire de 0x20 à l'accumulateur movfw 0x20 13 1.3. COURS 3 23 RAM du PIC 14 Registre d'état du PIC (STATUS) IRP RP1 RP0 TO 7 6 5 4 PD 3 Z 2 DC 1 C Carry DC Digital carry (Équivalent au Half-carry du AVR) Z Zero RP0 Bank select C 0 15 CHAPITRE 1. ACÉTATES 24 Jeu d'instr. complet du PIC 16 Accès direct au compteur de programme PCL ; PCLATH Avantage : Permet d'implémenter un switch/case beaucoup plus efficacement 17 1.4. COURS 4 25 1.4 Cours 4 Contenu du cours PIC de Microchip Ports d'entrées/sorties Instructions de précompilateur Compteurs sur PIC : Timer0, Timer1 Adressage indirect sur PIC 2 Ports d'entrées/sorties du PIC 2 ports de 6 bits chacun PORTA PORTC Bit 3 du port A en lecture seulement Périphériques alternatifs activés par défaut, donc initialisation plus difficile Résistances pull-up disponibles seulement sur le port A Registres reliés aux ports : PORTA, PORTC TRISA, TRISC WPUA Même registre pour la lecture que pour l'écriture 4 CHAPITRE 1. ACÉTATES 26 Exemple : Initialisation des ports Initialisation du port A bcf STATUS,RP0 clrf PORTA movlw 07h movwf CMCON bsf STATUS,RP0 clrf ANSEL movlw 0Ch movwf TRISA outputs bcf STATUS,RP0 ;Bank 0 ;Init PORTA ;Set RA<2:0> to ;digital I/O ;Bank 1 ;digital I/O ;Set RA<3:2> as inputs ;and set RA<5:4,1:0> as ;Bank 0 5 Ports d'entrées/sorties du PIC Exemple : Registre à décalage On désire programmer un PIC16F676 en registre à décalage de 6 bits. Le port A d'un PIC16F676 est configuré en entrée. Le bit 0 est un bit de données série, et le bit 1 est l'horloge (front montant). Le port C du même PIC est la sortie de 6 bits, qui se décale à gauche à chaque coup d'horloge. 6 1.4. COURS 4 27 PIC : Instructions du précompilateur Inclusions : #include nom_du_fichier Définitions : #define temp 0x20 Macro : nom_de_la_macro macro param1, param2, [...] instruction 1 instruction 2 [...] endm 7 PIC : Instructions du précompilateur Ligne de configuration : __CONFIG _PWRTE_ON & _WDT_OFF & _INTRC_OSC_NOCLKOUT ___________________ _CPD _CPD_OFF _CP _CP_OFF _BODEN _BODEN_OFF _MCLRE_ON _MCLRE_OFF _PWRTE_OFF _PWRTE_ON _WDT_ON _WDT_OFF _LP_OSC _XT_OSC _HS_OSC _EC_OSC _INTRC_OSC_NOCLKOUT _INTRC_OSC_CLKOUT _EXTRC_OSC_NOCLKOUT _EXTRC_OSC_CLKOUT EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU H'3EFF' H'3FFF' H'3F7F' H'3FFF' H'3FFF' H'3FBF' H'3FFF' H'3FDF' H'3FFF' H'3FEF' H'3FFF' H'3FF7' H'3FF8' H'3FF9' H'3FFA' H'3FFB' H'3FFC' H'3FFD' H'3FFE' H'3FFF' Copy protection ___________________ Brown-out detection ___________________ Reset pin ___________________ Power on reset ___________________ Watchdog timer ___________________ Clock configuration ___________________ 8 CHAPITRE 1. ACÉTATES 28 Compteurs sur PIC Timer0 8 bits Accessible en écriture et en lecture Prescaler programmable Source interne ou externe (avec sélection de front – montant ou descendant) 10 Compteurs sur PIC : Timer0 Lecture/Écriture Registre TMR0 accessible directement 3 LSB de OPTION_REG : PS2 PS1 PS0 Prescaler PS2:PS0: Prescaler Rate Select bits Bit Value TMR0 WDT 000 1:2 1:1 001 1:4 1:2 010 1:8 1:4 011 1:16 1:8 100 1:32 1:16 101 1:64 1:32 110 1:128 1:64 111 1:256 1:128 Source et front OPTION_REG : T0CS et T0SE (T0 Clock Select, T0 Source Edge) 11 1.4. COURS 4 29 Compteurs sur PIC : Timer0 12 Timer0 : Exemple Un cristal de 1 MHz est utilisé comme horloge sur le PIC16F676. On désire obtenir cette onde carrée sur la pin 0 du port C : 1,92 ms 6,272 ms Note : Pour notre exemple, la précision sur la période totale est essentielle (aussi précis que le cristal), mais on n'a pas besoin d'une précision à tout casser sur le rapport actif/inactif. 13 CHAPITRE 1. ACÉTATES 30 Compteurs sur PIC : Timer1 16 bits, accessibles en lecture et en écriture Source externe ou interne : Source externe : Activation d'une pin (front montant seulement) Cristal indépendant de l'oscillateur interne, connecté directement 14 Compteurs sur PIC : Timer1 15 1.4. COURS 4 31 Compteurs sur PIC : Timer1 Lecture du timer1 (16 bits) Problème pour la lecture des deux octets pendant que le compteur roule : risque d'overflow entre deux lectures Solution : Arrêter le compteur si on a besoin d'une précision de 16 bits. Sinon, ne lire que TMR1H ou TMR1L. Écriture du timer1 Même problème pour l'écriture pendant que le compteur roule. Solution : Arrêter le compteur, écrire la valeur, et repartir le compteur. 16 Adressage indirect de la mémoire sur PIC Adresse : Contenu : Registre FSR Registre INDF 18 CHAPITRE 1. ACÉTATES 32 1.5 Cours 5 Contenu du cours Interruptions Concept d'interruption But de l'interruption Implémentation sur PIC Implémentation sur AVR Compteurs sur AVR Timer 0 (8 bits) Timer 1 (16 bits) 2 Qu'est-ce qu'une interruption ? Exemples d'interruptions : Requête d'un périphérique d'entrées/sorties Débordement d'un compteur Exemples d'exceptions : Débordement arithmétique Utilisation d'une instruction indéfinie Accès illégal à la mémoire Division par zéro 4 1.5. COURS 5 33 But de l'interruption Possibilité de systèmes à temps réel Le processeur peut traiter du code au lieu de faire du « polling » 5 Identification de l'interruption Circuit à drain ouvert (ou collecteur ouvert) Très simple à réaliser Lent, car le uP doit balayer tous les périphériques Circuit parallèle Il faut plusieurs lignes d'interruption sur le uP, ce qui n'arrive pratiquement jamais Daisy Chain Contrôleur d'interruptions avec vecteur d'interruptions Le contrôleur envoie directement au uP l'adresse à exécuter selon le type d'interruption 6 CHAPITRE 1. ACÉTATES 34 Interruptions sur PIC Détection de l'interruption Équivalent d'un circuit à drain ouvert On doit parcourir tous les octets mémoire contenant des flags d'interruption pour savoir de quelle interruption il s'agit Registres concernant les interruptions INTCON OPTION_REG IOCA PIR1 PIE1 8 Interruptions sur PIC 9 1.5. COURS 5 35 Interruptions sur PIC INTCON (Interrupt Control Register) : GIE Global Interrupt Enable PEIE Peripheral Interrupt Enable T0IE Timer 0 Overflow Interrupt Enable INTE External Interrupt Enable RAIE PORTA Change Interrupt Enable T0IF Timer 0 Overflow Interrupt Flag INTF External Interrupt Flag RAIF PORTA Change Interrupt Flag 10 Interruptions sur PIC OPTION_REG INTEDG Interrupt Edge Select 1 = Front montant de la pin 2 du port A 0 = Front descendant de la pin 2 du port A IOCA (Interrupt On Change A) : 6 bits correspondants aux pins du port A 11 CHAPITRE 1. ACÉTATES 36 Interruptions sur PIC PIE1 (Peripheral Interrupt Enable Register 1) : EEIE EEPROM Write Complete Interrupt Enable ADIE Analog-Digital Converter Interrupt Enable CMIE Comparator Interrupt Enable TMR1IE Timer 1 Overflow Interrupt Enable PIR1 (Peripheral Interrupt Register 1) : EEIF EEPROM Write Complete Interrupt Flag ADIF Analog-Digital Converter Interrupt Flag CMIF Comparator Interrupt Flag TMR1IF Timer 1 Overflow Interrupt Flag 12 Interruptions sur PIC Traitement de l'interruption Espace mémoire de programme : 0x04 Sauvegarde du STATUS et de l'accumulateur Traitement de l'interruption Mise à 0 du flag d'interruption Restauration de l'accumulateur et du STATUS Retour de l'interruption 13 1.5. COURS 5 37 Interruptions sur PIC Exemple 1 Un signal numérique est appliqué à la pin 2 du port A. Le port C est configuré en sortie et à 0x00 par défaut. On veut que le port C sorte 0x01 dès que la pin 2 du port A a détecté un front montant. (Sa valeur restera ensuite à 0x01 pour l'éternité) On veut que le processeur passe le plus de temps possible à réaliser des tâches utiles. 14 Interruptions sur PIC Exemple 2 Un signal numérique est appliqué à la pin 2 du port A. Le port C est configuré en sortie et à 0x00 par défaut. On veut que le port C sorte 0x01 dès que la pin 2 du port A a détecté 256 fronts montants. (Sa valeur restera ensuite à 0x01 pour l'éternité) On veut que le processeur passe le plus de temps possible à réaliser des tâches utiles. 15 CHAPITRE 1. ACÉTATES 38 Interruptions sur AVR Détection de l'interruption Contrôleur d'interruption avec vecteur d'interruptions Traitement de l'interruption Vecteur d'interruption : rjmp Sauvegarde du SREG Traitement de l'interruption Le flag propre à l'interruption est automatiquement remis à 0 lors du traitement de l'interruption. Restauration du SREG Retour de l'interruption 17 Vecteurs d'interruptions Vector No. Prog Addr Source 1 $000 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 $001 $002 $003 $004 $005 $006 $007 $008 $009 $00A $00B $00C $00D $00E $00F $010 Interrupt Definition RESET External Pin, Power-on Reset, Brown-out Reset and Watchdog Reset INT0 External Interrupt Request 0 INT1 External Interrupt Request 1 TIMER1 CAPT Timer/Counter1 Capture Event TIMER1 COMPA Timer/Counter1 Compare Match A TIMER1 COMPB Timer/Counter1 Compare Match B TIMER1 OVF Timer/Counter1 Overflow TIMER0 OVF Timer/Counter0 Overflow SPI, STC Serial Transfer Complete USART, RXC USART, Rx Complete USART, UDRE USART Data Register Empty USART, TXC USART, Tx Complete ANA_COMP Analog Comparator INT2 External Interrupt Request 2 TIMER0 COMP Timer/Counter0 Compare Match EE_RDY EEPROM Ready SPM_RDY Store Program memory 18 1.5. COURS 5 39 Contrôle des interruptions sur AVR Les signaux Enable et Flag pour les interruptions d'un périphérique se trouvent dans les registres qui contrôlent ce périphérique. Exemple : Interruption sur timer 0 Les signaux d'activation des interruptions pour le timer 0 se retrouvent sur TIMSK (Timer Interrupt Mask Register) Les flags d'interruptions pour le timer 0 se retrouvent sur TIFR (Timer Interrupt Flag Register) 19 Exemple d'interruption sur AVR Programmer un AVR pour qu'il implémente les mêmes fonctions que le premier exemple du PIC : Un signal numérique est appliqué à la pin 0 du port B (Pin T0). Le port C est configuré en sortie et à 0x00 par défaut. On veut que le port C sorte 0x01 dès que la pin 0 du port B a détecté un front montant. (Sa valeur restera ensuite à 0x01 pour l'éternité). De plus, on veut être capable d'appeler l'interruption d'une manière logicielle. On veut que le processeur passe le plus de temps possible à réaliser des tâches utiles. 20 CHAPITRE 1. ACÉTATES 40 Pinout du ATmega8515 21 Sources d'erreurs avec les interruptions Accès à des registres 16 bits Exemple : TCNT1H, TCNT1L Solution : Désactiver les interruptions lors de ces accès Mauvaise procédure de sauvegarde de l'état du microprocesseur PIC : Oublier de spécifier la banque au début de l'interruption PIC : Oublier de remettre le flag à 0 en fin d'interruption AVR : Code dans les vecteurs d'interruptions Solution : Remplir les vecteurs d'interruptions de rjmp avant de coder 22 1.5. COURS 5 41 Compteurs sur AVR : Timer0 8 bits en lecture et écriture Prescaler Comparateur intégré Modulation PWM Reset sur comparaison : CTC – Clear Timer on Compare. Source interne ou externe Externe : choix du front montant ou descendant 24 Timer0 : Registres TCNT0 : Contenu du compteur OCR0 : Contenu du comparateur (valeur à comparer avec TCNT0) TCCR0 : Configuration (FOC0 WGM00 COM01 COM00 WGM01 CS02 CS01 CS00) val.init.=0x00 COM01, COM00 : Activation du comparateur En mode normal : COM01 COM00 Description 0 0 Normal port operation, OC0 disconnected. 0 1 Toggle OC0 on Compare Match. 1 0 Clear OC0 on Compare Match. 1 1 Set OC0 on Compare Match. CS02, CS01, CS00 : Clock Select CS02 0 0 0 0 1 1 1 1 CS01 0 0 1 1 0 0 1 1 CS00 0 1 0 1 0 1 0 1 Description No clock source (Timer/counter stopped). clk (No prescaling) clk/8 (From prescaler) clk/64 (From prescaler) clk/256 (From prescaler) clk/1024 (From prescaler) External clock source on T0 pin. Clock on falling edge. External clock source on T0 pin. Clock on rising edge. WGM01, WGM00 : Waveform Generation Mode 25 CHAPITRE 1. ACÉTATES 42 Pinout du ATmega8515 26 Modes d'opération WGM1..0 du registre TCCR0 (Timer/Counter Control Register 0) WGM = 00 : Mode normal - Le compteur monte continuellement. - Lorsqu'il dépasse 0xFF, il revient à 0. - C'est tout. 27 1.5. COURS 5 43 Modes d'opération WGM1..0 du registre TCCR0 (Timer/Counter Control Register 0) WGM = 10 : Mode CTC (Clear Timer on Compare match) n=0 OCRn 28 Modes d'opération WGM1..0 du registre TCCR0 (Timer/Counter Control Register 0) WGM = 11 : Mode Fast PWM n=0 OCRn 29 CHAPITRE 1. ACÉTATES 44 Modes d'opération WGM1..0 du registre TCCR0 (Timer/Counter Control Register 0) WGM = 01 : Phase Correct PWM n=0 OCRn 30 Compteurs sur AVR Timer0 : Exemple Un cristal de 2 MHz est utilisé comme horloge sur le ATmega8515. On désire obtenir cette onde carrée sur la pin 0 du port B : 1,92ms 6,272ms Note : Contrairement à l'exemple sur le PIC, on veut une très grande précision sur la période ET sur le rapport actif/inactif. 31 1.5. COURS 5 45 Compteurs sur AVR : Timer1 16 bits en lecture et écriture Prescaler 2 comparateurs intégrés Sortie des comparateur : Modulation PWM Reset sur comparaison : CTC – Clear Timer on Compare. Application : Modulation FM Source interne ou externe Externe : choix du front montant ou descendant 32 Timer1 : Registres TCCR1A : Timer 1 Control Register A COM1A1, COM1A0 : Compare Output Mode for Channel A COM1B1, COM1B0 : Compare Output Mode for Channel B WGM11, WGM10 : Waveform Generation Mode (LSB) TCCR1B : Timer 1 Control Register B WGM13, WGM12 : Waveform Generation Mode (MSB) CS12, CS11, CS10 : Clock Select TCNT1H, TCNT1L : Contenu du compteur OCR1AH, OCR1AL : Comparateur A, valeur à comparer OCR1BH, OCR1BL : Comparateur B, valeur à comparer 33 CHAPITRE 1. ACÉTATES 46 Timer1 : Lecture et écriture Pas de problème de lecture/écriture sur 16 bits grâce au registre temporaire TEMP Lecture On lit premièrement le LSB. Le MCU copie alors en même temps le MSB dans TEMP. On lit ensuite (si on veut) le MSB. À ce moment, on lit alors TEMP. 34 Timer1 : Lecture et écriture Écriture On écrit premièrement le MSB. À ce moment, on écrit alors dans TEMP. On écrit ensuite le LSB. Le MCU copie alors en même temps TEMP dans MSB. 35 1.6. COURS 6 47 1.6 Cours 6 Contenu du cours Architecture des microprocesseur : Harvard / Von Neumann CISC / RISC Architecture du µP MIPS Jeu d'instructions Représentation d'une instruction Datapath et contrôle Exemple de fonctionnement d'un microprocesseur 2 Architecture Von Neumann uP Mémoire de données + Mémoire de programme + Périphériques Addr Data Ctrl 4 CHAPITRE 1. ACÉTATES 48 Architecture Harvard uP Mémoire Programme Mémoire Données + Périphériques Addr (prog) Data (prog) Addr (data) Data (data) Ctrl 5 Architecture PIC Von Neumann ou Harvard ? 6 1.6. COURS 6 49 Architectures CISC / RISC Historique 1970 : Mémoire très dispendieuse et très lente, et on craint une crise du software. On transfert alors la complexité dans le hardware. Résultat : Moins d'instructions par programme, le programmeur ne passe pas son temps à réinventer la roue. Exemple : Mode d'adressage mémoire à mémoire. Problème : Optimisation impossible, car chaque fonction est « hard-codée ». De plus, nombreux bogues hardware impossibles à corriger. 8 Architectures CISC / RISC Historique 1980 : Pas de crise du software Le prix de la mémoire diminue Coût du processeur actuel exponentiel On s'aperçoit que 80% des instructions d'un programme typique n'utilisent que 20% du jeu d'instructions (rapport 80/20) Apparition d'un nouveau type de microprocesseur : RISC Architecture plus petite = Plus rapide Simplicité = Régularité Instructions les plus courantes = Le plus rapide possible 9 CHAPITRE 1. ACÉTATES 50 Architectures CISC / RISC Résumé CISC (Complex Instructions Set Computers) Le moins grand nombre d'instructions par programme Beaucoup de types d'instructions Instructions de haut niveau Instructions développées au niveau du hardware RISC (Reduced Instructions Set Computers) Plus d'instructions par programme Moins de types d'instructions Instruction très simples, de bas niveau 10 Architecture MIPS Architecture RISC très populaire (le tiers des processeurs RISC est à base MIPS) Utilisé dans : Périphériques roulant Windows CE Routeurs Cisco Jeux vidéos : Sony PlayStation 1, 2 et PSP, Nintendo 64, etc. Performant et simple à la fois 32 et 64 bits 12 1.6. COURS 6 51 Convention sur les registres MIPS (seulement les registres utiles pour la compréhension) Nom Adresse Usage --------------------------------------------$zero 0 Valeur constante à 0 $t0-$t7 8 à 15 Variables temporaires $s0-$s7 16 à 23 Variables sauvegardées $t8-$t9 24 et 25 Variables temporaires $sp 29 Stack pointer 13 Jeu d'instruction du processeur MIPS (instructions principales) Arithmétique Addition add A, B, C A=B+C Soustraction sub A, B, C A=B–C Addition imédiate addi A, B, 100 A = B + 100 Transfert de données Load word lw A, 100(B) A = Mémoire[B + 100] Store word sw A, 100(B) Mémoire[B + 100] = A Load upper immediate lui A, 100 Branchements conditionnels A = 100 x 216 Branch if equal beq A, B, 25 Si A = B, aller à PC + 4 + 100 Branchements non conditionnels Jump j 2500 Aller à 10000 14 CHAPITRE 1. ACÉTATES 52 Représentation d'une instruction Champs Format 6 bits 5 bits 5 bits 5 bits 5 bits 6 bits Commentaire R op rs rt rd shamt funct Arithmétique I op rs rt address/immediate Transferts, branch J op target address jump op rs rt rd shamt funct opcode Premier registre Deuxième registre Registre de destination Shift amount Fonction 15 Carte des Opcodes du processeur MIPS 1.6. COURS 6 53 Datapath - Incrémentation du compteur de programme - Lecture des instructions 18 Datapath Instructions de format R : Opér. arithm./logiques Addition Soustraction add A, B, C sub A, B, C A=B+C A=B–C Champs Format 6 bits 5 bits 5 bits 5 bits 5 bits 6 bits Commentaire R op B C A shamt funct Arithmétique I op rs rt address/immediate Transferts, branch J op target address jump 19 CHAPITRE 1. ACÉTATES 54 Datapath Instructions de format I : Écriture/lecture mémoire Store word Load word sw A, 100(B) lw A, 100(B) Mémoire[B + 100] = A A = Mémoire[B + 100] Champs Format 6 bits 5 bits 5 bits 5 bits 5 bits 6 bits Commentaire R op rs rt rd shamt funct Arithmétique I op B A address/immediate Transferts, branch J op target address jump 20 Datapath Instructions de format I : Branchements Branch if equal beq A, B, 25 Si A = B, aller à PC + 4 + 100 Champs Format 6 bits 5 bits 5 bits 5 bits 5 bits 6 bits Commentaire R op rs rt rd shamt funct Arithmétique I op rs rt address/immediate Transferts, branch J op target address jump 21 1.6. COURS 6 55 Datapath Instr. de format J : Branchements non conditionnels Jump j 2500 Aller à PC = 10000 Champs Format 6 bits 5 bits 5 bits 5 bits 5 bits 6 bits Commentaire R op rs rt rd shamt funct Arithmétique I op rs rt address/immediate Transferts, branch J op target address jump 22 CHAPITRE 1. ACÉTATES 56 Contrôle Opcode RegDst ALUSrc MemtoReg ROM RegWrite MemRead MemWrite Branch ALUOp[1:0] 24 1.6. COURS 6 57 Carte des Opcodes du processeur MIPS Registres et champs d'instruction MIPS Nom Adresse Usage --------------------------------------------$zero 0 Valeur constante à 0 $t0-$t7 8 à 15 Variables temporaires $s0-$s7 16 à 23 Variables sauvegardées $t8-$t9 24 et 25 Variables temporaires $sp 29 Stack pointer Champs Format 6 bits 5 bits 5 bits 5 bits 5 bits 6 bits Commentaire R op rs rt rd shamt funct Arithmétique I op rs rt address/immediate Transferts, branch J op target address jump op rs rt rd shamt funct opcode Premier registre Deuxième registre Registre de destination Shift amount Fonction 28 CHAPITRE 1. ACÉTATES 58 Exemple de fonctionnement d'un uP Soit le code assembleur MIPS suivant : addi $s0, $zero, 134 ; Mettre 134 dans $s0. lw ; Charger le contenu de l'adresse add $s1, 42($s0) $s2, $s0, $s1 ; mémoire 42 + contenu de $s0 ; dans $s1. ; Additionner les registre $s0 et $s1 ; beq $s0, $s2, -22 ; Si $s0 et $s2 sont égaux, ; j 2400 et mettre le résultat dans $s2. aller à PC – 88. ; Sinon, aller à PC = 9600. 29 1.6. COURS 6 59 60 CHAPITRE 1. ACÉTATES 1.7. COURS 7 61 1.7 Cours 7 Contenu du cours Équation de performance Microprocesseur multicycles 1 cycle vs Multicycles Nouvelle architecture Microinstructions Introduction aux pipelines 2 Équation de performance Une seule mesure à améliorer Pas la fréquence d'horloge Pas la taille du code Pas le nombre de coups d'horloges par instruction Le temps passé à exécuter le programme Plusieurs facteurs Fréquence d'horloge Taille du code Nombre de coups d'horloge par instruction 4 CHAPITRE 1. ACÉTATES 62 Équation de performance Temps Instructions Horloges Période d'horloge Programme Instruction Temps Nb instructionsCPI f Clock 5 Équation de performance Autre unité de mesure de performance : un MIPS (Million d'instructions par seconde) Avantage : - Augmente en fonction de la performance, donc plus intuitif. Inconvénients : - Ne spécifie pas de quel type d'instruction il s'agit. Conséquences : - On ne peut pas comparer deux architectures différentes - Si le CPI est variable, un même processeur n'aura pas le même nombre de MIPS pour deux programmes différents 6 1.7. COURS 7 63 Exemple Architecture du microprocesseur Classe d'instruction CPI A 1 B 2 C 3 fhorloge = 500 MHz Programmes à tester Nb d'instr. dans la classe Programme A B C 1 5 1 1 2 10 1 1 Calculer : a) Temps d'exécution pour les programmes 1 et 2 b) MIPS pour les programmes 1 et 2 7 1 cycle vs Multicycles 1 cycle par instruction Avantage : Plus simple à réaliser Inconvénients : La fréquence d'horloge maximale est déterminée par le plus long datapath possible, qui est une lecture de la mémoire Plusieurs cycles par instruction Avantages : Plus compact : une seule ALU, une seule mémoire Profite du fait que les instructions n'utilisent pas tous les blocs fonctionnels En séparant chaque instruction en microinstructions, on peut réduire le temps passé à exécuter chaque instruction. 9 CHAPITRE 1. ACÉTATES 64 Microinstructions Opérations Lecture Écriture Branchements Sauts ALU Mémoire Mémoire Étape 1 Instruction Fetch IF IF IF IF IF 2 Instruction Decode/ Register Fetch ID ID ID ID ID 3 Exécution EX EX EX EX EX 4 Accès mémoire MEM MEM 5 Sauvegarde (Write Back) WB WB 10 Illustration 1 cycle vs Multicycles Processeur à un cycle add $4, $5, $6 lw $4, 60($80) j 2000 Processeur multicycles add $4, $5, $6 IF ID EX WB lw $4, 60($80) IF ID EX MEM WB j 2000 IF ID EX 11 1.7. COURS 7 65 1 cycle vs Multicycles : Exemple 1. Calculer le temps minimal requis pour exécuter ce programme : 24 calculs avec ALU 12 lectures de mémoire 16 écritures de mémoire 4 sauts (jump) 6 branchements conditionnels (beq) a) avec une configuration à plusieurs cycles par instruction. b) avec une configuration à un cycle par instruction. Temps minimaux d'accès aux blocs fonctionnels : Mémoires (écriture/lecture, instr/données) : ALU et additionneurs : Registres (écriture et lecture) : 2 ns 2 ns 1 ns 12 Schéma-bloc du MIPS multicycles 13 CHAPITRE 1. ACÉTATES 66 Microinstructions Décomposition d'une instruction en microinstructions 1. Instruction Fetch IR = Memory[PC] IF PC = PC + 4 2. Instruction Decode et Register Fetch A = Reg[IR[25-21]] ID B = Reg[IR[20-16]] ALUOut = PC + (sign-extend(IR[15-0]) << 2) (branch potentiel) 3. Exécution : Opération ALU ou Référence mémoire ou Branch ou Jump Opération ALU : ALUOut = A op B EX Référence mémoire : ALUOut = A + sign-extend(IR[15-0]) Branch : if (A==B) PC = ALUOut Jump : PC = PC[31-28] || (IR[25-0]<<2) 4. Accès mémoire MDR = Memory[ALUOut] ou Memory[ALUOut] = B MEM 5. Sauvegarde (Write back) Lecture mémoire : Reg[IR[20-16]] = MDR WB Opération ALU : Reg[IR[15-11]] = ALUOut 14 Réalisation d'un tel contrôle Une simple table de vérité ne suffit plus. Solution : Machine à états finis de Moore État courant État Opcode Combinatoire futur d'entrée Registre d'état Signaux de contrôle Combinatoire de sortie Horloge 15 1.7. COURS 7 67 Résumé des processeurs multicycles Une instruction peut prendre différents nombres de coups d'horloge Ceci permet d'optimiser les instructions les plus utilisées (calculs) par rapports aux instructions plus exigentes (lectures de mémoire) Sur l'architecture 80x86, une instruction peut prendre un cycle pour s'exécuter, et une autres quelques centaines de cycles... Un processeur multicycles permet de réutiliser les composantes d'un cycle à l'autre. 16 Pipelines But d'une pipeline Exécuter plusieurs microinstructions en même temps afin d'accélérer le flux de données 18 CHAPITRE 1. ACÉTATES 68 Datapath : Processeur avec pipeline 19 Pipeline : Exemple Tracer le pipeline pour les instructions suivantes : lw $s1, 20($t1) sub $t0, $s2, $s3 and $t2, $s4, $s5 or $t3, $s6, $s7 Opérations Lecture ALU Mémoire Étape Écriture BrancheMémoire ments Sauts 1 Instruction Fetch IF IF IF IF IF 2 Instruction Decode/ Register Fetch ID ID ID ID ID 3 Exécution EX EX EX EX EX 4 Accès mémoire MEM MEM 5 Sauvegarde (Write Back) WB WB 20 1.7. COURS 7 69 Problèmes dans le pipeline Problème d'interdépendance procédurale Une opération de branchement doit attendre le résultat de la soustraction avant de savoir quelle doit être la prochaine instruction. Problème d'interdépendance des données Un traitement de données (calcul ou accès à la mémoire) nécessite l'accès à des registres dont la valeur n'est pas encore connue. 21 Problème d'interdépendance procédurale add $s4, $s5, $s6 add $t0, $t1, $t2 beq $s1, $s2, 40 IF ID IF EX ID IF add $t7, $t8, $t9 WB EX ID WB EX IF ID EX WB Temps Ordre d'exécution Bubbles 23 CHAPITRE 1. ACÉTATES 70 Problème d'interdépendance procédurale Problème add $s4, $s5, $s6 IF ID add $t0, $t1, $t2 EX IF WB ID beq $s1, $s2, 40 EX IF WB ID EX add $t7, $t8, $t9 IF ID EX WB Au niveau logiciel (exécuté par le compilateur) Solution 1 : Ajouter des « no-operation » (nop) add $s4, $s5, $s6 IF ID add $t0, $t1, $t2 EX IF WB ID beq $s1, $s2, 40 EX IF WB ID nop EX IF ID nop IF ID add $t7, $t8, $t9 IF ID EX WB Temps Ordre d'exécution 24 Problème d'interdépendance procédurale Problème add $s4, $s5, $s6 IF add $t0, $t1, $t2 ID EX IF beq $s1, $s2, 40 ID WB EX IF ID WB EX add $t7, $t8, $t9 IF ID EX WB Au niveau logiciel (exécuté par le compilateur) Solution 2 : Déplacer les opérations indépendantes de la condition beq $s1, $s2, 40 add $s4, $s5, $s6 add $t0, $t1, $t2 add $t7, $t8, $t9 Ordre d'exécution IF ID IF EX ID IF EX ID IF WB EX ID WB EX WB Temps 25 1.7. COURS 7 71 Problème d'interdépendance procédurale Processeur MIPS - Tenter la solution 2 - Si c'est impossible, utiliser la solution 1. Après compilation, environ 50% des instructions placées après un branchement sont des nop. 26 Problème d'interdépendance procédurale Au niveau du hardware Solution 3 : Prédiction de branchement Bonne prédiction : Rendement optimal beq $s1, $s2, 40 IF add $t7, $t8, $t9 ID IF lw $t1, 100($t2) EX ID IF add $t3, $t4, $t5 EX ID IF WB EX ID MEM WB EX WB Temps Ordre d'exécution Mauvaise prédiction : On doit vider le pipeline, et on a donc des bubbles beq $s1, $s2, 40 add $t7, $t8, $t9 lw $t1, 100($t2) sub $t1, $t2, $t3 Ordre d'exécution IF ID IF EX ID IF EX ID IF WB EX ID MEM WB EX nop WB Temps 27 CHAPITRE 1. ACÉTATES 72 Problème d'interdépendance procédurale Prédictions de branchements Assumer que le branchement n'est pas pris Assumer que le branchement est pris Avantage : Possibilité de 100% d'efficacité Inconvénient : Pas très réaliste Avantage : Plus réaliste ID Inconvénient : On ne connaît l'adresse qu'après l'étape ID Prédiction dynamique de branchement Demande plus de circuiterie (buffer de prédiction) Les prédictions s'avèrent exactes jusqu'à 90% du temps 28 Problème d'interdépendance procédurale Au niveau du hardware Solution 4 : Avancer l'opération de décision Si on peut savoir dès l'étape ID s'il y aura un branchement ou non, on diminue le nombre d'instructions à vider en cas d'erreur. Inconvénient : Demande plus de circuiterie (une ALU de plus pour faire la comparaison entre les deux registres) Mauvaise prédiction : On doit vider le pipeline, et on a des bubbles beq $s1, $s2, 40 add $t7, $t8, $t9 sub $t1, $t2, $t3 Ordre d'exécution IF ID IF EX ID IF EX ID nop WB EX WB Temps 29 1.7. COURS 7 73 Problème d'interdépendance des données Exemple : sub $s2,$s1,$s3 ID s1 s3 IF WB s2 EX and $t2,$s2,$s5 ID s2 s5 IF add $s2,$s1,$s2 WB t2 EX ID s1 s2 IF WB s2 EX sw $t5,100($s2) ID s2 IF EX MEM WB t5 31 Problème d'interdépendance des données Au niveau logiciel (exécuté par le compilateur) Solution 1 : Remplir les bubbles avec des « No-Operation » sub $s2,$s1,$s3 nop nop and $t2,$s2,$s5 add $s2,$s1,$s2 nop nop sw $t5,100($s2) IF ID s1 s3 IF WB s2 EX ID IF ID IF ID s2 s5 IF WB t2 EX ID s1 s2 IF WB s2 EX ID IF ID IF ID s2 EX MEM WB t5 32 CHAPITRE 1. ACÉTATES 74 Problème d'interdépendance des données Au niveau logiciel (exécuté par le compilateur) Solution 2 : Réordonner les instructions pour remplir les bubbles avec des fonctions utiles sub $s2,$s1,$s3 add $t1,$t2,$t3 IF ID s1 s3 IF add $t4,$t5,$t6 WB s2 EX ID t2 t3 IF and $t2,$s2,$s5 WB t1 EX ID t5 t6 ID s2 s5 IF add $s2,$s1,$s2 WB t4 EX ID s1 s2 IF add $t4,$t3,$t3 WB t2 EX ID t3 IF add $t1,$t5,$t6 WB s2 EX ID t5 t6 IF sw $t5,100($s2) WB t4 EX WB t1 EX ID s2 IF EX MEM WB t5 33 Problème d'interdépendance des données Au niveau du hardware Solution 3 : Utiliser de la circuiterie pour permettre à des données d'être accessibles dès qu'elles sont prêtes Cette solution se nomme le forwarding sub $s2,$s1,$s3 and $t2,$s2,$s5 add $s2,$s1,$s2 sw $t5,100($s2) IF ID s1 s3 IF WB s2 EX ID s2 s5 IF WB t2 EX ID s1 s2 IF WB s2 EX ID s2 EX MEM WB t5 34 1.7. COURS 7 75 Problèmes dans les pipelines : Exemple Exemple add add lw sw $s1, $s2, $s3, $t5, $t1, $t2 $t3, $s1 26($t1) 26($t1) 1. Dessiner le pipeline 2. Identifier les bubbles 3. Réordonner les instructions pour les corriger 4. Pour un processeur sans forwarding, peut-on éliminer les bubbles ? 5. Pour un processeur avec forwarding, peut-on éliminer les bubbles ? 35 CHAPITRE 1. ACÉTATES 76 1.8 Cours 8 Plan de cours Communication série SPI USART / RS232 Multiplication sur AVR Convertisseur ADC sur PIC Exercices 2 SPI – Serial Peripheral Interface CS/SS : (actif bas) Chip Select/ Slave Select SCKL/SCK : Serial Clock SDI/MOSI : Serial Data IN/ Master Out, Slave in CS = 0 : Esclave actif, SDO = Data CS = 1 : Esclave inactif, SDO = Z SDO/MISO : Serial Data OUT/ Master in, Slave Out Source des images pour le SPI : http://www.mct.net/faq/spi.html 4 1.8. COURS 8 77 SPI – Serial Peripheral Interface Configuration 1 : Plusieurs esclaves en parallèle Source des images pour le SPI : http://www.mct.net/faq/spi.html 5 SPI – Serial Peripheral Interface Configuration 2 : Daisy chain Source des images pour le SPI : http://www.mct.net/faq/spi.html 6 CHAPITRE 1. ACÉTATES 78 USART Quelques définitions USART : Universal Synchronous and Asynchronous serial Receiver and Transmitter RS232 : Protocole utilisé pour les ports série d'un ordinateur : pinout, niveaux de tensions. Le RS232 utilise l'UART (Universal Asynchronous serial Receiver and Transmitter). 7 USART Synchrone ou non : pin XCK sur AVR Si synchrone, choix de Master ou Slave Format de communication : 1 bit de départ 5, 6, 7, 8 ou 9 bits de données bit de parité paire ou impaire, ou pas de bit de parité 1 ou 2 bits d'arrêt 8 1.8. COURS 8 79 RS232 Protocole du port série de l'ordinateur Trois fils « utiles » : Ground TX RX Niveaux logiques : 0 : +3 à +15V 1 : -3 à -15V Interfaçage : MAX232 9 Images provenant du site http://www.lammertbies.nl/comm/cable/RS-232.html Multiplication sur AVR Multiplication entière mul Rd, Rr (Multiply Unsigned) Rd et Rr doivent être des entiers non signés Le résultat non signé se retrouve dans r1:r0 d et r = [0,31] muls Rd, Rr (Multiply Signed) Rd et Rr doivent être des entiers signés Le résultat signé se retrouve dans r1:r0 d et r = [16,31] mulsu Rd, Rr (Multiply Signed with Unsigned) Rd doit être un entier signé Rr doit être un entier non signé d et r = [16,23] Le résultat signé se retrouve dans r1:r0 11 CHAPITRE 1. ACÉTATES 80 Multiplication sur AVR Multiplication fractionnaire fmul Rd, Rr (Fractional Multiply Unsigned) fmuls Rd, Rr (Fractional Multiply Signed) fmulsu Rd, Rr (Fract. Mult. Signed with Unsigned) Représentation d'un nombre fractionnaire non signé dans l'intervalle [0,2[ : R7, R6 R5 R4 R3 R2 R1 R0 Représentation d'un nombre fractionnaire signé dans l'intervalle [-1,1[ : Même procédé qu'en complément à deux : On exprime la valeur positive selon R7, R6 R5 R4 R3 R2 R1 R0 On inverse les bits On ajoute 1 au LSB Le résultat se retrouve dans r1:r0 sous la même forme : r1 r0 R15, R14 R13 R12 R11 R10 R9 R8 R7 R6 R5 R4 R3 R2 R1 R0 12 Convertisseur analogique/numérique Fonctionnement général 13 1.8. COURS 8 81 Convertisseur analogique/numérique Schéma-bloc sur PIC 15 Convertisseur analogique/numérique Alignement des données 16 82 CHAPITRE 1. ACÉTATES Chapitre 2 Exercices 2.1 AVR b) mov r4, r17 c) ldi r2, 50 2.1.1 Révision des nombres binaires d) add r15, r15 Q1 e) addi r15, 45 Exprimer ces nombres en notation binaire à 8 bits, et en hexa- f) out PORTD, 15 décimal. g) out DDRA, r16 a) 2 c) 254 b) 25 d) 37 e) 128 h) in PINA, r16 i) lsr r28 Q2 Q5 Si c’est possible, exprimer ces nombre en notation binaire à 8 bits en complément à deux. Si c’est impossible, expliquer Quelle est la différence entre les instructions de précompilation .def et .equ ? pourquoi. a) 40 c) -140 e) -128 b) -100 d) 130 f) 255 Q6 Soit le programme suivant : Q3 .def temp=r16 .macro macro1 ldi temp, @1 out @0, temp .endmacro .macro macro2 in r17, @0 .endmacro Effectuer ces opérations sur des nombres binaires à 8 bits. a) 100100102 + 001100112 b) 100100102 − 001100112 c) 001100112 − 111000112 d) 100100102 ÷ 210 e) 10010010 × 410 macro1 macro1 macro1 nop macro2 2.1.2 Jeu d’instructions, Entrées/Sorties Q4 DDRB, 255 PORTB, 255 DDRB, 0 PINB Décrire ce que ces instructions sont censées faire. Certaines a) En combien de cycles d’horloge sera-t-il exécuté ? instructions comportent une erreur : corriger ces erreurs. a) ldi r16, 5 b) Quelle serait l’utilité de ces deux macros ? 83 CHAPITRE 2. EXERCICES 84 Q7 2.1.4 Branchements conditionnels On veut créer une macro qui prend une lecture d’un port, inverse tous les bits et sort le résultat sur un autre port. Cette macro doit avoir la forme suivante : Q12 inverse Pout Pin Écrire un programme qui compare deux octets (8 bits) : r16 et r17. Si r16 est plus petit que r17, le compteur de programme doit aller au label R16_PLUS_PETIT où Pout est le port de sortie, et Pin est le port d’entrée. sinon, à a) Écrire cette macro R17_PLUS_PETIT_OU_EGAL. b) Donner un exemple d’appel de cette macro. Q13 2.1.3 Registre d’état Écrire un programme qui compare deux mots (16 bits) : X et Y. Si X est plus petit que Y, le compteur de programme doit aller au label Q8 Déterminer les bits C, N, Z, V et S du registre d’état (SREG) après l’exécution des calculs suivants1 : X_PLUS_PETIT sinon, à a) 0 + 0 c) 127 << 1 e) −128 − 1 b) 85 − 127 d) 1 >> 1 f) 200 − 127 Y_PLUS_PETIT_OU_EGAL. Q14 Q9 Quelle est la différence entre les bits S et N du registre d’état ? On désire créer un compteur à 8 bits syncrone possédant la configuration suivante : PORTC(7..0) Compte Q10 a) Décrire comment on peut additionner deux nombres de 16 bits (composés de chacun deux octets). b) Écrire le code pour additionner les mots de 16 bits X et Y. Q11 PORTA(0) Horloge a) Dessiner le schéma-bloc (schéma électrique) du compteur b) Tracer l’ordinogramme conceptuel du compteur c) Écrire le code Q15 Indiquer le contenu de r17 et les valeurs des bits Z, C et N du On désire ajouter deux options au compteur précédent. registre SREG à chaque étape de ce programme. On assume Voici la nouvelle configuration : que le microcontrôleur vient d’être mis sous tension. ldi rol rol lsl clr r17, 0b11110000 r17 r17 r17 r17 1 Les symboles << et >> signifient respectivement un décalage des bits vers la gauche ou la droite, du nombre de bits suivant le symbole. Par exemple, 127 << 1 signifie un décalage des bits du nombre 127 d’un bit vers la gauche (multiplication par 2). PORTA(1) Direction 0 = Descendant 1 = Ascendant PORTA(2) Reset_N 0 = Mise à zéro du compteur 1 = Fonctionnement normal a) Modifier le schéma-bloc du compteur b) Modifier l’ordinogramme conceptuel c) Modifier le code 2.1. AVR 85 Q16 Q19 Soit le programme suivant : On veut faire clignoter le bit 0 du port A d’un ATmega8515 à l’aide du programme suivant : ;Définition des variables .def temp=r16 rjmp RESET ;Définition des macros .macro outi ldi temp, @1 out @0, temp .endmacro ;Programme principal ;Port A en entrée, sans pull-up outi DDRA, 0x00 outi PORTA, 0x00 ;Port B en sortie, = 0xEE outi PORTB, 0xEE outi DDRB, 0xFF ;Si PA1=0, PORTB=0xAA sbis PINA, 1 outi PORTB, 0xAA ;****************************** ; Routine qui fait clignoter le ; bit 0 du port A ;****************************** CLIGNOTE: sbi PORTA, 0 nop cbi PORTA, 1 nop rcall CLIGNOTE ;****************************** ;Programme principal ;****************************** RESET: .include "include1.asm" ;Boucle principale BOUCLE: b) Si on applique 1 sur la pin 1 du port A, quelle sera la valeur rcall CLIGNOTE rjmp BOUCLE lue sur le port B après l’exécution du programme ? a) Quel est le problème avec ce programme ? 2.1.5 Pile Pour tous les exercices de la section 2.1.5, un fichier nommé include1.asm contiendra les lignes suivantes : ldi out ldi out r16, SPH, r16, SPL, high(RAMEND) r16 low(RAMEND) r16 a) Est-ce que le programme va fonctionner ? b) S’il y a une erreur, la corriger. Q20 À quoi servent les instructions push et pop ? Q21 Q17 À quoi servent les instructions du fichier include1.asm ? Quel sera le contenu de r16, r17 et r18 après l’exécution du programme suivant : Q18 Quelle valeur aura r16 après l’exécution de ces commandes ? .include ldi r16, push r16 ldi r16, push r16 ldi r16, pop r16 "include1.asm" 0x01 0x02 0x03 .include ldi r16, ldi r17, ldi r18, push r16 push r17 push r18 pop r16 pop r17 pop r18 "include1.asm" 15 34 127 CHAPITRE 2. EXERCICES 86 2.1.6 Mémoires Quel sera le contenu de r18 après la dernière instruction lpm de chacun des programme suivants ? Q22 a) On veut fabriquer un générateur de tension à l’aide d’un microcontrôleur ATmega8515 et d’un convertisseur numériqueanalogique connecté au port B. Grâce à ce convertisseur, on n’a qu’à envoyer un octet entre 0 et 255 sur le port B pour générer une tension entre 0 et 5V. rjmp MAIN .include "tableau.asm" MAIN: ldi ZL, low(TABLE*2) ldi ZL, high(TABLE*2) Le programme doit pouvoir générer quatre types de forme de lpm r18, Z tension : une onde sinusoïdale, une onde en dents de scie, une onde triangulaire et une onde carrée. Pour ce faire, on dis- b) pose de quatre tables de 256 valeurs de tension dans la mémoire flash : SINUS, SCIE, TRIANGLE et CARRE. Chaque table couvre une période du signal. Par exemple, la table SCIE rjmp MAIN .include "tableau.asm" contiendra les données suivantes : MAIN: ldi ZL, low(TABLE*2+3) SCIE: ldi ZH, high(TABLE*2+3) .db 0 1 2 3 4 5 6 7 ... lpm r18, Z+ .db ... 252 253 254 255 et la table TRIANGLE contiendra : TRIANGLE : .db 0 2 4 6 8 ... .db ... 252 254 254 252 250 ... .db ... 10 8 6 4 2 c) ldi ZL, low(0x01A0*2) ldi ZH, high(0x01A0*2) adiw ZH:ZL, 10 lpm r18, Z .org 0x01A0 .include "tableau.asm" On devra incrémenter l’index du tableau à chaque coup d’horloge : c’est ce qui déterminera la fréquence du générateur. d) L’horloge est connectée à la pin 0 du port A. Finalement, le choix de la forme d’onde sera déterminée par .org 0x0000 ldi ZL, low(TABLE<<1) les bits 2 et 1 du port A : ldi ZH, 0 lpm r18, Z+ 00 : Onde sinusoïdale lpm r18, Z+ 01 : Onde en dents de scie lpm r18, Z+ 10 : Onde triangulaire .include "tableau.asm" 11 : Onde carrée a) Dessiner le schéma-bloc du système Q24 b) Tracer l’ordinogramme conceptuel On dispose du fichier affichage.asm, qui contient les lignes suivantes : c) Écrire le code Q23 Voici le contenu du fichier “tableau.asm” : TABLE: .db 0x16, 0xFF, 0x24, 0x00 .db 0xF4, 0xAB, 0xC1, 0x44 .db 0x11, 0x12, 0x13, 0x14 BONJOUR: .db ’B’, ’o’, .db ’o’, ’u’, AUREVOIR: .db ’A’, ’u’, .db ’e’, ’v’, ’n’, ’j’ ’r’, ’ ’, ’ ’, ’ ’ ’ ’, ’r’ ’o’, ’i’, ’r’, ’ ’ et du fichier ecran_lcd.asm, qui contient les fonctions suivantes : 2.1. AVR 87 – LCD_INIT – Cette fonction initialise l’écran LCD ; – LCD_WRITE_CHAR – Cette fonction écrit le caractère contenu dans r16 sur l’écran LCD, puis incrémente le curseur de l’écran (ainsi, chaque appel de LCD_WRITE_CHAR écrit un caractère l’un après l’autre) ; F IG . 2.1 – Schéma-bloc du convertisseur numérique– LCD_CURSOR_HOME analogique (exercice 28) – Cette fonction renvoie le curseur de l’écran LCD au début. Ainsi, le prochain appel de LCD_WRITE_CHAR écrira un caractère au tout début de l’écran. vers la RAM. Le tableau comporte 54 octets et se trouve à On veut écrire un programme pour AVR qui écrira un mot sur l’adresse TABLE. On veut charger ces données séquentielleun écran LCD selon l’entrée RA0. Si RA0 est à 0, on veut ment dans la RAM à partir de l’adresse 0x0060. écrire “Bonjour”, et si RA0 est à 1, on veut écrire “Au revoir”. a) Tracer l’ordinogramme conceptuel a) Tracer un ordinogramme conceptuel permettant de réaliser cette fonction. b) Écrire le code b) Écrire le code correspondant à votre ordinogramme. 2.1.7 Compteurs Q25 Q28 On veut fabriquer un convertisseur numérique-analogique à Que contiendront les registres XL, XH, YL, YH, r18, et r19 l’aide d’un ATmega8515, dont un schéma-bloc sommaire est après l’exécution de ces instructions ? illustré à la figure 2.1. ldi XL, 0xFF clr XH mov YL, XH ldi YH, 1 ldi r16, 0x7C ldi r17, 0x7D st X+, r16 st Y, r17 ld r18, X+ ld r19, -Y La sortie analogique doit représenter une tension entre 0 et 5V, proportionnelle à l’entrée numérique comprise entre 0 et 255. Le convertisseur doit respecter ces conditions : 1. Le programme doit être extrêmement court et efficace 2. La sortie du microcontrôleur (soit l’entrée du filtre passebas) doit osciller le plus rapidement possible 3. L’entrée doit être lue continuellement, afin d’actualiser la sortie en tout temps. a) Quel périphérique sera utilisé pour générer l’entrée du filtre passe-bas ? Comment sera-t-il utilisé ? Q26 b) Déterminer le port utilisé pour l’entrée, et la pin de sortie. Quel est le rôle de ce programme ? c) Donner la valeur de tous les octets concernant le périphérique choisi en a). clr XH ldi XL, 0xA0 st X+, r16 st X+, r17 st X+, r18 subiw XH:XL, 3 ld r17, X+ ld r18, X+ ld r16, X+ d) Écrire le programme, en moins de 10 instructions. 2.1.8 Adressage indirect Q29 Soit le sous-programme AVR suivant : ser r16 clr XH ldi XL, 0x32 Q27 out 0x11, r16 st X+, r16 On désire programmer la fonction TRANSFERT_MEMOIRE, qui subiw XH:XL, 2 charge le contenu d’un tableau de la mémoire de programme ld r17, -X CHAPITRE 2. EXERCICES 88 F IG . 2.3 – Capteurs de température et de niveau d’essence (exercice 31) F IG . 2.2 – Tableau de bord (exercice 31) Est-il possible de déterminer quelle sera la valeur de r17 après l’exécution de ce programme ? Si oui, quelle sera-t-elle ? Si non, pourquoi ? Q30 Écrire le contenu des registres r15, r16, r17, r18, et XL après F IG . 2.4 – Module pour le calcul de la vitesse du véhicule l’exécution de ces instructions. On assume que le microcon- (exercice 31) trôleur vient d’être mis sous tension. .org 0x0000 ldi r16, 0b00110011 mov r15, r16 ldi r16, 0b00001111 ldi XL, 15 ld r17, X+ ld r18, X+ eor r17, r18 Capteurs de température et de niveau d’essence On dispose du module de la figure 2.3. Ce module interagit avec le capteur de température et la jauge à essence, et sort directement la valeur à afficher en fonction du signal de sélection du capteur (grâce à un multiplexeur). Révolution du moteur Pour obtenir la révolution du moteur, on dispose d’un signal numérique qui change de niveau à chaque fois que le moteur a effectué un tour complet. On calculera donc le nombre de changements de ce signal en un intervalle de temps donné de Q31 300 millisecondes. Note : selon la conception du moteur, il est Vous devez concevoir un tableau de bord à l’aide d’un AT- impossible d’obtenir plus de 10000 tours par minute. mega8515, pour une voiture sensationnelle et révolutionnaire. Ce tableau de bord, illustré à la figure 2.2, doit comprendre Vitesse du véhicule quatre informations, soient : Finalement, pour obtenir la vitesse du véhicule, on dispose – La vitesse du véhicule, exprimée en kilomètres/heure – La vitesse du moteur (révolution), exprimée en centaines du module montré à la figure 2.4. La roue est branchée à un générateur qui produit une tension proportionnelle à la vitesse de tours par minute (x100 RPM) du véhicule (entre 0 et 5V), 5V correspondant à 255 km/h. – La température du moteur, exprimée en degrés Celcius Afin de trouver à quelle vitesse le véhicule roule, on procède – Le niveau d’essence, exprimé en pourcentage par itérations : 2.1.9 Problème d’intégration Fonctionnement du tableau de bord Pour écrire une valeur sur un des quatre cadrans, on spécifie la valeur à écrire sur Data, puis on donne un front montant sur le Clk du registre à mettre à jour. Par exemple, pour écrire « 45% d’essence », on mettra 45 sur Data et on mettra Clk[0] à 1, puis à 0. 1. On génère une tension analogique correspondant à la vitesse qu’on affiche présentement. 2. On attend 300 millisecondes, le temps que le filtre passebas se stabilise. 3. On lit la sortie du comparateur. Si on lit 0, on augmente la vitesse affichée ; si on lit 1, on diminue la vitesse affichée. 2.2. PIC 89 g) Décrire les fonctions des différents registres que vous utiliserez (r16, r17, etc.) h) Écrivez le code correspondant à vos ordinogrammes conceptuels. 2.2 PIC 2.2.1 Entrées/Sorties Q32 F IG . 2.5 – Ordinogramme de haut niveau (exercice 31) On veut construire un circuit qui fait clignoter des leds dont le patron est déterminé par une combinaison de trois boutons. Parmi les quatre circuits de la figure 2.6, un seul pourrait fonctionner. Quel est-il et pourquoi les autres sont voués à l’échec ? 4. On recommence. Q33 Autres spécifications Configurer les entrées/sorties d’un PIC16F676 comme menL’affichage doit être actualisé à chaque 300ms approximati- tionné à la table 2.1. Donner les valeurs binaires de chaque vement. Le Atmega8515 est connecté à un cristal de 4,096 périphérique (registre d’entrée/sortie) nécessaire. MHz Q34 Ordinogramme de haut niveau Refaire le compteur de l’exercice 14, cette fois-ci à l’aide d’un Afin de vous aider dans votre développement, l’ordinogramme PIC (faire un compteur 6 bits plutôt que 8 bits) de haut niveau vous est donné, à la figure 2.5. a) Modifier l’ordinogramme conceptuel, s’il y a lieu On demande : b) Écrire le code a) Selon l’architecture du module de vitesse du véhicule, quelle Q35 est la meilleure manière de générer une tension analogique à l’aide du ATmega8515 ? Spécifier le périphérique utilisé, et Refaire le compteur de l’exercice 15, cette fois-ci à l’aide d’un PIC (faire un compteur 6 bits plutôt que 8 bits) en quel mode sera-t-il utilisé. b) Déterminer les valeurs de tous les registres concernant le a) Modifier l’ordinogramme conceptuel, s’il y a lieu périphérique spécifié en a) b) Écrire le code c) Pour avoir une bonne précision sur la révolution du moteur, on utilisera les interruptions. Quelle interruption sera utilisée Q36 pour le calcul du nombre de tours de moteur ? d) Déterminer les valeurs de tous les registres permettant à cette interruption de s’exécuter. Soit le programme suivant : movfw 0x20 subwf 0x21, w btfss STATUS, C f) Développer les étapes de l’ordinogramme fourni à l’aide de goto LABEL1 sous-ordinogrammes. Ne pas oublier d’inclure un (des) ordi- btfss STATUS, Z nogramme(s) pour les interruptions. Il n’est pas nécessaire de goto LABEL2 développer le délai en sous-ordinogramme. goto LABEL3 e) Dessiner le schéma électrique du circuit. Bien indiquer les noms des entrées/sorties des différents modules. CHAPITRE 2. EXERCICES 90 a) b) c) TAB . 2.1 – Configurations à réaliser à l’exercice 33 Port A Port C Complètement en sortie Complètement en entrée Complètement en entrée, avec résistances de pull-up Bits 0 à 3 en entrée, bits 4 et 5 en sortie actives sur chaque entrée Complètement en entrée, avec résistances de pull-up Complètement en sortie actives sur les entrées 0 à 2, et inactives sur les entrées 3à5 a) Si possible, donner un exemple de contenus des registres 0x20 et 0x21 pour que le compteur de programme se dirige vers LABEL1 b) Si possible, donner un exemple de contenus des registres 0x20 et 0x21 pour que le compteur de programme se dirige vers LABEL2 (a) Circuit 1 c) Si possible, donner un exemple de contenus des registres 0x20 et 0x21 pour que le compteur de programme se dirige vers LABEL3 Astuce : commenter exactement ce qui se passe à chaque ligne, ceci devrait vous aider. 2.2.2 Compteurs et interruptions Q37 (b) Circuit 2 Un microcontrôleur PIC16F676 fonctionne à une fréquence fosc de 4MHz. Déterminer les bits de tous les périphériques nécessaires pour que le compteur 0 (8 bits) s’incrémente à : a) Toutes les microsecondes b) Toutes les 32 microsecondes c) Chaque fois que la pin T0CKI a capté 8 fronts montants d) Chaque front descendant de la pin T0CKI (c) Circuit 3 Q38 Selon la figure 4-1 de la datasheet du PIC16F676, quelle est la seule façon d’arrêter le compteur 0 ? Q39 (d) Circuit 4 F IG . 2.6 – Configurations proposées pour l’exercice 32 Un microcontrôleur PIC16F676 fonctionne à une fréquence fosc de 4MHz. Déterminer les bits de tous les périphériques nécessaires pour que le compteur 1 (16 bits) s’incrémente à : a) Toutes les microsecondes b) Toutes les 8 microsecondes c) Chaque front montant de la pin OSC1 2.2. PIC 91 Q40 On veut programmer une fonction qui écrit 13 dans le compteur 1, pendant que celui-ci est activé et connecté sur la fréquence interne du microcontrôleur avec un prescaler de 1 : 2. Lorsque la fonction revient à l’endroit où elle a été appelée, le compteur doit donc être à 13. Est-ce que ce programme fonctionnera correctement ? Sinon, comment pourrait-on le corriger sans arrêter le compteur ? ECRIRE_13_DANS_TIMER1 bcf STATUS, RP0 movlw 13 movwf TMR1L movlw 0 movwf TMR1H nop return 2.2.3 Adressage indirect Q41 F IG . 2.7 – Kiosque de « Frappe la marmotte » (exercice 43) température ambiante est inférieure à la température demandée ; inversement, il doit être éteint dès que la température ambiante est supérieure à la température demandée. Finalement, on dispose d’un potentiomètre pour contrôler la Sur un PIC16F676, on dispose de 60 registres à usage général, température demandée. Ce potentiomètre est gradué de 0 à ◦ distribués de l’adresse 0x20 à 0x5B. On veut faire une fonc- 32 C. On n’a droit à aucune pièce supplémentaire. tion qui copie le contenu d’un de ces registres dans le registre a) Dessiner le schéma électrique du système. 0x5D, selon le contenu du registre 0x5E. Par exemple : b) Quelle sera la précision sur la conversion de la température – Si le contenu de 0x5E est « 0 », on veut copier le contenu courante (en degrés celcius) ? de 0x20 dans 0x5D ; – Si le contenu de 0x5E est « 1 », on veut copier le contenu c) Dessiner le(s) ordinogramme(s) conceptuel(s) permettant de réaliser ce thermostat. de 0x21 dans 0x5D ; – Si le contenu de 0x5E est « 2 », on veut copier le contenu d) Écrire le code correspondant à ce(s) ortinogramme(s). de 0x22 dans 0x5D ; – ... – Si le contenu de 0x5E est « 59 », on veut copier le contenu 2.2.5 Problème d’intégration de 0x5B dans 0x5D ; Q43 Écrire le code permettant de réaliser cette fonction. 2.2.4 Convertisseur analogique/numérique On veut programmer un kiosque de « Frappe la marmotte » comme dans les parcs d’attraction. Le principe est le suivant : Une table contient 4 terriers dans lesquels se cachent 4 marmottes en plastique (une marmotte par terrier). À un instant donné, une marmotte sort de son trou On désire fabriquer un thermostat électronique à l’aide d’un pendant un court instant : le but est de la frapper vigoureusePIC. Pour ce faire, on dispose d’un capteur de température ment et le plus rapidement possible à l’aide d’un marteau en dont la sortie est une tension analogique entre 0 et 5V, suivant caoutchouc. L’histoire se répète pendant toute la partie. Si jacette fonction : mais une marmotte reste sortie plus d’une seconde, la partie est terminée. " ! T + 30 Vout = 5 On est intéressé à faire le système de détection de coups de 128 marteau à l’aide d’un PIC. Les 4 signaux de sortie du monoù Vout est en volts et T est en degrés celcius. De plus, on tage ci-contre sont à la base en haute impédance (connectés dispose d’un élément chauffant contrôlé par un signal numé- à rien). Lorsqu’une marmotte est frappée, le signal devient 0 rique 0/5V (il suffit d’assigner 5V à son entrée pour que l’élé- (connecté à la masse) pendant un très court instant (la durée ment chauffe). L’élément chauffant doit être allumé dès que la de 20 cycles du PIC), avant de revenir à une haute impédance. Q42 CHAPITRE 2. EXERCICES 92 Comme on veut être certain de ne manquer aucun coup, le système devra fonctionner sur une base d’interruptions. 2.3 MIPS À chaque fois qu’une marmotte est frappée, une des 4 fonc- Q44 tions suivantes devra être appelée (selon le cas) : Soit le programme suivant : MARMOTTE1_FRAPPEE MARMOTTE2_FRAPPEE MARMOTTE3_FRAPPEE MARMOTTE4_FRAPPEE addi $t1, zero, 100 addi $t2, $t3, 20 sw $t4, 10($t5) j 200 Si une écriture ou une lecture d’un registre prend 1ns, une écriture ou une lecture d’une mémoire prend 2ns, et qu’un calcul arithmétique prend 2ns, calculer le temps d’exécution du programme s’il est exécuté sur : Chacune de ces fonction ne fait qu’envoyer le numéro de mar- a) Un processeur MIPS à un cycle motte frappée à un contrôleur général, par une communication b) Un processeur MIPS à cinq cycles SPI. Ces fonctions sont programmées pour vous, on n’a qu’à c) Un processeur MIPS pipeliné à 5 étages les appeler au bon moment. De plus, on doit générer une interruption lorsqu’une marmotte est sortie pour plus d’une seconde. Afin d’aider pour le calcul de cette période, on utilise une composante externe qui génère une onde carrée à 65,536 kHz chaque fois qu’une marmotte (n’importe laquelle) se trouve à l’extérieur de son trou. S’il n’y a aucune marmotte sortie, ce générateur est simplement arrêté. La sortie du générateur est obligatoirement appliquée sur la pin 11 (RA2/AN2/COUT/T0CKI/INT). La fonction à appeler lors de cette interruption est celle-ci : FIN_DE_PARTIE Du côté physique, on ne dispose que du montage montré à la figure 2.7, du générateur d’horloge à 65,536 kHz sur la pin 11, et du PIC. Aucune composante additionnelle ne peut être utilisée. On demande : a) Déterminer le type d’interruption générée lorsqu’une marmotte est frappée. b) Déterminer le type d’interruption générée lors d’une fin de partie (lorsqu’une marmotte est sortie depuis plus d’une seconde). c) Dessiner le schéma électrique (schéma-bloc) de votre circuit. Bien identifier le nom des pins. Q45 Soit la séquence d’instructions suivante, pour un processeur MIPS pipeliné à 5 étages. On suppose que les valeurs de $t1, $t2 et $t3 sont sauvegardées depuis longtemps dans les registres avant l’exécuton de ces commandes. addi $t1, $zero, 1 sw $t2, 50($t1) lw $t3, 32($t2) add $s1, $t1, $t3 a) Dessiner le pipeline correspondant à ce programme, pour un processeur sans forwarding, en identifiant les « bubbles » s’il y a lieu. b) Que devrait faire le compilateur pour éliminer les « bubbles » de façon à ce que le programme soit le plus rapide possible ? Dessiner le nouveau pipeline sans « bubbles ». 2.4 Communication série 2.4.1 SPI Q46 d) Comment doit-on configurer les ports et les périphériques a) Suivant une configuration en parallèle telle que vue dans les utilisés ? Donner les valeurs de tous les octets concernant ces acétates, est-il possible, pour un ATmega8515, de communiports et périphériques. quer indépendamment avec 256 esclaves différents ? e) Dessiner les ordinogrammes (Main et Interruption) pour ce programme. Ne pas oublier de bien initialiser tout ce qui a besoin d’être initialisé. f) Écrire le code, avec commentaires. b) Qu’en est-il si on utilise une configuration Daisy-Chain ? c) Lors du projet final, on n’utilise pas le signal CS. Comment peut faire l’esclave pour savoir si le maître s’adresse à lui ou non ? 2.4. COMMUNICATION SÉRIE d) Suivant une configuration telle que celle utilisée lors du projet final, serait-il possible de communiquer indépendamment avec 256 esclaves différents ? 93 Communication sans erreur SCK On active l’interruption sur débordement du timer On désactive l’interruption sur débordement du timer Q47 Communication avec erreur SCK Lors du projet final du cours, vous serez amenés à utiliser une communication SPI entre deux PIC16F676 et un ATmega8515. Or, la communication SPI n’est malheureusement pas impléOn active l’interruption Débordement sur débordement du timer du timer mentée sur le microcontrôleur PIC16F676. On doit donc la programmer. Pour mieux comprendre la communication SPI, F IG . 2.8 – Illustration de l’utilité du timer pour la syncronisaprocédons par étapes. tion en cas d’erreur de communication (exercice 47) a) Dessiner un ordinogramme correspondant à un registre à décalage de largeur 8. Le registre possède une entrée SDI qui s’insère dans le bit le plus significatif du registre, alors que le bit le moins significatif du registre se retrouve dans la sortie SDO. Ne pas utiliser d’interruptions. F IG . 2.9 – Transmission série (exercice 49) b) Modifier cet ordinogramme pour inclure un appel à une fonction chaque fois que 8 bits sont reçus. b) Déterminer le nombre de cycles minimum passés en interc) Les précédents ordinogrammes amènent un problème ma- ruption, seulement pour traiter la sauvegarde et la restauration jeur : le PIC ne peut rien faire pendant qu’il attend des don- de l’accumulateur et du STATUS. nées. Modifier l’ordinogramme pour que le PIC soit libre de traiter du code utile entre deux coups d’horloge (ceci implique c) S’il y a des fronts montants sur la pin d’interruption externe à une fréquence de 20kHz, déterminer de combien de cycles l’utilisation d’interruptions). disponibles vous disposez pour traiter les interruptions (autre d) L’ordinogramme tracé en c) commence à être beaucoup que la sauvegarde et la restauration de l’accumulateur et du plus intéressant. Par contre, il subsiste un problème qui est STATUS). l’alignement des données. En effet, en cas d’erreur dans la communication (il y en a toujours), il se peut que le PIC ne d) À la lumière de ces calculs, est-il une bonne idée de faire de reçoive que 7 coups d’horloge et non 8. Les prochains octets la communication bidirectionnelle pour ce projet ? Comment faire pour envoyer et recevoir des données à l’aide d’une comreçus seront alors tous décalés. munication unidirectionnelle ? Pour éviter cette situation, on utilise une interruption sur un overflow de timer qui peut survenir seulement en cours de réception (c’est-à-dire qu’on désactive cette interruption lors- 2.4.2 UART qu’un octet complet est reçu). Ainsi, comme le temps pour recevoir une donnée est relativement court, un débordement Q49 du timer signifie que le maître a terminé d’envoyer sa donnée, et que certains bits ne se sont pas rendus à l’esclave. Il faut On veut transmettre deux octets à l’aide du port série d’un ordonc resyncroniser l’esclave et ignorer les données reçues. La dinateur. La figure 2.9 montre un diagramme temporel de la tension sur la ligne TX de l’ordinateur pour cette communifigure 2.8 illustre ce concept. cation. Modifier l’ordinogramme tracé en c) pour incorporer le traitement d’un timer pour resyncroniser l’esclave en cas d’erreur. La communication totale (du premier bit ”Start” au dernier bit ”Stop”) a pris 0,764ms, et aucune erreur n’est survenue. Q48 a) Quels sont les octets transmis ? b) Combien y a-t-il de bits d’arrêt ? Sur un PIC16F676, il faut un maximum de quatre cycles entre c) Quelle est la parité utilisée (paire, impaire, pas de parité) ? le moment où une interruption est captée par le microprocesseur, et le temps où le compteur de programme se retrouve à d) Quelle est la vitesse de transmission en kilobits par seconde l’adresse 0x0004. Si le PIC fonctionne à une horloge interne (kbps) ? de 4MHz et qu’on l’a configuré pour réagir aux interruptions externes sur front montant : Q50 a) Déterminer le nombre de cycles minimum pour lire une pin quelconque du port A lors du front montant de la pin d’inter- Une communication SPI nécessite une horloge, afin que les ruption externe. deux modules qui communiquent puissent savoir quand lire 94 où écrire les données. Or, pour une communication avec un UART, il n’y a pas de signal d’horloge. Les deux modules doivent donc chacun générer cette horloge. Comment les deux modules peuvent-il faire pour synchroniser leurs horloges et être certains que celles-ci ne divergent pas avec le temps ? CHAPITRE 2. EXERCICES Chapitre 3 Solutions aux exercices R1 R4 a) 000000102, 0x02 a) Charger la constante 5 dans le registre r16 b) Copier le contenu du registre r17 dans le registre r4 b) 000110012, 0x19 c) Erreur : on ne peut pas charger directement une constante dans les registres r0 à r15. Solution : c) 111111102, 0xFE d) 001001012, 0x25 e) 100000002, 0x80 ldi r16, 50 mov r2, r16 R2 d) Additionner le contenu du registre r15 à lui-même, et mettre le résultat dans r15 e) Additionner 45 au registre r15, et mettre le résultat dans r15 a) 00101000 f) Erreur : on ne peut pas envoyer directement une constante sur un périphérique. Solution : b) 10011100 c) Impossible, car on ne peut pas exprimer un nombre plus petit que -128 en complément à deux sur 8 bits. On aurait alors 01110100 qui est interprété comme un nombre positif (116), le bit de signe étant 0. ldi r16, 15 out PORTD, r16 g) Sortir le contenu de r16 sur le périphérique DDRA (confid) Impossible, car on ne peut pas exprimer un nombre plus guration Entrée/Sortie du port A) grand que 127 en complément à deux sur 8 bits. On aurait h) Erreur : les deux arguments sont inversés. On veut lire alors 10000010 qui est interprété comme un nombre négatif PINA et mettre le contenu dans r16. Solution : (-126), le bit de signe étant 0. in r16, PINA e) 10000000 f) Impossible, car on ne peut pas exprimer un nombre plus i) Déplacer les bits de r28 vers la droite, et mettre 0 au MSb grand que 127 en complément à deux sur 8 bits. On aurait (bit le plus significatif). Attention : il ne faut pas utiliser r28 alors 11111111, qui est interprété comme un nombre négatif si on utilise le registre de 16 bits Y, car r28 fait partie de Y. (-1), le bit de signe étant 1. R5 R3 .equ définit une constante, alors que .def définit un registre. a) 11000101 R6 b) 01011111 c) 01010000 a) 8 cycles d) 01001001 b) La macro 1 sert à envoyer directement une constante dans un registre d’entrées/sorties. La macro 2 sert à lire un registre d’entrées/sorties dans le registre r17. e) 01001000 95 CHAPITRE 3. SOLUTIONS AUX EXERCICES 96 TAB . 3.1 – Réponse à l’exercice 8 C N Z V S a) 0 0 1 0 0 b) 1 1 0 0 1 c) 0 1 0 1 0 d) 1 0 1 1 1 e) 0 0 0 1 1 f) 0 0 0 1 1 R10 a) Simplement en additionnant leurs parties basses et hautes respectives. On commence par additionner les parties basses, puis on additionne les parties hautes en prenant soin de propager le carry de l’addition précédente. b) R7 add XL, YL ; Additionner les parties basses adc XH, YH ; Additionner les parties hautes ; et le carry ; Le résultat est dans X. a) R11 .def temp=r16 .macro inverse in temp, @1 com temp out @0, temp .endmacro b) Pour inverser les bits de PINA et sortir sur PORTB : inverse PORTB, PINA R8 Voir la table 3.1. Note : Le bit V de la question f) est moins évident que les autres. En fait, le résultat de 200 - 127 est 73, ce qui est exprimable en notation en complément à deux sur 8 bits. On serait donc tenté de dire que V vaut 0. Or, 200 n’est pas exprimable en complément à deux sur 8 bits. En chargeant 200 dans un registre, on se trouve plutôt à charger -56, qui est son équivalent en complément à deux. Le calcul est alors -56 - 127, ce qui donne -183. La réponse est donc effectivement plus petite que -128, ce qui la rend non exprimable en complément à deux sur 8 bits. On a donc les bits V et S qui se mettent à 1. ldi ; ; rol ; ; rol ; ; lsl ; ; clr ; ; r17, 0b11110000 r17 = 11110000 ZCN = 001 r17 r17 = 11100000 ZCN = 011 r17 r17 = 11000001 ZCN = 011 r17 r17 = 10000010 ZCN = 011 r17 r17 = 00000000 ZCN = 110 R12 cmp r16, r17 brlt R16_PLUS_PETIT rjmp R17_PLUS_PETIT_OU_EGAL R13 ;Commencer par comparer les parties hautes cmp XH, YH brlt X_PLUS_PETIT ; Si plus petit... brne Y_PLUS_PETIT_OU_EGAL ; Si pas égal... ;Ici, XH et YH sont égaux Notons que -183 et 73 sont complètement compatibles au point ;On va donc comparer les parties basses du vue binaire sur 8 bits. cmp XL, YL brlt X_PLUS_PETIT rjmp Y_PLUS_PETIT_OU_EGAL R9 R14 Le bit N est simplement le bit le plus significatif de l’octet. S’il y a eu débordement en complément à deux, le bit N sera a) Voir figure 3.1 automatiquement faux (0 pour un résultat négatif, 1 pour un résultat positif). Le bit S indique le signe de la réponse même b) Voir figure 3.2 en cas de débordement de complément à deux. c) 97 F IG . 3.1 – Réponse à l’exercice 14 a) F IG . 3.3 – Réponse à l’exercice 15 a) R15 a) Voir figure 3.3 b) On doit ajouter : 1. Une condition sur la direction du compteur ; 2. Une vérification du reset lorsqu’on attend un front montant ; 3. Une vérificaiton du reset lorsqu’on attend un front descendant. Voir figure 3.4 c) F IG . 3.2 – Réponse à l’exercice 14 b) .def temp=r16 .def compteur=r17 MAIN: ;Initialisation des ports ; Port C complètement en sortie ser temp out DDRC, temp ; Pin 0 du port A en entrée ldi temp, 0b11111110 out DDRA, temp FRONT_MONTANT: sbis PINA, 0 ; Si CLK = 1, ne pas rjmp FRONT_MONTANT ;revenir à FRONT_MONTANT ;Incrémenter compteur inc compteur ;Sortir compteur sur le port C out PORTC, compteur .def temp=r16 .def compteur=r17 MAIN: ;Initialisation des ports ; Port C complètement en sortie ser temp out DDRC, temp ; Pins 0, 1, 2 du port A en entrée ldi temp, 0b11111000 out DDRA, temp FRONT_MONTANT: sbis PINA, 2 ; Si Reset_n = 1, ne pas clr compteur ; effacer le compte sbis PINA, 0 ; Si CLK = 1, ne pas rjmp FRONT_MONTANT ;revenir à FRONT_MONTANT sbis PINA, 1 dec compteur sbis PINA, 0 inc compteur ; ; ; ; Si ascendant, ne pas décrémenter compteur Si descendant, ne pas incrémenter compteur ;Sortir compteur sur le port C out PORTC, compteur FRONT_DESC: sbic PINA, 0 ; Si CLK = 0, ne pas rjmp FRONT_DESC ;revenir à FRONT_DESC FRONT_DESC: sbis PINA, 2 ; Si Reset_n = 1, ne pas clr compteur ; effacer le compte sbic PINA, 0 ; Si CLK = 0, ne pas rjmp FRONT_DESC ;revenir à FRONT_DESC rjmp FRONT_MONTANT rjmp FRONT_MONTANT CHAPITRE 3. SOLUTIONS AUX EXERCICES 98 R16 a) On se sert de l’instruction sbis pour sauter l’instruction d’après si le bit 1 de PINA est à 1. Or, l’instruction d’après est une macro. On pourrait penser qu’elle serait sautée, mais c’est bien seulement la première instruction qui serait sautée. b) 0xFF R17 Ces instructions servent à placer le pointeur de pile à la fin de la RAM. Ceci est nécessaire avant tout appel de rcall, ret, push ou pop. R18 0x02 R19 a) Le programme va fonctionner, mais il comporte tout de même une erreur grave. Lorsqu’on utilise la fonction rcall, c’est pour appeler temporairement une fonction et ensuite revenir après l’instruction rcall grâce à un ret. Or, au lieu du ret en fin de fonction, on retrouve un autre rcall. On ne sortira donc jamais de cette fonction ; de plus, comme rcall sauve l’adresse de retour dans la RAM, la RAM sera pleine en une fraction de seconde et le pointeur de pile (Stack Pointer) fera un débordement. b) Pour résoudre ce problème, il faudrait remplacer la dernière instruction de la fonction CLIGNOTE (l’instruction rcall tout de suite après le nop) par l’instruction ret. R20 L’instruction push sert à placer temporairement un registre dans la pile, afin d’utiliser ce registre pour autre chose. L’instruction pop sert à recharger la dernière valeur mise dans la pile, dans un registre. F IG . 3.4 – Réponse à l’exercice 15 b) R21 r16 = 127, r17 = 34, r18 = 15 R22 a) Voir la figure 3.5 b) Voir la figure 3.6 c) 99 ;Variable temporaire .def temp=r16 ;Zero, pour additionner Z et compteur .def zero=r17 ;Compteur dans le tableau .def compteur=r18 F IG . 3.5 – Réponse à l’exercice 22 a) MAIN: ;Initialisation de la pile ldi temp, high(RAMEND) out SPH, temp ldi temp, low(RAMEND) out SPL, temp ;Initialisation des ports ;Port A : bits 0, 1 et 2 en entrée ldi temp, 0b11111000 out DDRA, temp ;Port B en sortie au complet ser temp out DDRB, temp ;Compteur, zero = 0 clr compteur clr zero FRONT_MONTANT: sbis PINA, 0 ;Si PA0=1, ne pas rjmp FRONT_MONTANT ;Chargement de l’adresse du ;bon tableau dans Z rcall CHARGEMENT ;Addition compteur et Z add ZL, compteur adc ZH, zero ;Chargement de la donnee lpm temp, Z ;Envoi sur le port B out PORTB, temp inc compteur FRONT_DESC: sbic PINA, 0 ;Si PA0=0, ne pas rjmp FRONT_DESC rjmp BOUCLE F IG . 3.6 – Réponse à l’exercice 22 b) ;********************************************* ;Chargement de l’adresse du bon tableau dans Z CHARGEMENT: in temp, PINA cpi temp, 0 100 CHAPITRE 3. SOLUTIONS AUX EXERCICES breq CHARGE_SINUS cpi temp, 1 breq CHARGE_SCIE cpi temp, 2 breq CHARGE_TRIANGLE CHARGE_CARRE: ldi ZL, low(CARRE*2); ldi ZH, high(CARRE*2); ret CHARGE_SINUS: ldi ZL, low(SINUS*2); ldi ZH, high(SINUS*2); ret CHARGE_SCIE: ldi ZL, low(SCIE*2); ldi ZH, high(SCIE*2); ret CHARGE_TRIANGLE: ldi ZL, low(TRIANGLE*2); ldi ZH, high(TRIANGLE*2); ret R23 a) 0x16 b) 0x00 c) 0x13 d) 0x24 R24 a) Voir la figure 3.7. b) ; Définition des registres ; Caractère à afficher .def caractere = r16 ; Compteur (10 caractères) .def compteur = r17 ; Variable temporaire .def temp = r18 ;Initialisation de la pile ldi temp, low(RAMEND) out SPL, temp ldi temp, high(RAMEND) out SPH, temp ;Initialisation des ports ;On assume que les ports relatifs ;au LCD sont initialisés dans ;LCD_INIT. F IG . 3.7 – Réponse à l’exercice 24 a) 101 cbi DDRA, 0 ;PA0 en entrée ;Initialisation de l’écran LCD rcall LCD_INIT NOUVEAU: sbis PINA, 0 ;Si PA0=1, ne pas rjmp ADDRBONJOUR ;aller a ADDRBONJOUR ADDRAUREVOIR: ldi ZL, low(AUREVOIR*2) ldi ZH, high(AUREVOIR*2) rjmp COMPTEUR10 ADDRBONJOUR: ldi ZL, low(BONJOUR*2) ldi ZH, high(BONJOUR*2) COMPTEUR10: ldi compteur, 10 ;Cursor Home du LCD rcall LCD_CURSOR_HOME BOUCLE: lpm caractere, Z+ rcall LCD_WRITE_CHAR ;Décrémenter le compteur dec compteur ;Si 0, aller à NOUVEAU breq NOUVEAU ;Sinon, aller à BOUCLE rjmp BOUCLE st Y, r17 ld r18, X+ ld r19, -Y Donc à la fin du programme : XL = 0x01, XH = 0x01, YL = 0xFF, YH = 0x00, r18 = 0x7D, r19 = 0x7C R26 Utiliser la RAM aux adresses 0xA0 à 0xA2 pour permuter les registres r16, r17 et r18 de cette façon : r16 → 17 → r18 → r16. R27 R25 ldi XL, 0xFF clr XH mov YL, XH ldi YH, 1 ldi r16, 0x7C ldi r17, 0x7D st X+, r16 F IG . 3.8 – Réponse à l’exercice 27 a) ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; XL=0xFF XH=0x00 YL=0x00 YH=0x01 r16=0x7C r17=0x7D RAM[0x00FF]=0x7C XL=0x00 XH=0x01 RAM[0x0100]=0x7D r18=RAM[0x0100] =0x7D XL=0x01 XH=0x01 YL=0xFF YH=0x00 r19=RAM[0x00FF] =0x7C Chargement de la mémoire de programme vers la RAM a) Z = adresse de la mémoire de programme, Y = adresse de la mémoire vive. Voir la figure 3.8 b) .def contenu = r16 .def compteur = r17 .equ addrbaseRAM = 0x0060 TRANSFERT_MEMOIRE: clr compteur ; Assigner l’adresse de base : RAM ldi YL, low(addrbaseRAM) ldi YH, high(addrbaseRAM) ; Assigner l’adresse de base : FLASH ldi ZL, low(TABLE*2) CHAPITRE 3. SOLUTIONS AUX EXERCICES 102 ldi ZH, high(TABLE*2) R29 BOUCLE: cpi compteur, 54 ;Si compteur = 54 breq RETOUR ;Aller à RETOUR ser r16 clr XH ldi XL, 0x32 out 0x11, r16 st X+, r16 sbiw XH:XL, 2 ld r17, -X ;Lire FLASH, inc Z lpm contenu, Z+ ;Écrire RAM, inc Y st Y+, contenu rjmp BOUCLE RETOUR: ret R28 a) Timer 0 en mode Fast PWM b) Entrée = PORTA (ou PORTC ou PORTD), Sortie = PB0 (OC0, pin 1) c) Détermination de TCCR0 : WGM1..0 = 11 (Fast PWM) COM01..00 = 10 (Actif lorsque le TCNT0 < OCR0) CS2..0 = 001 (Pas de prescaling, le plus rapide possible) TCCR0 = 0b01101001 TCNT0 : Géré automatiquement ; ; ; ; ; X = 0x0032 DDRD = 0xFF, tout en sortie PORTD = 0xFF, X = 0x0033 X = 0x0031 X = 0x0030, r17 = PIND = 0xFF r17 vaut donc 0xFF à la fin de ce programme. R30 .org 0x0000 ldi r16, 0b00110011 ; r16 = 0b00110011 mov r15, r16 ; r15 = 0b00110011 ldi r16, 0b00001111 ; r16 = 0b00001111 ldi XL, 15 ; X pointe vers r15 ld r17, X+ ; r17 = 0b00110011 ; X pointe vers r16 ld r18, X+ ; r18 = 0b00001111 ; X pointe vers r17 eor r17, r18 ; r17 = 0b00111100 Donc à la fin du programme : r15 = 0b00110011 OCR0 : Continuellement mis à jour par le programme r16 = 0b00001111 DDRB = 0x01 (Au moins la pin PB0 en sortie) r17 = 0b00111100 d) r18 = 0b00001111 XL = 17 ;PORTA en entrée par défaut (au démarrage) ;Configuration du Timer0 ldi r16, 0b01101001 out TCCR0, r16 R31 sbi DDRB, 0 ;PB0 en sortie b) Premièrement, on doit mettre le bit 0 du port B en sortie (OC0) : a) Modulation PWM grâce au Timer0 (mode Fast PWM) BOUCLE: in r16, PINA ;Lire l’entrée numérique out OCR0, r16 ;Mettre son contenu ;dans le comparateur rjmp BOUCLE Ensuite, on doit configurer le timer en mode Fast PWM : W GM01 : 00 = 11. (6 instructions) On doit aussi configurer le comportement de la pin OC0 : COM01 : 00 = 10. DDRB0 = 1 103 Toutes les initialisations Initialisation de la pile Initialisation des ports Initialisation du timer0 Initialisation des interruptions Retour F IG . 3.10 – Réponse à l’exercice 31 f) - Ordinogramme 1 Initialiser le calcul du RPM et de la vitesse RPM : Remettre le nombre d’interruption reçues à zéro F IG . 3.9 – Réponse à l’exercice 31 e) Retour Finalement, on doit configurer la vitesse la plus rapide possible (pas de prescaler) : CS02 : 00 = 001. F IG . 3.11 – Réponse à l’exercice 31 f) - Ordinogramme 2 Ce qui donne : TCCR0 = 01101001 c) Interruption externe : front sur INT0, INT1 ou INT2. La solution donnée sera sur le front montant de INT0. sregsave = r21 = Sauvegarde du status register lors de l’interruption h) .def temp = r16 d) Premièrement, on doit mettre le bit 2 du port D en entrée .def nbinterrupts = r17 (INT0) : DDRD2 = 0. .def compteur1 = r18 .def compteur2 = r19 Ensuite, on doit activer l’interruption externe : .def compteur3 = r20 .def sregsave = r21 GICR = 01000000 rjmp RESET Finalement, on doit choisir le front de l’interruption (front rjmp INTERRUPTION montant ou front descendant). En choisissant le front mon- RESET: tant : ; Initialisation de la pile ldi temp, low(RAMEND) out SPL, temp MCUCR = 00000011 ldi temp, high(RAMEND) out SPH, temp e) Voir la figure 3.9 f) Voir les figures 3.10, 3.11, 3.12 et 3.13. ; Initialisation des ports clr temp g) out DDRA temp = r16 = Registre temporaire ser temp out DDRB nbinterrupts = r17 = Nombre d’interruptions externes dans out DDRC 300ms ldi temp, 0b11111010 compteur1 = r18 = Boucle de délai 1 out DDRD compteur2 = r19 = Boucle de délai 2 compteur3 = r20 = Boucle de délai 3 ; Initialisation du timer 0 ldi temp, 0b01101001 CHAPITRE 3. SOLUTIONS AUX EXERCICES 104 out TCCR0, temp ; Initialisation des interruptions ldi temp, 0b01000000 out GICR, temp ldi temp, 0b00000011 out MCUCR, temp sei Calcul et affichage des quatre informations Mettre 2x le nombre d’interruptions sur le bus data Front montant sur le signal d’horloge du RPM rjmp BOUCLE Sortie du comparateur du module de vitesse Incrémenter OCR0 Décrémenter OCR0 Mettre OCR0 sur le bus data Front montant sur le signal d’horloge de la vitesse Sélection = 0 : Jauge à essence Mettre données sur le bus data Front montant sur le signal d’horloge du niveau d’essence Sélection = 1 : Température Mettre données sur le bus data Front montant sur le signal d’horloge de la température Retour F IG . 3.12 – Réponse à l’exercice 31 f) - Ordinogramme 3 Interruption sur pin externe Sauver SREG Incrémenter le nombre d’incrémentations reçues Restaurer SREG Retour F IG . 3.13 – Réponse à l’exercice 31 f) - Ordinogramme 4 ;****************** DELAI: ; Délai de 300ms ; On attend environ 1228800 cycles ; On peut le faire avec trois boucles imbriquées ; de 15, 64 et 128 fois 10 cycles. ; Ou toute autre combinaison qui donne ; approximativement le même résultat ldi compteur1, 15 DELAI1: ldi compteur2, 64 DELAY2: ldi compteur3, 128 DELAY3 ;Environ 10 cycles dans cette boucle nop; nop; nop; nop; nop; nop; nop; dec compteur3 brne DELAY3 dec compteur2 brne DELAY2 dec compteur1 brne DELAY1 ret ;*************** CALCUL: ; Calcul et affichage des quatre informations ; RPM lsl nbinterrupts out PORTC, nbinterrupts sbi PORTD, 6 ; Front montant sur clk cbi PORTD, 6 ; Calcul vitesse in temp, OCR0 sbis PIND, 0 ; Si on ne lit pas zéro inc temp ; On n’incrémente pas sbic PIND, 0 ; Si on ne lit pas un dec temp ; On de décrémente pas out OCR0, temp ; Afficher la vitesse out PORTC, temp sbi PORTD, 7 cbi PORTD, 7 105 ; Affichage essence cbi PORTD, 3 ; Selection=0 in temp, PINA out PORTC, temp sbi PORTD, 5 cbi PORTD, 5 ; Affichage de la température sbi PORTD, 3 ; Selection = 1 in temp, PINA out PORTC, temp sbi PORTD, 4 cbi PORTD, 4 ret ;************** INTERRUPTION: ; Interruption externe in sregsave, SREG inc nbinterrupts out SREG, sregsave reti ;************* BOUCLE: ;Boucle principale ; Initialiser le calcul du RPM et de la vitesse clr nbinterrupts ; Délai de 300ms rcall DELAI ; Calcul et affichage rcall CALCUL rjmp BOUCLE R32 Le circuit 1 ne peut pas fonctionner, car RA3 est utilisée en sortie (impossible) TAB . 3.2 – Réponse à l’exercice 33 Registre d’E/S a) b) c) ANSEL 00000000 00000000 00000000 CMCON 00000111 00000111 00000111 TRISA xx000000 xx111111 xx000000 WPUA xxxxxxxx xx111111 xx000111 TRISC xx111111 xx001111 xx000000 OPTION_REG 1xxxxxxx 0xxxxxxx 0xxxxxxx R34 a) On travaillera directement à partir du port C, sans nécessiter de registre compteur. On ne fait donc qu’enlever l’étape « Sortir compteur sur PORTC ». b) MAIN ;Initialisation des ports bcf STATUS,RP0 ;Banque 0 clrf PORTA movlw 07h ; Pas de comparateur movwf CMCON bsf STATUS,RP0 ;Banque 1 clrf ANSEL ;E/S numériques ;PORTA : Bit 0 en entrée movlw B’00000001’ movwf TRISA ;PORTC : Complètement en sortie movlw B’00000000’ movwf TRISC bcf STATUS,RP0 ; Banque 0 FRONT_MONTANT btfss PORTA, 0 ; Si CLK=1, ne pas goto FRONT_MONTANT ;Incrémenter compteur incf PORTC, f FRONT_DESC btfsc PORTA, 0 ; Si CLK=0, ne pas goto FRONT_DESC Le circuit 2 ne peut pas fonctionner, car le port C est utilisé en entrée où des résistances de pull-up sont nécessaires. Or, le port C ne comporte pas de pull-ups. Le circuit 3 peut fonctionner. goto FRONT_MONTANT R35 Le circuit 4 ne peut pas fonctionner, car le cristal partage des a) On travaillera directement à partir du port C, sans nécespins utilisées (OSC1 = RA5 et OSC2 = RA4). siter de registre compteur. On ne fait donc qu’enlever l’étape « Sortir compteur sur PORTC ». R33 b) Voir la table 3.2 MAIN CHAPITRE 3. SOLUTIONS AUX EXERCICES 106 ;Initialisation des ports bcf STATUS,RP0 ;Banque 0 clrf PORTA movlw 07h ; Pas de comparateur movwf CMCON bsf STATUS,RP0 ;Banque 1 clrf ANSEL ;E/S numériques ;PORTA : Bits 0,1,2 en entrée movlw B’00000111’ movwf TRISA ;PORTC : Complètement en sortie movlw B’00000000’ movwf TRISC bcf STATUS,RP0 ; Banque 0 En somme, reg[0x21] doit être strictement plus grand que reg[0x20]. c) reg[0x21] doit être égal à reg[0x20]. R37 a) Premièrement, on trouve la fréquence d’un cycle, qui est de : fcycle = Ce qui donne une période pour un incrément de : FRONT_MONTANT btfss PORTA, 2 ;Si Reset_n=1, ne pas clrf PORTC btfss PORTA, 2 ; Si CLK=1, ne pas goto FRONT_MONTANT btfss PORTA, 1 ; Si ascendant, ne pas decf PORTC, f btfsc PORTA, 0 ; Si descendant, ne pas incf PORTC, f FRONT_DESC btfss PORTA, 2 ; Si Reset_n=1, ne pas clrf PORTC btfsc PORTA, 0 ; Si CLK=0, ne pas goto FRONT_DESC goto FRONT_MONTANT fosc = 1MHz 4 tcycle = 1 fcycle = 1µs On constate donc qu’on n’a pas besoin de prescaler. Réponse : voir la table 3.3. b) On doit aller 32 fois moins vite qu’en a), on met donc un prescaler de 1 pour 32. Réponse : voir la table 3.4. c) On doit connecter l’entrée du timer sur la pin externe T0CKl, et mettre un prescaler de 1 pour 8. On doit bien sûr configurer T0CKl en entrée, qui correspond à RA2. Réponse : voir la table 3.5. d) On doit connecter l’entrée du timer sur la pin externe T0CKl, inverser cette entrée, et ne pas mettre de prescaler. Réponse : voir la table 3.6. R36 movfw 0x20 subwf 0x21, w btfss STATUS, C goto LABEL1 btfss STATUS, Z goto LABEL2 goto LABEL3 R38 ;Faire reg[0x21] - reg[0x20] ;C=1, donc pas d’overflow ;sur la soustraction. ;reg[0x21] >= reg[0x20]. Ne pas ;aller à LABEL1 ;Z=1, donc ;reg[0x21] = reg[0x20]. Ne pas ;aller à LABEL2 ;aller à LABEL3 a) Pour ne pas sauter le goto vers LABEL1, reg[0x21] doit être strictement plus petit que reg[0x20]. Connecter l’entrée du timer sur la pin externe T0CKl, et s’assurer que cette pin soit stable. R39 a) On n’a pas besoin de prescaler, et on utilise la fréquence interne du microcontrôleur. Réponse : voir la table 3.7. b) Même chose qu’en a), mais on utilise un prescaler de 1 pour 8. b) Pour sauter le goto vers LABEL1, reg[0x21] doit être plus Réponse : voir la table 3.8 grand ou égal à reg[0x20]. De plus, pour ne pas sauter le goto vers LABEL2, reg[0x21] c) On utilise la pin externe OSC1 sans prescaler. On doit bien doit être différent de reg[0x20]. sûr configurer OSC1 en entrée (qui correpond à RA5). 107 - - RAPUn x TAB . 3.3 – Réponse à l’exercice 37 a) OPTION_REG INTEDG T0CS T0SE PSA PS2 x 0 x 1 x PS1 x PS0 x RAPUn x TAB . 3.4 – Réponse à l’exercice 37 b) OPTION_REG INTEDG T0CS T0SE PSA PS2 x 0 x 0 1 PS1 0 PS0 0 RAPUn x INTEDG x - - TAB . 3.5 – Réponse à l’exercice 37 c) OPTION_REG T0CS T0SE PSA PS2 1 0 0 0 TRISA TRISA5 TRISA4 TRISA3 TRISA2 x x x 1 PS1 1 PS0 0 TRISA1 x TRISA0 x TAB . 3.6 – Réponse à l’exercice 37 d) OPTION_REG T0CS T0SE PSA PS2 1 1 1 x TRISA TRISA5 TRISA4 TRISA3 TRISA2 x x x 1 PS1 x PS0 x TRISA1 x TRISA0 x TMR1GE 0 TAB . 3.7 – Réponse à l’exercice 39 a) T1CON T1CKPS1 T1CKPS0 T1OSCEN T1SYNCn 0 0 x x TMR1CS 0 TMR1ON 1 TMR1GE 0 TAB . 3.8 – Réponse à l’exercice 39 b) T1CON T1CKPS1 T1CKPS0 T1OSCEN T1SYNCn 1 1 x x TMR1CS 0 TMR1ON 1 TMR1CS 1 TMR1ON 1 TRISA1 x TRISA0 x RAPUn x INTEDG x - - - TMR1GE 0 - - TAB . 3.9 – Réponse à l’exercice 39 c) T1CON T1CKPS1 T1CKPS0 T1OSCEN T1SYNCn 0 0 x x TRISA TRISA5 TRISA4 TRISA3 TRISA2 1 x x x CHAPITRE 3. SOLUTIONS AUX EXERCICES 108 F IG . 3.14 – Réponse à l’exercice 42 a) R40 Au moment du retour de la fonction, TMR1L se sera déjà incrémenté de 2. Pour résoudre ce problème, on peut simplement écrire 11 dans TMR1L, ou écrire 13 de nouveau dans TMR1L, après TMR1H. Il est toutefois important d’écrire dans TMR1L avant TMR1H. Sinon, considérons ce code : 1 2 3 4 movlw movwf movlw movwf 0 TMR1H 13 TMR1L Si à l’instruction 2, TMR1L vaut 255, TMR1H ne vaudra pas 0, mais bien 1 à l’instruction 3. R41 movfw movwf movlw addwf 0x5E FSR ; FSR = adresse de base 0x20 FSR, f ; Maintenant, INDF pointe sur ; le bon registre movfw INDF ; Lire le bon registre movwf 0x5D ; Écrire sur contenu sur 0x5D R42 a) Solution suggérée : Voir la figure 3.14. b) Il y a 10 bits de précision sur le convertisseur analogique, donc 1024 niveaux de tension possible. On a donc : %Vout = 5 5 = %T 1024 128 %T = 0, 125◦C F IG . 3.15 – Réponse à l’exercice 42 c) 109 c) Solution suggérée : Voir la figure 3.15. d) #define #define #define #define TdemandeeL TdemandeeH TambianteL TambianteH 0x20 0x21 0x22 0x23 ;Initialisation des ports bcf STATUS, RP0 ; Banque 0 clrf PORTA clrf PORTC movlw 0x07 movwf CMCON ; Desactiver le comparateur bsf STATUS, RP0 ; Banque 1 movlw B’00000011’ movwf TRISA ; RA0, RA1 en entree movwf ANSEL ; RA0, RA1 analogiques clrf TRISC ; Port C en sortie bcf STATUS, RP0 ; Banque 0 ;Initialisation de l’ADC movlw B’00000001’ movwf ADCON0 ; ADC ON bsf STATUS, RP0 ; Banque 1 movlw B’01100000’ movwf ADCON1 ; Prescaler le plus lent ; pour avoir la meilleure precision bcf STATUS, RP0 ; Banque 0 BOUCLE ;Conversion sur AN0 movlw B’00000011’ movwf ADCON0 ;Attendre la fin de la conversion ATTENTE_ADC_1 btfsc ADCON0, 1 goto ATTENTE_ADC_1 ;Sauver le resultat movfw ADRESH movwf TambianteH bsf STATUS, RP0 movfw ADRESL bcf STATUS, RP0 movwf TambianteL ;Conversion sur AN1 movlw B’00000111’ movwf ADCON0 ;Attendre la fin de la conversion ATTENTE_ADC_2 btfsc ADCON0, 1 goto ATTENTE_ADC_2 ;Sauver le resultat movfw ADRESH movwf TdemandeeH bsf STATUS, RP0 movfw ADRESL bcf STATUS, RP0 movwf TdemandeeL ;Tdemandee = ;Tdemandee - Tambiante ;Commencer par les parties basses movfw TambianteL subwf TdemandeeL, f ;S’il n’y a pas eu d’emprunt btfss STATUS, C ;ne pas ;propager cet emprunt sur la ;partie haute. decf TdemandeeH ;Terminer par les parties hautes movfw TambianteH subwf TdemandeeH, f ;Determiner ou on s’en va btfss STATUS, Z ;Si zero, ne pas goto PAS_EGAL movf TdemandeeL, f btfss STATUS, Z ;Si zero, ne pas goto PAS_EGAL ;Ici, Tdemandee=Tambiante goto BOUCLE PAS_EGAL btfss TdemandeeH, 7 ;Si negatif, alors ;Tdemandee < Tambiante ;donc ne pas bsf PORTC, 0 ;allumer l’element chauffant btfsc TdemandeeH, 7 ;Si positif, alors ;Tdemandee > Tambiante ;donc ne pas bcf PORTC, 0 ;eteindre l’element chauffant goto BOUCLE R43 a) PORTA Change Interrupt CHAPITRE 3. SOLUTIONS AUX EXERCICES 110 #define PORTAbak 0x20 #define status_temp 0x21 #define w_temp 0x22 org 0x0000 goto MAIN org 0x0004 goto INTERRUPT MAIN ;Initaliser le port A clrf PORTA movlw 0x07 b) Timer 0 Overflow Interrupt (note : il est aussi possible, movwf CMCON ;Comparateur désactivé moyennant un code moins efficace, d’utiliser l’interruption bsf STATUS, RP0 ;Banque 1 externe, ou bien une combinaison de l’interruption externe et clrf ANSEL ;Entrées numériques du timer 1. Seulement le Timer 0 Overflow Interrupt sera démovlw 0xFF veloppé dans cette solution). movwf TRISA ;Tout en entrée c) Voir la figure 3.16 movlw B’00110011’ d) movwf WPUA ;Pull-ups movwf IOCA ;Activations pour Configuration du port A : ;PORTA change interrupt ANSEL = 0 (aucune entrée analogique) bcf STATUS, RP0 ;Banque 0 CMCON = 0x07 (comparateur désactivé) ;Initialiser le timer 0 TRISA = 255 (tout en entrée) bsf STATUS, RP0 ;Banque 1 movlw B’00100111’ WPUA = B’00110011’ (Pull-ups pour les marmottes activées) movwf OPTION_REG IOCA = B’00110011’ (activer les interruptions sur les chanbcf STATUS, RP0 gements du port A dues au marmottes) clrf TMR0 ;Mettre le timer0 à 0 Configuration du Timer 0 : ;Initialiser les interruptions Fréquence = 65536 Hz movlw B’10101000’ Si on divise par 256 incréments pour le Timer 0 Overflow, et movwf INTCON ;Mettre tous les flags a 0 par 256 grâce au Prescaler, on obtient une période d’overflow ;et activer les interruptions du timer d’exactement 1 seconde. F IG . 3.16 – Réponse à l’exercice 43 c) OPTION_REG : T0CS = 1 (Source externe, pin T0CKl) T0SE = 0 (Front montant. Front descendant fonctionne aussi.) PSA = 0 (Prescaler actif) PS2 :PS0 = 111 (Prescaler = 1 :256) RAPU = 0 (Pull-ups enable pour le port A) OPTION_REG = B’00100111’ Configuration des interruptions : INTCON : BOUCLE goto BOUCLE INTERRUPTION ;Sauver STATUS et W movwf w_temp swapf STATUS, w bcf STATUS, RP0 movwf status_temp ;Sauver la marmotte frappee movfw PORTA movwf PORTAbak T0IE = 1 (Timer Overflow Interrupt actif) RAIE = 1 (Port A Change Interrupt actif) GIE = 1 (Activer les interruptions générales) INTCON = B’10101000’ e) Voir la figure 3.17 f) ;Timer0 Overflow ? btfsc INTCON, T0IF ;Si pas un Timer0 Overflow, ;ne pas goto TIMER0_OVERFLOW ;aller a TIMER0_OVERFLOW ;Effacer le timer 0 111 F IG . 3.17 – Réponse à la question 43 e) CHAPITRE 3. SOLUTIONS AUX EXERCICES 112 TAB . 3.10 – Calcul des temps pour l’exercice 44 a) Étape Temps Lecture de la mémoire d’instructions 2ns Lecture des registres/Décodage de l’instruction 1ns Calcul arithmétique 2ns Accès à la mémoire de données 2ns Écriture dans les registres 1ns Total 8ns c) On doit dessiner le pipeline (figure 3.18) et vérifier qu’il n’y ait pas de problèmes d’interdépendances procédurales ou de données. Comme il n’y a pas de problèmes dans le pipeline, on constate qu’il ne faudra que 12ns pour exécuter ce programme. R45 a) Voir la figure 3.19 TAB . 3.11 – Calcul des temps pour l’exercice 44 b) Instr. IF ID EX MEM WB Total 1 2ns 1ns 2ns 1ns 6ns 2 2ns 1ns 2ns 1ns 6ns 3 2ns 1ns 2ns 2ns 7ns 4 2ns 1ns 2ns 5ns Total 24ns clrf TMR0 ;Marmotte 1..4 frappée ? btfss PORTAbak, 0 call MARMOTTE1_FRAPPEE btfss PORTAbak, 1 call MARMOTTE2_FRAPPEE btfss PORTAbak, 4 call MARMOTTE3_FRAPPEE btfss PORTAbak, 5 call MARMOTTE4_FRAPPEE goto RETOUR_INTERRUPT TIMER0_OVERFLOW call FIN_DE_PARTIE RETOUR_INTERRUPT ;Restaurer STATUS et W swapf status_temp, w movwf STATUS swapf w_temp, f swapf w_temp, w retfie b) Il faut inverser les lignes 2 et 3, et ajouter un nop entre ces lignes. Voir la figure 3.20 R46 a) Non, c’est impossible puisque le ATmega8515 manquerait d’entrées/sorties pour les signaux d’activation (CS) des 256 esclaves. b) Oui, c’est possible. On n’a qu’à envoyer 256 messages un après l’autre. Une fois les 256 messages envoyés, on remet CS à 1 pour informer chaque esclave que son message propre est maintenant dans son tampon. c) On encode l’adresse de l’esclave dans le message. Les deux esclaves lisent donc à tout moment, mais seulement un a le droit d’activer sa sortie pour communiquer avec le maître. d) Oui, il suffirait d’envoyer un octet d’adresse qui spécifierait à quel esclave on veut parler ; puis on enverrait l’octet de données utiles. R47 Note : l’initialisation des ports a été omise pour ne conserver que ce qui est propre à la communication SPI. a) On utilise la variable de 8 bits « registre », qui est en fait le contenu du registre à décalage. Ordinogramme : voir la figure 3.21. b) On ajoute une autre variable, « compteur », qui conserve le nombre de bits reçus. R44 Ordinogramme : voir la figure 3.22 a) On doit utiliser le temps du plus long datapath possible pour c) Voir la figure 3.23 toutes les instructions : voir la table 3.10. d) Voir la figure 3.24 Comme on a 4 instructions, il faudra donc 32ns pour exécuter le programme. R48 b) On doit séparer les instructions en microinstructions, chacune utilisant les blocs fonctionnels nécessaires seulement : a) voir la table 3.11. – Il faut 4 cycles pour que le compteur de programme atIl faudra donc 24ns pour exécuter le programme. teigne l’adresse 0x0004 ; 113 F IG . 3.18 – Réponse à l’exercice 44 c) IF ID zero WB t1 EX Bubble Bubble ID t1 t2 IF EX MEM ID t2 IF Bubble EX MEM Bubble IF WB t3 ID t1 t3 WB s1 EX F IG . 3.19 – Réponse à l’exercice 45 a) ID zero IF ID t2 IF nop WB t1 EX EX IF WB t3 MEM ID ID t1 t2 IF IF EX MEM ID t1 t3 F IG . 3.20 – Réponse à l’exercice 45 b) EX WB s1 CHAPITRE 3. SOLUTIONS AUX EXERCICES 114 MAIN BOUCLE non Front montant sur l’horloge oui SDO = Registre(0) Décaler le registre vers la droite Registre(7) = SDI F IG . 3.21 – Réponse à l’exercice 47 a) MAIN INTERRUPTION Compteur = 8 Sauver STATUS et W Initialiser les interruptions externes (pin INT) SDO = Registre(0) Décaler le registre vers la droite CODE UTILE Registre(7) = SDI Décrémenter Compteur MAIN Compteur = 8 non Compteur = 0 BOUCLE oui non Front montant sur l’horloge Appeler la fonction qui traite le registre qu’on vient de recevoir oui SDO = Registre(0) Compteur = 8 RETOUR_INT Décaler le registre vers la droite Effacer le flag d’interruption Registre(7) = SDI Restaurer STATUS et W Décrémenter Compteur Retour F IG . 3.23 – Réponse à l’exercice 47 c) non Compteur = 0 oui Appeler la fonction qui traite le registre qu’on vient de recevoir Compteur = 8 F IG . 3.22 – Réponse à l’exercice 47 b) 115 – Il faut 4 cycles pour sauver l’accumulateur et le STATUS. MAIN INTERRUPTION Compteur = 8 Sauver STATUS et W Au total, on doit attendre 8 cycles avant même de pouvoir lire le port A. b) 8 cycles c) Initialiser le timer 0, mais ne pas activer les interruptions sur débordement tout de suite. Interruption externe non Période entre deux interruptions : oui Initialiser les interruptions externes (pin INT) non Compteur = 8 (1er bit reçu) CODE UTILE ttotal = 1 = 50µs 20kHz Temps requis pour atteindre l’adresse 0x0004 après une interruption : oui Timer0 = 0 t0x0004 = 1 × 4 = 4µs 4MHz/4 Effacer le flag du timer0 Activer les interruptions sur débordement du timer0 Temps requis pour sauvegarder et restaurer l’accumulateur et le STATUS : tW+STATUS = DEBUT_RECEPTION 1 × 8 = 8µs 4MHz/4 SDO = Registre(0) Temps disponible pour du code utile dans l’interruption : Décaler le registre vers la droite tutile = 50µs − 4µs − 8µs = 38µs Registre(7) = SDI Décrémenter Compteur Nombre de cycles disponibles pour du code utile dans l’interruption : nbcycles utiles = 38µs × non Compteur = 0 oui Appeler la fonction qui traite le registre qu’on vient de recevoir RESET_INT Désactiver les interruptions sur le débordement du timer0 Compteur = 8 4MHz = 38 cycles 4 d) Avec si peu de cycles, il vaudrait mieux penser à baisser la fréquence de communication, ou bien envisager une communication unidirectionnelle (ou encore les deux). À ce propos, on pourrait par exemple suggérer une communication constante sur 16 bits, où le premier octet serait toujours du maître à l’esclave, et où le deuxième octet serait toujours de l’esclave au maître. R49 RETOUR_INT Effacer le flag d’interruption a) 1er octet = 00100011 ; 2ème octet = 00000000 b) 1 bit d’arrêt Restaurer STATUS et W c) Parité paire Retour F IG . 3.24 – Réponse à l’exercice 47 d) d) Communication totale = 22 bits Temps de transmission = 0,764ms Temps pour un bit = 34,73µs Vitesse de transmission = 28,8 kbps 116 R50 Lorsque la ligne est en attente ou qu’une donnée vient d’être transmise, la ligne est toujours à 1 (tension négative). Or, lorsque la ligne passe à 0, c’est qu’un bit « Start » est envoyé. Le receveur peut alors immédiatement démarrer son horloge. Ainsi, à chaque transition de la ligne de « Idle » à « Start », ou de « Stop » à « Start », le receveur remet son horloge à zéro. Si les horloges sont bien conçues, il n’y a pas de risque qu’elles divergent en aussi peu qu’une seule communication. CHAPITRE 3. SOLUTIONS AUX EXERCICES Chapitre 4 Spécifications du AVR ATmega8515 de Atmel Features • High-performance, Low-power AVR® 8-bit Microcontroller • RISC Architecture • • • • • • – 130 Powerful Instructions – Most Single Clock Cycle Execution – 32 x 8 General Purpose Working Registers – Fully Static Operation – Up to 16 MIPS Throughput at 16 MHz – On-chip 2-cycle Multiplier Nonvolatile Program and Data Memories – 8K Bytes of In-System Self-programmable Flash Endurance: 10,000 Write/Erase Cycles – Optional Boot Code Section with Independent Lock bits In-System Programming by On-chip Boot Program True Read-While-Write Operation – 512 Bytes EEPROM Endurance: 100,000 Write/Erase Cycles – 512 Bytes Internal SRAM – Up to 64K Bytes Optional External Memory Space – Programming Lock for Software Security Peripheral Features – One 8-bit Timer/Counter with Separate Prescaler and Compare Mode – One 16-bit Timer/Counter with Separate Prescaler, Compare Mode, and Capture Mode – Three PWM Channels – Programmable Serial USART – Master/Slave SPI Serial Interface – Programmable Watchdog Timer with Separate On-chip Oscillator – On-chip Analog Comparator Special Microcontroller Features – Power-on Reset and Programmable Brown-out Detection – Internal Calibrated RC Oscillator – External and Internal Interrupt Sources – Three Sleep Modes: Idle, Power-down and Standby I/O and Packages – 35 Programmable I/O Lines – 40-pin PDIP, 44-lead TQFP, 44-lead PLCC, and 44-pad QFN/MLF Operating Voltages – 2.7 - 5.5V for ATmega8515L – 4.5 - 5.5V for ATmega8515 Speed Grades – 0 - 8 MHz for ATmega8515L – 0 - 16 MHz for ATmega8515 8-bit Microcontroller with 8K Bytes In-System Programmable Flash ATmega8515 ATmega8515L Rev. 2512G–AVR–03/05 Ces spécifications sont tirées de la datasheet du AVR ATmega8515, disponible gratuitement sur le site de Atmel : www.atmel.com 117 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 118 4.1 Pinout Pin Configurations Figure 1. Pinout ATmega8515 PDIP (OC0/T0) PB0 (T1) PB1 (AIN0) PB2 (AIN1) PB3 (SS) PB4 (MOSI) PB5 (MISO) PB6 (SCK) PB7 RESET (RXD) PD0 (TDX) PD1 (INT0) PD2 (INT1) PD3 (XCK) PD4 (OC1A) PD5 (WR) PD6 (RD) PD7 XTAL2 XTAL1 GND 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 VCC PA0 (AD0) PA1 (AD1) PA2 (AD2) PA3 (AD3) PA4 (AD4) PA5 (AD5) PA6 (AD6) PA7 (AD7) PE0 (ICP/INT2) PE1 (ALE) PE2 (OC1B) PC7 (A15) PC6 (A14) PC5 (A13) PC4 (A12) PC3 (A11) PC2 (A10) PC1 (A9) PC0 (A8) TQFP/MLF (WR) PD6 (RD) PD7 XTAL2 XTAL1 GND NC* (A8) PC0 (A9) PC1 (A10) PC2 (A11) PC3 (A12) PC4 (MOSI) PB5 (MISO) PB6 (SCK) PB7 RESET (RXD) PD0 NC* (TXD) PD1 (INT0) PD2 (INT1) PD3 (XCK) PD4 (OC1A) PD5 7 8 9 10 11 12 13 14 15 16 17 39 38 37 36 35 34 33 32 31 30 29 18 19 20 21 22 23 24 25 26 27 28 PA4 (AD4) PA5 (AD5) PA6 (AD6) PA7 (AD7) PE0 (ICP/INT2) NC* PE1 (ALE) PE2 (OC1B) PC7 (A15) PC6 (A14) PC5 (A13) PA4 (AD4) PA5 (AD5) PA6 (AD6) PA7 (AD7) PE0 (ICP/INT2) NC* PE1 (ALE) PE2 (OC1B) PC7 (A15) PC6 (A14) PC5 (A13) (WR) PD6 (RD) PD7 XTAL2 XTAL1 GND NC* (A8) PC0 (A9) PC1 (A10) PC2 (A11) PC3 (A12) PC4 33 32 31 30 29 28 27 26 25 24 23 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 (MOSI) PB5 (MISO) PB6 (SCK) PB7 RESET (RXD) PD0 NC* (TXD) PD1 (INT0) PD2 (INT1) PD3 (XCK) PD4 (OC1A) PD5 6 5 4 3 2 1 44 43 42 41 40 44 43 42 41 40 39 38 37 36 35 34 PB4 (SS) PB3 (AIN1) PB2 (AIN0) PB1 (T1) PB0 (OC0/T0) NC* VCC PA0 (AD0) PA1 (AD1) PA2 (AD2) PA3 (AD3) PB4 (SS) PB3 (AIN1) PB2 (AIN0) PB1 (T1) PB0 (OC0/T0) NC* VCC PA0 (AD0) PA1 (AD1) PA2 (AD2) PA3 (AD3) PLCC NOTES: 1. MLF bottom pad should be soldered to ground. 2. * NC = Do not connect (May be used in future devices) 2 ATmega8515(L) 2512G–AVR–03/05 4.2. SCHÉMA-BLOC 119 4.2 Schéma-bloc ATmega8515(L) Overview The ATmega8515 is a low-power CMOS 8-bit microcontroller based on the AVR enhanced RISC architecture. By executing powerful instructions in a single clock cycle, the ATmega8515 achieves throughputs approaching 1 MIPS per MHz allowing the system designer to optimize power consumption versus processing speed. Block Diagram Figure 2. Block Diagram PA0 - PA7 PE0 - PE2 PC0 - PC7 PORTA DRIVERS/BUFFERS PORTE DRIVERS/ BUFFERS PORTC DRIVERS/BUFFERS PORTA DIGITAL INTERFACE PORTE DIGITAL INTERFACE PORTC DIGITAL INTERFACE VCC GND PROGRAM COUNTER STACK POINTER PROGRAM FLASH SRAM TIMERS/ COUNTERS INTERNAL OSCILLATOR XTAL1 INSTRUCTION REGISTER GENERAL PURPOSE REGISTERS WATCHDOG TIMER OSCILLATOR XTAL2 X INSTRUCTION DECODER Y MCU CTRL. & TIMING RESET Z CONTROL LINES ALU INTERRUPT UNIT AVR CPU STATUS REGISTER EEPROM PROGRAMMING LOGIC SPI USART + - INTERNAL CALIBRATED OSCILLATOR COMP. INTERFACE PORTB DIGITAL INTERFACE PORTD DIGITAL INTERFACE PORTB DRIVERS/BUFFERS PORTD DRIVERS/BUFFERS PB0 - PB7 PD0 - PD7 3 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 120 4.3 Registre d’état (SREG) ATmega8515(L) Status Register The Status Register contains information about the result of the most recently executed arithmetic instruction. This information can be used for altering program flow in order to perform conditional operations. Note that the Status Register is updated after all ALU operations, as specified in the Instruction Set Reference. This will in many cases remove the need for using the dedicated compare instructions, resulting in faster and more compact code. The Status Register is not automatically stored when entering an interrupt routine and restored when returning from an interrupt. This must be handled by software. The AVR Status Register – SREG – is defined as: Bit 7 6 5 4 3 2 1 0 I T H S V N Z C Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 SREG • Bit 7 – I: Global Interrupt Enable The Global Interrupt Enable bit must be set for the interrupts to be enabled. The individual interrupt enable control is then performed in separate Control Registers. If the Global Interrupt Enable Register is cleared, none of the interrupts are enabled independent of the individual interrupt enable settings. The I-bit is cleared by hardware after an interrupt has occurred, and is set by the RETI instruction to enable subsequent interrupts. The Ibit can also be set and cleared by the application with the SEI and CLI instructions, as described in the instruction set reference. • Bit 6 – T: Bit Copy Storage The Bit Copy instructions BLD (Bit LoaD) and BST (Bit STore) use the T-bit as source or destination for the operated bit. A bit from a register in the Register File can be copied into T by the BST instruction, and a bit in T can be copied into a bit in a register in the Register File by the BLD instruction. • Bit 5 – H: Half Carry Flag The Half Carry Flag H indicates a Half Carry in some arithmetic operations. Half Carry is useful in BCD arithmetic. See the “Instruction Set Description” for detailed information. • Bit 4 – S: Sign Bit, S = NV V The S-bit is always an exclusive or between the Negative Flag N and the Two’s Complement Overflow Flag V. See the “Instruction Set Description” for detailed information. • Bit 3 – V: Two’s Complement Overflow Flag The Two’s Complement Overflow Flag V supports two’s complement arithmetics. See the “Instruction Set Description” for detailed information. • Bit 2 – N: Negative Flag The Negative Flag N indicates a negative result in an arithmetic or logic operation. See the “Instruction Set Description” for detailed information. • Bit 1 – Z: Zero Flag The Zero Flag Z indicates a zero result in an arithmetic or logic operation. See the “Instruction Set Description” for detailed information. • Bit 0 – C: Carry Flag The Carry Flag C indicates a carry in an arithmetic or logic operation. See the “Instruction Set Description” for detailed information. 9 2512G–AVR–03/05 4.4. REGISTRES, POINTEUR DE PILE 121 4.4 Registres, pointeur de pile General Purpose Register File The Register File is optimized for the AVR Enhanced RISC instruction set. In order to achieve the required performance and flexibility, the following input/output schemes are supported by the Register File: • One 8-bit output operand and one 8-bit result input • Two 8-bit output operands and one 8-bit result input • Two 8-bit output operands and one 16-bit result input • One 16-bit output operand and one 16-bit result input Figure 4 shows the structure of the 32 general purpose working registers in the CPU. Figure 4. AVR CPU General Purpose Working Registers 7 0 Addr. R0 $00 R1 $01 R2 $02 … R13 $0D General R14 $0E Purpose R15 $0F Working R16 $10 Registers R17 $11 … R26 $1A X-register Low Byte R27 $1B X-register High Byte R28 $1C Y-register Low Byte R29 $1D Y-register High Byte R30 $1E Z-register Low Byte R31 $1F Z-register High Byte Most of the instructions operating on the Register File have direct access to all registers, and most of them are single cycle instructions. As shown in Figure 4, each register is also assigned a Data memory address, mapping them directly into the first 32 locations of the user Data Space. Although not being physically implemented as SRAM locations, this memory organization provides great flexibility in access of the registers, as the X-, Y-, and Z-pointer Registers can be set to index any register in the file. 10 ATmega8515(L) 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 122 ATmega8515(L) The X-register, Y-register, and Z-register The registers R26..R31 have some added functions to their general purpose usage. These registers are 16-bit address pointers for indirect addressing of the Data Space. The three indirect address registers X, Y, and Z are defined as described in Figure 5. Figure 5. The X-, Y-, and Z-registers 15 X-register XH XL 7 0 R27 ($1B) YH YL 7 0 R29 ($1D) Z-register 0 R26 ($1A) 15 Y-register 0 7 0 7 0 R28 ($1C) 15 ZH 7 0 ZL 7 R31 ($1F) 0 0 R30 ($1E) In the different addressing modes these address registers have functions as fixed displacement, automatic increment, and automatic decrement (see the Instruction Set reference for details). Stack Pointer The Stack is mainly used for storing temporary data, for storing local variables and for storing return addresses after interrupts and subroutine calls. The Stack Pointer Register always points to the top of the Stack. Note that the Stack is implemented as growing from higher memory locations to lower memory locations. This implies that a Stack PUSH command decreases the Stack Pointer. The Stack Pointer points to the data SRAM Stack area where the Subroutine and Interrupt Stacks are located. This Stack space in the data SRAM must be defined by the program before any subroutine calls are executed or interrupts are enabled. The Stack Pointer must be set to point above $60. The Stack Pointer is decremented by one when data is pushed onto the Stack with the PUSH instruction, and it is decremented by two when the return address is pushed onto the Stack with subroutine call or interrupt. The Stack Pointer is incremented by one when data is popped from the Stack with the POP instruction, and it is incremented by two when address is popped from the Stack with return from subroutine RET or return from interrupt RETI. The AVR Stack Pointer is implemented as two 8-bit registers in the I/O space. The number of bits actually used is implementation dependent. Note that the data space in some implementations of the AVR architecture is so small that only SPL is needed. In this case, the SPH Register will not be present. Bit Read/Write Initial Value 15 14 13 12 11 10 9 8 SP15 SP14 SP13 SP12 SP11 SP10 SP9 SP8 SPH SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 SPL 7 6 5 4 3 2 1 0 R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 11 2512G–AVR–03/05 4.5. MÉMOIRE VIVE (SRAM) 123 4.5 Mémoire vive (SRAM) SRAM Data Memory Figure 9 shows how the ATmega8515 SRAM Memory is organized. The lower 608 Data Memory locations address the Register File, the I/O Memory, and the internal data SRAM. The first 96 locations address the Register File and I/O Memory, and the next 512 locations address the internal data SRAM. An optional external data SRAM can be used with the ATmega8515. This SRAM will occupy an area in the remaining address locations in the 64K address space. This area starts at the address following the internal SRAM. The Register File, I/O, Extended I/O and Internal SRAM occupies the lowest 608 bytes in normal mode, so when using 64KB (65536 bytes) of External Memory, 64928 Bytes of External Memory are available. See “External Memory Interface” on page 24 for details on how to take advantage of the external memory map. When the addresses accessing the SRAM memory space exceeds the internal Data memory locations, the external data SRAM is accessed using the same instructions as for the internal Data memory access. When the internal data memories are accessed, the read and write strobe pins (PD7 and PD6) are inactive during the whole access cycle. External SRAM operation is enabled by setting the SRE bit in the MCUCR Register. Accessing external SRAM takes one additional clock cycle per byte compared to access of the internal SRAM. This means that the commands LD, ST, LDS, STS, LDD, STD, PUSH, and POP take one additional clock cycle. If the Stack is placed in external SRAM, interrupts, subroutine calls and returns take three clock cycles extra because the two-byte Program Counter is pushed and popped, and external memory access does not take advantage of the internal pipe-line memory access. When external SRAM interface is used with wait-state, one-byte external access takes two, three, or four additional clock cycles for one, two, and three wait-states respectively. Interrupts, subroutine calls and returns will need five, seven, or nine clock cycles more than specified in the instruction set manual for one, two, and three wait-states. The five different addressing modes for the Data memory cover: Direct, Indirect with Displacement, Indirect, Indirect with Pre-decrement, and Indirect with Post-increment. In the Register File, registers R26 to R31 feature the indirect addressing pointer registers. The direct addressing reaches the entire data space. The Indirect with Displacement mode reaches 63 address locations from the base address given by the Y- or Z-register. When using register indirect addressing modes with automatic pre-decrement and postincrement, the address registers X, Y, and Z are decremented or incremented. The 32 general purpose working registers, 64 I/O Registers, and the 512 bytes of internal data SRAM in the ATmega8515 are all accessible through all these addressing modes. The Register File is described in “General Purpose Register File” on page 10. 16 ATmega8515(L) 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 124 ATmega8515(L) Figure 9. Data Memory Map Data Memory 32 Registers 64 I/O Registers Internal SRAM (512 x 8) $0000 - $001F $0020 - $005F $0060 $025F $0260 External SRAM (0 - 64K x 8) $FFFF Data Memory Access Times This section describes the general access timing concepts for internal memory access. The internal data SRAM access is performed in two clkCPU cycles as described in Figure 10. Figure 10. On-chip Data SRAM Access Cycles T1 T2 T3 clkCPU Address Compute Address Address Valid Write Data WR Read Data RD Memory Access Instruction Next Instruction 17 2512G–AVR–03/05 4.6. MÉMOIRE PROGRAMMABLE (EEPROM) 125 4.6 Mémoire programmable (EEPROM) EEPROM Data Memory The ATmega8515 contains 512 bytes of data EEPROM memory. It is organized as a separate data space, in which single bytes can be read and written. The EEPROM has an endurance of at least 100,000 write/erase cycles. The access between the EEPROM and the CPU is described in the following, specifying the EEPROM Address Registers, the EEPROM Data Register, and the EEPROM Control Register. “Memory Programming” on page 177 contains a detailed description on EEPROM Programming in SPI or Parallel Programming mode. EEPROM Read/Write Access The EEPROM Access Registers are accessible in the I/O space. The write access time for the EEPROM is given in Table 1. A self-timing function, however, lets the user software detect when the next byte can be written. If the user code contains instructions that write the EEPROM, some precautions must be taken. In heavily filtered power supplies, VCC is likely to rise or fall slowly on Power-up/down. This causes the device for some period of time to run at a voltage lower than specified as minimum for the clock frequency used. See “Preventing EEPROM Corruption” on page 23. for details on how to avoid problems in these situations. In order to prevent unintentional EEPROM writes, a specific write procedure must be followed. Refer to the description of the EEPROM Control Register for details on this. When the EEPROM is read, the CPU is halted for four clock cycles before the next instruction is executed. When the EEPROM is written, the CPU is halted for two clock cycles before the next instruction is executed. The EEPROM Address Register – EEARH and EEARL Bit Read/Write Initial Value 15 14 13 12 11 10 9 8 – – – – – – – EEAR8 EEARH EEAR7 EEAR6 EEAR5 EEAR4 EEAR3 EEAR2 EEAR1 EEAR0 EEARL 7 6 5 4 3 2 1 0 R R R R R R R R/W R/W R/W R/W R/W R/W R/W R/W R/W 0 0 0 0 0 0 0 X X X X X X X X X • Bits 15..9 – Res: Reserved Bits These bits are reserved bits in the ATmega8515 and will always read as zero. • Bits 8..0 – EEAR8..0: EEPROM Address The EEPROM Address Registers – EEARH and EEARL – specify the EEPROM address in the 512 bytes EEPROM space. The EEPROM data bytes are addressed linearly between 0 and 511. The initial value of EEAR is undefined. A proper value must be written before the EEPROM may be accessed. 18 ATmega8515(L) 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 126 ATmega8515(L) The EEPROM Data Register – EEDR Bit 7 6 5 4 3 2 1 MSB 0 LSB Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 EEDR • Bits 7..0 – EEDR7.0: EEPROM Data For the EEPROM write operation, the EEDR Register contains the data to be written to the EEPROM in the address given by the EEAR Register. For the EEPROM read operation, the EEDR contains the data read out from the EEPROM at the address given by EEAR. The EEPROM Control Register – EECR Bit 7 6 5 4 3 2 1 0 – – – – EERIE EEMWE EEWE EERE Read/Write R R R R R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 X 0 EECR • Bits 7..4 – Res: Reserved Bits These bits are reserved bits in the ATmega8515 and will always read as zero. • Bit 3 – EERIE: EEPROM Ready Interrupt Enable Writing EERIE to one enables the EEPROM Ready Interrupt if the I-bit in SREG is set. Writing EERIE to zero disables the interrupt. The EEPROM Ready interrupt generates a constant interrupt when EEWE is cleared. • Bit 2 – EEMWE: EEPROM Master Write Enable The EEMWE bit determines whether setting EEWE to one causes the EEPROM to be written. When EEMWE is set, setting EEWE within four clock cycles will write data to the EEPROM at the selected address If EEMWE is zero, setting EEWE will have no effect. When EEMWE has been written to one by software, hardware clears the bit to zero after four clock cycles. See the description of the EEWE bit for an EEPROM write procedure. • Bit 1 – EEWE: EEPROM Write Enable The EEPROM Write Enable Signal EEWE is the write strobe to the EEPROM. When address and data are correctly set up, the EEWE bit must be written to one to write the value into the EEPROM. The EEMWE bit must be written to one before a logical one is written to EEWE, otherwise no EEPROM write takes place. The following procedure should be followed when writing the EEPROM (the order of steps 3 and 4 is not essential): 1. Wait until EEWE becomes zero. 2. Wait until SPMEN in SPMCR becomes zero. 3. Write new EEPROM address to EEAR (optional). 4. Write new EEPROM data to EEDR (optional). 5. Write a logical one to the EEMWE bit while writing a zero to EEWE in EECR. 6. Within four clock cycles after setting EEMWE, write a logical one to EEWE. The EEPROM can not be programmed during a CPU write to the Flash memory. The software must check that the Flash programming is completed before initiating a new EEPROM write. Step 2 is only relevant if the software contains a Boot Loader allowing the CPU to program the Flash. If the Flash is never being updated by the CPU, step 2 can be omitted. See “Boot Loader Support – Read-While-Write Self-Programming” on page 164 for details about boot programming. 19 2512G–AVR–03/05 4.6. MÉMOIRE PROGRAMMABLE (EEPROM) 127 Caution: An interrupt between step 5 and step 6 will make the write cycle fail, since the EEPROM Master Write Enable will time-out. If an interrupt routine accessing the EEPROM is interrupting another EEPROM access, the EEAR or EEDR Register will be modified, causing the interrupted EEPROM access to fail. It is recommended to have the Global Interrupt Flag cleared during all the steps to avoid these problems. When the write access time has elapsed, the EEWE bit is cleared by hardware. The user software can poll this bit and wait for a zero before writing the next byte. When EEWE has been set, the CPU is halted for two cycles before the next instruction is executed. • Bit 0 – EERE: EEPROM Read Enable The EEPROM Read Enable Signal EERE is the read strobe to the EEPROM. When the correct address is set up in the EEAR Register, the EERE bit must be written to a logic one to trigger the EEPROM read. The EEPROM read access takes one instruction, and the requested data is available immediately. When the EEPROM is read, the CPU is halted for four cycles before the next instruction is executed. The user should poll the EEWE bit before starting the read operation. If a write operation is in progress, it is neither possible to read the EEPROM, nor to change the EEAR Register. The calibrated Oscillator is used to time the EEPROM accesses. Table 1 lists the typical programming time for EEPROM access from the CPU. Table 1. EEPROM Programming Time Symbol EEPROM Write (from CPU) Note: Number of Calibrated RC Oscillator Cycles(1) Typ Programming Time 8448 8.5 ms 1. Uses 1 MHz clock, independent of CKSEL Fuse settings. The following code examples show one assembly and one C function for writing to the EEPROM. The examples assume that interrupts are controlled (e.g., by disabling interrupts globally) so that no interrupts will occur during execution of these functions. The examples also assume that no Flash Boot Loader is present in the software. If such code is present, the EEPROM write function must also wait for any ongoing SPM command to finish. 20 ATmega8515(L) 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 128 ATmega8515(L) Assembly Code Example EEPROM_write: ; Wait for completion of previous write sbic EECR,EEWE rjmp EEPROM_write ; Set up address (r18:r17) in address register out EEARH, r18 out EEARL, r17 ; Write data (r16) to data register out EEDR,r16 ; Write logical one to EEMWE sbi EECR,EEMWE ; Start eeprom write by setting EEWE sbi EECR,EEWE ret C Code Example void EEPROM_write(unsigned int uiAddress, unsigned char ucData) { /* Wait for completion of previous write */ while(EECR & (1<<EEWE)) ; /* Set up address and data registers */ EEAR = uiAddress; EEDR = ucData; /* Write logical one to EEMWE */ EECR |= (1<<EEMWE); /* Start eeprom write by setting EEWE */ EECR |= (1<<EEWE); } 21 2512G–AVR–03/05 4.6. MÉMOIRE PROGRAMMABLE (EEPROM) 129 The next code examples show assembly and C functions for reading the EEPROM. The examples assume that interrupts are controlled so that no interrupts will occur during execution of these functions. Assembly Code Example EEPROM_read: ; Wait for completion of previous write sbic EECR,EEWE rjmp EEPROM_read ; Set up address (r18:r17) in address register out EEARH, r18 out EEARL, r17 ; Start eeprom read by writing EERE sbi EECR,EERE ; Read data from data register in r16,EEDR ret C Code Example unsigned char EEPROM_read(unsigned int uiAddress) { /* Wait for completion of previous write */ while(EECR & (1<<EEWE)) ; /* Set up address register */ EEAR = uiAddress; /* Start eeprom read by writing EERE */ EECR |= (1<<EERE); /* Return data from data register */ return EEDR; } EEPROM Write During Powerdown Sleep Mode 22 When entering Power-down Sleep mode while an EEPROM write operation is active, the EEPROM write operation will continue, and will complete before the Write Access time has passed. However, when the write operation is completed, the crystal Oscillator continues running, and as a consequence, the device does not enter Power-down entirely. It is therefore recommended to verify that the EEPROM write operation is completed before entering Power-down. ATmega8515(L) 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 130 4.7 Vecteurs d’interruptions ATmega8515(L) Interrupts Interrupt Vectors in ATmega8515 This section describes the specifics of the interrupt handling as performed in ATmega8515. For a general explanation of the AVR interrupt handling, refer to “Reset and Interrupt Handling” on page 12. Table 22. Reset and Interrupt Vectors Vector No. 1 Program Address(2) $000 (1) Source Interrupt Definition RESET External Pin, Power-on Reset, Brown-out Reset and Watchdog Reset 2 $001 INT0 External Interrupt Request 0 3 $002 INT1 External Interrupt Request 1 4 $003 TIMER1 CAPT Timer/Counter1 Capture Event 5 $004 TIMER1 COMPA Timer/Counter1 Compare Match A 6 $005 TIMER1 COMPB Timer/Counter1 Compare Match B 7 $006 TIMER1 OVF Timer/Counter1 Overflow 8 $007 TIMER0 OVF Timer/Counter0 Overflow 9 $008 SPI, STC Serial Transfer Complete 10 $009 USART, RXC USART, Rx Complete 11 $00A USART, UDRE USART Data Register Empty 12 $00B USART, TXC USART, Tx Complete 13 $00C ANA_COMP Analog Comparator 14 $00D INT2 External Interrupt Request 2 15 $00E TIMER0 COMP Timer/Counter0 Compare Match 16 $00F EE_RDY EEPROM Ready 17 $010 SPM_RDY Store Program memory Ready Notes: 1. When the BOOTRST Fuse is programmed, the device will jump to the Boot Loader address at reset, see “Boot Loader Support – Read-While-Write Self-Programming” on page 164. 2. When the IVSEL bit in GICR is set, Interrupt Vectors will be moved to the start of the Boot Flash section. The address of each Interrupt Vector will then be the address in this table added to the start address of the Boot Flash section. Table 23 shows Reset and Interrupt Vectors placement for the various combinations of BOOTRST and IVSEL settings. If the program never enables an interrupt source, the Interrupt Vectors are not used, and regular program code can be placed at these locations. This is also the case if the Reset Vector is in the Application section while the Interrupt Vectors are in the Boot section or vice versa. 53 2512G–AVR–03/05 4.8. PORTS D’ENTRÉES/SORTIES 131 4.8 Ports d’entrées/sorties ATmega8515(L) Ports as General Digital I/O The ports are bi-directional I/O ports with optional internal pull-ups. Figure 30 shows a functional description of one I/O-port pin, here generically called Pxn. Figure 30. General Digital I/O(1) PUD Q D DDxn Q CLR RESET WDx Q Pxn D PORTxn Q CLR WPx DATA BUS RDx RESET RRx SLEEP SYNCHRONIZER D Q D RPx Q PINxn L Q Q clk I/O PUD: SLEEP: clkI/O: Note: Configuring the Pin PULLUP DISABLE SLEEP CONTROL I/O CLOCK WDx: RDx: WPx: RRx: RPx: WRITE DDRx READ DDRx WRITE PORTx READ PORTx REGISTER READ PORTx PIN 1. WPx, WDx, RRx, RPx, and RDx are common to all pins within the same port. clkI/O, SLEEP, and PUD are common to all ports. Each port pin consists of three register bits: DDxn, PORTxn, and PINxn. As shown in “Register Description for I/O Ports” on page 74, the DDxn bits are accessed at the DDRx I/O address, the PORTxn bits at the PORTx I/O address, and the PINxn bits at the PINx I/O address. The DDxn bit in the DDRx Register selects the direction of this pin. If DDxn is written logic one, Pxn is configured as an output pin. If DDxn is written logic zero, Pxn is configured as an input pin. If PORTxn is written a logic one when the pin is configured as an input pin, the pull-up resistor is activated. To switch the pull-up resistor off, PORTxn has to be written a logic zero or the pin has to be configured as an output pin. The port pins are tri-stated when a reset condition becomes active, even if no clocks are running. If PORTxn is written a logic one when the pin is configured as an output pin, the port pin is driven high (one). If PORTxn is written a logic zero when the pin is configured as an output pin, the port pin is driven low (zero). When switching between tri-state ({DDxn, PORTxn} = 0b00) and output high ({DDxn, PORTxn} = 0b11), an intermediate state with either pull-up enabled ({DDxn, PORTxn} = 0b01) or output low ({DDxn, PORTxn} = 0b10) must occur. Normally, the pull-up 59 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 132 enabled state is fully acceptable, as a high-impedant environment will not notice the difference between a strong high driver and a pull-up. If this is not the case, the PUD bit in the SFIOR Register can be set to disable all pull-ups in all ports. Switching between input with pull-up and output low generates the same problem. The user must use either the tri-state ({DDxn, PORTxn} = 0b00) or the output high state ({DDxn, PORTxn} = 0b11) as an intermediate step. Table 24 summarizes the control signals for the pin value. Table 24. Port Pin Configurations Reading the Pin Value DDxn PORTxn PUD (in SFIOR) I/O Pull-up 0 0 X Input No Tri-state (Hi-Z) 0 1 0 Input Yes Pxn will source current if ext. pulled low. 0 1 1 Input No Tri-state (Hi-Z) 1 0 X Output No Output Low (Sink) 1 1 X Output No Output High (Source) Comment Independent of the setting of Data Direction bit DDxn, the port pin can be read through the PINxn Register bit. As shown in Figure 30, the PINxn Register bit and the preceding latch constitute a synchronizer. This is needed to avoid metastability if the physical pin changes value near the edge of the internal clock, but it also introduces a delay. Figure 31 shows a timing diagram of the synchronization when reading an externally applied pin value. The maximum and minimum propagation delays are denoted tpd,max and tpd,min respectively. Figure 31. Synchronization when Reading an Externally Applied Pin Value SYSTEM CLK INSTRUCTIONS XXX XXX in r17, PINx SYNC LATCH PINxn r17 0x00 0xFF t pd, max t pd, min Consider the clock period starting shortly after the first falling edge of the system clock. The latch is closed when the clock is low, and goes transparent when the clock is high, as indicated by the shaded region of the “SYNC LATCH” signal. The signal value is latched when the system clock goes low. It is clocked into the PINxn Register at the succeeding positive clock edge. As indicated by the two arrows tpd,max and tpd,min, a single 60 ATmega8515(L) 2512G–AVR–03/05 4.8. PORTS D’ENTRÉES/SORTIES 133 ATmega8515(L) signal transition on the pin will be delayed between ½ and 1½ syst em clock period depending upon the time of assertion. When reading back a software assigned pin value, a nop instruction must be inserted as indicated in Figure 32. The out instruction sets the “SYNC LATCH” signal at the positive edge of the clock. In this case, the delay tpd through the synchronizer is one system clock period. Figure 32. Synchronization when Reading a Software Assigned Pin Value SYSTEM CLK r16 INSTRUCTIONS 0xFF out PORTx, r16 nop in r17, PINx SYNC LATCH PINxn r17 0x00 0xFF t pd 61 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 134 The following code example shows how to set port B pins 0 and 1 high, 2 and 3 low, and define the port pins from 4 to 7 as input with pull-ups assigned to port pins 6 and 7. The resulting pin values are read back again, but as previously discussed, a nop instruction is included to be able to read back the value recently assigned to some of the pins. Assembly Code Example(1) ... ; Define pull-ups and set outputs high ; Define directions for port pins ldi r16,(1<<PB7)|(1<<PB6)|(1<<PB1)|(1<<PB0) ldi r17,(1<<DDB3)|(1<<DDB2)|(1<<DDB1)|(1<<DDB0) out PORTB,r16 out DDRB,r17 ; Insert nop for synchronization nop ; Read port pins in r16,PINB ... C Code Example unsigned char i; ... /* Define pull-ups and set outputs high */ /* Define directions for port pins */ PORTB = (1<<PB7)|(1<<PB6)|(1<<PB1)|(1<<PB0); DDRB = (1<<DDB3)|(1<<DDB2)|(1<<DDB1)|(1<<DDB0); /* Insert nop for synchronization*/ _NOP(); /* Read port pins */ i = PINB; ... Note: Digital Input Enable and Sleep Modes 1. For the assembly program, two temporary registers are used to minimize the time from pull-ups are set on pins 0, 1, 6, and 7, until the direction bits are correctly set, defining bit 2 and 3 as low and redefining bits 0 and 1 as strong high drivers. As shown in Figure 30, the digital input signal can be clamped to ground at the input of the Schmitt Trigger. The signal denoted SLEEP in the figure, is set by the MCU Sleep Controller in Power-down mode and Standby mode to avoid high power consumption if some input signals are left floating, or have an analog signal level close to VCC/2. SLEEP is overridden for port pins enabled as External Interrupt pins. If the External Interrupt Request is not enabled, SLEEP is active also for these pins. SLEEP is also overridden by various other alternate functions as described in “Alternate Port Functions” on page 63. If a logic high level (“one”) is present on an Asynchronous External Interrupt pin configured as “Interrupt on Rising Edge, Falling Edge, or Any Logic Change on Pin” while the external interrupt is not enabled, the corresponding External Interrupt Flag will be set when resuming from the above mentioned sleep modes, as the clamping in these sleep modes produces the requested logic change. 62 ATmega8515(L) 2512G–AVR–03/05 4.9. INTERRUPTIONS EXTERNES 135 4.9 Interruptions externes External Interrupts The External Interrupts are triggered by the INT0, INT1, and INT2 pins. Observe that, if enabled, the interrupts will trigger even if the INT0..2 pins are configured as outputs. This feature provides a way of generating a software interrupt. The External Interrupts can be triggered by a falling or rising edge or a low level (INT2 is only an edge triggered interrupt). This is set up as indicated in the specification for the MCU Control Register – MCUCR and Extended MCU Control Register – EMCUCR. When the External Interrupt is enabled and is configured as level triggered (only INT0/INT1), the interrupt will trigger as long as the pin is held low. Note that recognition of falling or rising edge interrupts on INT0 and INT1 requires the presence of an I/O clock, described in “Clock Systems and their Distribution” on page 33. Low level interrupts on INT0/INT1 and the edge interrupt on INT2 are detected asynchronously. This implies that these interrupts can be used for waking the part also from sleep modes other than Idle mode. The I/O clock is halted in all sleep modes except Idle mode. Note that if a level triggered interrupt is used for wake-up from Power-down mode, the changed level must be held for some time to wake up the MCU. This makes the MCU less sensitive to noise. The changed level is sampled twice by the Watchdog Oscillator clock. The period of the Watchdog Oscillator is 1 µs (nominal) at 5.0V and 25GC. The frequency of the Watchdog Oscillator is voltage dependent as shown in “Electrical Characteristics” on page 195. The MCU will wake up if the input has the required level during this sampling or if it is held until the end of the start-up time. The start-up time is defined by the SUT Fuses as described in “System Clock and Clock Options” on page 33. If the level is sampled twice by the Watchdog Oscillator clock but disappears before the end of the start-up time, the MCU will still wake up, but no interrupt will be generated. The required level must be held long enough for the MCU to complete the wake up to trigger the level interrupt. MCU Control Register – MCUCR The MCU Control Register contains control bits for interrupt sense control and general MCU functions. Bit 7 6 5 4 3 2 1 0 SRE SRW10 SE SM1 ISC11 ISC10 ISC01 ISC00 Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 MCUCR • Bit 3, 2 – ISC11, ISC10: Interrupt Sense Control 1 Bit 1 and Bit 0 The External Interrupt 1 is activated by the external pin INT1 if the SREG I-bit and the corresponding interrupt mask in the GICR are set. The level and edges on the external INT1 pin that activate the interrupt are defined in Table 40. The value on the INT1 pin is sampled before detecting edges. If edge or toggle interrupt is selected, pulses that last longer than one clock period will generate an interrupt. Shorter pulses are not guaranteed to generate an interrupt. If low level interrupt is selected, the low level must be held until the completion of the currently executing instruction to generate an interrupt. Table 40. Interrupt 1 Sense Control ISC11 ISC10 0 0 Description The low level of INT1 generates an interrupt request. 0 1 Any logical change on INT1 generates an interrupt request. 1 0 The falling edge of INT1 generates an interrupt request. 1 1 The rising edge of INT1 generates an interrupt request. • Bit 1, 0 – ISC01, ISC00: Interrupt Sense Control 0 Bit 1 and Bit 0 76 ATmega8515(L) 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 136 ATmega8515(L) The External Interrupt 0 is activated by the external pin INT0 if the SREG I-flag and the corresponding interrupt mask are set. The level and edges on the external INT0 pin that activate the interrupt are defined in Table 41. The value on the INT0 pin is sampled before detecting edges. If edge or toggle interrupt is selected, pulses that last longer than one clock period will generate an interrupt. Shorter pulses are not guaranteed to generate an interrupt. If low level interrupt is selected, the low level must be held until the completion of the currently executing instruction to generate an interrupt. Table 41. Interrupt 0 Sense Control Extended MCU Control Register – EMCUCR ISC01 ISC00 0 0 Description The low level of INT0 generates an interrupt request. 0 1 Any logical change on INT0 generates an interrupt request. 1 0 The falling edge of INT0 generates an interrupt request. 1 1 The rising edge of INT0 generates an interrupt request. Bit 7 6 5 4 3 2 1 0 SM0 SRL2 SRL1 SRL0 SRW01 SRW00 SRW11 ISC2 Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 EMCUCR • Bit 0 – ISC2: Interrupt Sense Control 2 The Asynchronous External Interrupt 2 is activated by the external pin INT2 if the SREG I-bit and the corresponding interrupt mask in GICR are set. If ISC2 is written to zero, a falling edge on INT2 activates the interrupt. If ISC2 is written to one, a rising edge on INT2 activates the interrupt. Edges on INT2 are registered asynchronously. Pulses on INT2 wider than the minimum pulse width given in Table 42 will generate an interrupt. Shorter pulses are not guaranteed to generate an interrupt. When changing the ISC2 bit, an interrupt can occur. Therefore, it is recommended to first disable INT2 by clearing its Interrupt Enable bit in the GICR Register. Then, the ISC2 bit can be changed. Finally, the INT2 Interrupt Flag should be cleared by writing a logical one to its Interrupt Flag bit (INTF2) in the GIFR Register before the interrupt is re-enabled. Table 42. Asynchronous External Interrupt Characteristics Symbol tINT General Interrupt Control Register – GICR Bit Parameter Condition Min Typ Minimum pulse width for asynchronous external interrupt Max 50 Units ns 7 6 5 4 3 2 1 0 INT1 INT0 INT2 – – – IVSEL IVCE Read/Write R/W R/W R/W R R R R/W R/W Initial Value 0 0 0 0 0 0 0 0 GICR • Bit 7 – INT1: External Interrupt Request 1 Enable When the INT1 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), the external pin interrupt is enabled. The Interrupt Sense Control1 bits 1/0 (ISC11 and ISC10) in the MCU General Control Register (MCUCR) define whether the External Interrupt is activated on rising and/or falling edge of the INT1 pin or level sensed. Activity on the pin will cause an interrupt request even if INT1 is configured as an output. The 77 2512G–AVR–03/05 4.10. COMPTEUR À 8 BITS AVEC PWM/CTC (TIMER 0) 137 4.10 Compteur à 8 bits avec PWM/CTC (Timer 0) ATmega8515(L) 8-bit Timer/Counter0 with PWM Timer/Counter0 is a general purpose, single channel, 8-bit Timer/Counter module. The main features are: • Single Channel Counter • Clear Timer on Compare Match (Auto Reload) • Glitch-free, Phase Correct Pulse Width Modulator (PWM) • Frequency Generator • External Event Counter • 10-bit Clock Prescaler • Overflow and Compare Match Interrupt Sources (TOV0 and OCF0) Overview A simplified block diagram of the 8-bit Timer/Counter is shown in Figure 34. For the actual placement of I/O pins, refer to “Pinout ATmega8515” on page 2. CPU accessible I/O Registers, including I/O bits and I/O pins, are shown in bold. The device-specific I/O Register and bit locations are listed in the “8-bit Timer/Counter Register Description” on page 90. Figure 34. 8-bit Timer/Counter Block Diagram TCCRn count clear direction TOVn (Int.Req.) Control Logic clk Tn Clock Select Edge Detector DATA BUS BOTTOM Tn TOP ( From Prescaler ) Timer/Counter TCNTn = =0 = 0xFF OCn (Int.Req.) Waveform Generation OCn OCRn Registers The Timer/Counter (TCNT0) and Output Compare Register (OCR0) are 8-bit registers. Interrupt request (abbreviated to Int.Req. in the figure) signals are all visible in the Timer Interrupt Flag Register (TIFR). All interrupts are individually masked with the Timer Interrupt Mask Register (TIMSK). TIFR and TIMSK are not shown in the figure since these registers are shared by other timer units. The Timer/Counter can be clocked internally, via the prescaler, or by an external clock source on the T0 pin. The Clock Select logic block controls which clock source and edge the Timer/Counter uses to increment (or decrement) its value. The Timer/Counter is 79 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 138 inactive when no clock source is selected. The output from the clock select logic is referred to as the timer clock (clkT0). The double buffered Output Compare Register (OCR0) is compared with the Timer/Counter value at all times. The result of the compare can be used by the Waveform Generator to generate a PWM or variable frequency output on the Output Compare Pin (OC0). See “Output Compare Unit” on page 81. for details. The Compare Match event will also set the Compare Flag (OCF0) which can be used to generate an output compare interrupt request. Definitions Many register and bit references in this document are written in general form. A lower case “n” replaces the Timer/Counter number, in this case 0. However, when using the register or bit defines in a program, the precise form must be used, i.e., TCNT0 for accessing Timer/Counter0 counter value and so on. The definitions in Table 43 are also used extensively throughout the document. Table 43. Definitions BOTTOM The counter reaches the BOTTOM when it becomes 0x00. MAX The counter reaches its MAXimum when it becomes 0xFF (decimal 255). TOP The counter reaches the TOP when it becomes equal to the highest value in the count sequence. The TOP value can be assigned to be the fixed value 0xFF (MAX) or the value stored in the OCR0 Register. The assignment is dependent on the mode of operation. Timer/Counter Clock Sources The Timer/Counter can be clocked by an internal or an external clock source. The clock source is selected by the clock select logic which is controlled by the Clock Select (CS02:0) bits located in the Timer/Counter Control Register (TCCR0). For details on clock sources and prescaler, see “Timer/Counter0 and Timer/Counter1 Prescalers” on page 94. Counter Unit The main part of the 8-bit Timer/Counter is the programmable bi-directional counter unit. Figure 35 shows a block diagram of the counter and its surroundings. Figure 35. Counter Unit Block Diagram TOVn (Int.Req.) DATA BUS Clock Select count TCNTn clear Control Logic clkTn Edge Detector Tn direction ( From Prescaler ) bottom top Signal description (internal signals): 80 count Increment or decrement TCNT0 by 1. direction Select between increment and decrement. clear Clear TCNT0 (set all bits to zero). ATmega8515(L) 2512G–AVR–03/05 4.10. COMPTEUR À 8 BITS AVEC PWM/CTC (TIMER 0) Modes of Operation 139 The mode of operation, i.e., the behavior of the Timer/Counter and the output compare pins, is defined by the combination of the Waveform Generation mode (WGM01:0) and Compare Output mode (COM01:0) bits. The Compare Output mode bits do not affect the counting sequence, while the Waveform Generation mode bits do. The COM01:0 bits control whether the PWM output generated should be inverted or not (inverted or non-inverted PWM). For non-PWM modes the COM01:0 bits control whether the output should be set, cleared, or toggled at a Compare Match (See “Compare Match Output Unit” on page 83.). For detailed timing information refer to Figure 41, Figure 42, Figure 43, and Figure 44 in “Timer/Counter Timing Diagrams” on page 88. Normal Mode The simplest mode of operation is the Normal mode (WGM01:0 = 0). In this mode the counting direction is always up (incrementing), and no counter clear is performed. The counter simply overruns when it passes its maximum 8-bit value (TOP = 0xFF) and then restarts from the bottom (0x00). In normal operation the Timer/Counter Overflow Flag (TOV0) will be set in the same timer clock cycle as the TCNT0 becomes zero. The TOV0 Flag in this case behaves like a ninth bit, except that it is only set, not cleared. However, combined with the timer overflow interrupt that automatically clears the TOV0 Flag, the timer resolution can be increased by software. There are no special cases to consider in the Normal mode, a new counter value can be written anytime. The output compare unit can be used to generate interrupts at some given time. Using the output compare to generate waveforms in Normal mode is not recommended, since this will occupy too much of the CPU time. Clear Timer on Compare Match (CTC) Mode In Clear Timer on Compare or CTC mode (WGM01:0 = 2), the OCR0 Register is used to manipulate the counter resolution. In CTC mode the counter is cleared to zero when the counter value (TCNT0) matches the OCR0. The OCR0 defines the top value for the counter, hence also its resolution. This mode allows greater control of the Compare Match output frequency. It also simplifies the operation of counting external events. The timing diagram for the CTC mode is shown in Figure 38. The counter value (TCNT0) increases until a Compare Match occurs between TCNT0 and OCR0, and then counter (TCNT0) is cleared. Figure 38. CTC Mode, Timing Diagram OCn Interrupt Flag Set TCNTn OCn (Toggle) Period (COMn1:0 = 1) 1 2 3 4 An interrupt can be generated each time the counter value reaches the TOP value by using the OCF0 Flag. If the interrupt is enabled, the interrupt handler routine can be used for updating the TOP value. However, changing TOP to a value close to BOTTOM 84 ATmega8515(L) 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 140 ATmega8515(L) when the counter is running with none or a low prescaler value must be done with care since the CTC mode does not have the double buffering feature. If the new value written to OCR0 is lower than the current value of TCNT0, the counter will miss the Compare Match. The counter will then have to count to its maximum value (0xFF) and wrap around starting at 0x00 before the Compare Match can occur. For generating a waveform output in CTC mode, the OC0 output can be set to toggle its logical level on each Compare Match by setting the Compare Output mode bits to toggle mode (COM01:0 = 1). The OC0 value will not be visible on the port pin unless the data direction for the pin is set to output. The waveform generated will have a maximum frequency of fOC0 = fclk_I/O/2 when OCR0 is set to zero (0x00). The waveform frequency is defined by the following equation: f clk_I/O f OCn = ---------------------------------------------2 b N b 1 + OCRn The “N” variable represents the prescale factor (1, 8, 64, 256, or 1024). As for the Normal mode of operation, the TOV0 Flag is set in the same timer clock cycle that the counter counts from MAX to 0x00. Fast PWM Mode The fast Pulse Width Modulation or fast PWM mode (WGM01:0 = 3) provides a high frequency PWM waveform generation option. The fast PWM differs from the other PWM option by its single-slope operation. The counter counts from BOTTOM to MAX then restarts from BOTTOM. In non-inverting Compare Output mode, the Output Compare (OC0) is cleared on the Compare Match between TCNT0 and OCR0, and set at BOTTOM. In inverting Compare Output mode, the output is set on Compare Match and cleared at BOTTOM. Due to the single-slope operation, the operating frequency of the fast PWM mode can be twice as high as the phase correct PWM mode that use dualslope operation. This high frequency makes the fast PWM mode well suited for power regulation, rectification, and DAC applications. High frequency allows physically small sized external components (coils, capacitors), and therefore reduces total system cost. In fast PWM mode, the counter is incremented until the counter value matches the MAX value. The counter is then cleared at the following timer clock cycle. The timing diagram for the fast PWM mode is shown in Figure 39. The TCNT0 value is in the timing diagram shown as a histogram for illustrating the single-slope operation. The diagram includes non-inverted and inverted PWM outputs. The small horizontal line marks on the TCNT0 slopes represent Compare Matches between OCR0 and TCNT0. 85 2512G–AVR–03/05 4.10. COMPTEUR À 8 BITS AVEC PWM/CTC (TIMER 0) 141 Figure 39. Fast PWM Mode, Timing Diagram OCRn Interrupt Flag Set OCRn Update and TOVn Interrupt Flag Set TCNTn OCn (COMn1:0 = 2) OCn (COMn1:0 = 3) Period 1 2 3 4 5 6 7 The Timer/Counter Overflow Flag (TOV0) is set each time the counter reaches MAX. If the interrupt is enabled, the interrupt handler routine can be used for updating the compare value. In fast PWM mode, the compare unit allows generation of PWM waveforms on the OC0 pin. Setting the COM01:0 bits to 2 will produce a non-inverted PWM and an inverted PWM output can be generated by setting the COM01:0 to 3 (See Table 46 on page 91). The actual OC0 value will only be visible on the port pin if the data direction for the port pin is set as output. The PWM waveform is generated by setting (or clearing) the OC0 Register at the Compare Match between OCR0 and TCNT0, and clearing (or setting) the OC0 Register at the timer clock cycle the counter is cleared (changes from MAX to BOTTOM). The PWM frequency for the output can be calculated by the following equation: f clk_I/O f OCnPWM = ----------------N b 256 The “N” variable represents the prescale factor (1, 8, 64, 256, or 1024). The extreme values for the OCR0 Register represents special cases when generating a PWM waveform output in the fast PWM mode. If the OCR0 is set equal to BOTTOM, the output will be a narrow spike for each MAX+1 timer clock cycle. Setting the OCR0 equal to MAX will result in a constantly high or low output (depending on the polarity of the output set by the COM01:0 bits). A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by setting OC0 to toggle its logical level on each Compare Match (COM01:0 = 1). The waveform generated will have a maximum frequency of fOC0 = fclk_I/O/2 when OCR0 is set to zero. This feature is similar to the OC0 toggle in CTC mode, except the double buffer feature of the output compare unit is enabled in the fast PWM mode. 86 ATmega8515(L) 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 142 ATmega8515(L) Phase Correct PWM Mode The phase correct PWM mode (WGM01:0 = 1) provides a high resolution phase correct PWM waveform generation option. The phase correct PWM mode is based on a dualslope operation. The counter counts repeatedly from BOTTOM to MAX and then from MAX to BOTTOM. In non-inverting Compare Output mode, the Output Compare (OC0) is cleared on the Compare Match between TCNT0 and OCR0 while upcounting, and set on the Compare Match while downcounting. In inverting Output Compare mode, the operation is inverted. The dual-slope operation has lower maximum operation frequency than single slope operation. However, due to the symmetric feature of the dual-slope PWM modes, these modes are preferred for motor control applications. The PWM resolution for the phase correct PWM mode is fixed to eight bits. In phase correct PWM mode the counter is incremented until the counter value matches MAX. When the counter reaches MAX, it changes the count direction. The TCNT0 value will be equal to MAX for one timer clock cycle. The timing diagram for the phase correct PWM mode is shown on Figure 40. The TCNT0 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. The diagram includes non-inverted and inverted PWM outputs. The small horizontal line marks on the TCNT0 slopes represent Compare Matches between OCR0 and TCNT0. Figure 40. Phase Correct PWM Mode, Timing Diagram OCn Interrupt Flag Set OCRn Update TOVn Interrupt Flag Set TCNTn OCn (COMn1:0 = 2) OCn (COMn1:0 = 3) Period 1 2 3 The Timer/Counter Overflow Flag (TOV0) is set each time the counter reaches BOTTOM. The Interrupt Flag can be used to generate an interrupt each time the counter reaches the BOTTOM value. In phase correct PWM mode, the compare unit allows generation of PWM waveforms on the OC0 pin. Setting the COM01:0 bits to 2 will produce a non-inverted PWM. An inverted PWM output can be generated by setting the COM01:0 to 3 (See Table 47 on page 91). The actual OC0 value will only be visible on the port pin if the data direction for the port pin is set as output. The PWM waveform is generated by clearing (or setting) the OC0 Register at the Compare Match between OCR0 and TCNT0 when the counter increments, and setting (or clearing) the OC0 Register at Compare Match between 87 2512G–AVR–03/05 4.10. COMPTEUR À 8 BITS AVEC PWM/CTC (TIMER 0) 143 OCR0 and TCNT0 when the counter decrements. The PWM frequency for the output when using phase correct PWM can be calculated by the following equation: f clk_I/O f OCnPCPWM = ----------------N b 510 The N variable represents the prescale factor (1, 8, 64, 256, or 1024). The extreme values for the OCR0 Register represent special cases when generating a PWM waveform output in the phase correct PWM mode. If the OCR0 is set equal to BOTTOM, the output will be continuously low and if set equal to MAX the output will be continuously high for non-inverted PWM mode. For inverted PWM the output will have the opposite logic values. At the very start of period 2 in Figure 40 OCn has a transition from high to low even though there is no Compare Match. The point of this transition is to guarantee symmetry around BOTTOM. There are two cases that give a transition without Compare Match: Timer/Counter Timing Diagrams • OCR0 changes its value from MAX, like in Figure 40. When the OCR0 value is MAX the OCn pin value is the same as the result of a down-counting Compare Match. To ensure symmetry around BOTTOM the OCn value at MAX must correspond to the result of an up-counting Compare Match. • The timer starts counting from a higher value than the one in OCR0, and for that reason misses the Compare Match and hence the OCn change that would have happened on the way up. The Timer/Counter is a synchronous design and the timer clock (clkT0) is therefore shown as a clock enable signal in the following figures. The figures include information on when Interrupt Flags are set. Figure 41 contains timing data for basic Timer/Counter operation. The figure shows the count sequence close to the MAX value in all modes other than phase correct PWM mode. Figure 41. Timer/Counter Timing Diagram, no Prescaling clkI/O clkTn (clkI/O /1) TCNTn MAX - 1 MAX BOTTOM BOTTOM + 1 TOVn Figure 42 shows the same timing data, but with the prescaler enabled. 88 ATmega8515(L) 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 144 8-bit Timer/Counter Register Description Timer/Counter Control Register – TCCR0 Bit 7 6 5 4 3 2 1 0 FOC0 WGM00 COM01 COM00 WGM01 CS02 CS01 CS00 Read/Write W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 TCCR0 • Bit 7 – FOC0: Force Output Compare The FOC0 bit is only active when the WGM00 bit specifies a non-PWM mode. However, for ensuring compatibility with future devices, this bit must be set to zero when TCCR0 is written when operating in PWM mode. When writing a logical one to the FOC0 bit, an immediate Compare Match is forced on the waveform generation unit. The OC0 output is changed according to its COM01:0 bits setting. Note that the FOC0 bit is implemented as a strobe. Therefore it is the value present in the COM01:0 bits that determines the effect of the forced compare. A FOC0 strobe will not generate any interrupt, nor will it clear the timer in CTC mode using OCR0 as TOP. The FOC0 bit is always read as zero. • Bit 6, 3 – WGM01:0: Waveform Generation Mode These bits control the counting sequence of the counter, the source for the maximum (TOP) counter value, and what type of waveform generation to be used. Modes of operation supported by the Timer/Counter unit are: Normal mode, Clear Timer on Compare Match (CTC) mode, and two types of Pulse Width Modulation (PWM) modes. See Table 44 and “Modes of Operation” on page 84. Table 44. Waveform Generation Mode Bit Description(1) Mode WGM01 (CTC0) WGM00 (PWM0) 0 0 1 2 3 Note: Timer/Counter Mode of Operation TOP Update of OCR0 at TOV0 Flag Set on 0 Normal 0xFF Immediate MAX 0 1 PWM, Phase Correct 0xFF TOP BOTTOM 1 0 CTC OCR0 Immediate MAX 1 1 Fast PWM 0xFF TOP MAX 1. The CTC0 and PWM0 bit definition names are now obsolete. Use the WGM01:0 definitions. However, the functionality and location of these bits are compatible with previous versions of the timer. • Bit 5:4 – COM01:0: Compare Match Output Mode These bits control the Output Compare pin (OC0) behavior. If one or both of the COM01:0 bits are set, the OC0 output overrides the normal port functionality of the I/O pin it is connected to. However, note that the Data Direction Register (DDR) bit corresponding to the OC0 pin must be set in order to enable the output driver. 90 ATmega8515(L) 2512G–AVR–03/05 4.10. COMPTEUR À 8 BITS AVEC PWM/CTC (TIMER 0) 145 ATmega8515(L) When OC0 is connected to the pin, the function of the COM01:0 bits depends on the WGM01:0 bit setting. Table 45 shows the COM01:0 bit functionality when the WGM01:0 bits are set to a normal or CTC mode (non-PWM). Table 45. Compare Output Mode, non-PWM Mode COM01 COM00 Description 0 0 Normal port operation, OC0 disconnected. 0 1 Toggle OC0 on Compare Match. 1 0 Clear OC0 on Compare Match. 1 1 Set OC0 on Compare Match. Table 46 shows the COM01:0 bit functionality when the WGM01:0 bits are set to fast PWM mode. Table 46. Compare Output Mode, Fast PWM Mode(1) COM01 COM00 Description 0 0 Normal port operation, OC0 disconnected. 0 1 Reserved 1 0 Clear OC0 on Compare Match, set OC0 at TOP. 1 1 Set OC0 on Compare Match, clear OC0 at TOP. Note: 1. A special case occurs when OCR0 equals TOP and COM01 is set. In this case, the Compare Match is ignored, but the set or clear is done at TOP. See “Fast PWM Mode” on page 85 for more details. Table 47 shows the COM01:0 bit functionality when the WGM01:0 bits are set to phase correct PWM mode. Table 47. Compare Output Mode, Phase Correct PWM Mode(1) COM01 COM00 Description 0 0 Normal port operation, OC0 disconnected. 0 1 Reserved 1 0 Clear OC0 on Compare Match when up-counting. Set OC0 on Compare Match when downcounting. 1 1 Set OC0 on Compare Match when up-counting. Clear OC0 on Compare Match when downcounting. Note: 1. A special case occurs when OCR0 equals TOP and COM01 is set. In this case, the Compare Match is ignored, but the set or clear is done at TOP. See “Phase Correct PWM Mode” on page 87 for more details. • Bit 2:0 – CS02:0: Clock Select The three Clock Select bits select the clock source to be used by the Timer/Counter. Table 48. Clock Select Bit Description CS02 CS01 CS00 Description 0 0 0 No clock source (Timer/counter stopped). 0 0 1 clkI/O/(No prescaling) 0 1 0 clkI/O/8 (From prescaler) 91 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 146 Table 48. Clock Select Bit Description CS02 CS01 CS00 0 1 1 Description clkI/O/64 (From prescaler) 1 0 0 clkI/O/256 (From prescaler) 1 0 1 clkI/O/1024 (From prescaler) 1 1 0 External clock source on T0 pin. Clock on falling edge. 1 1 1 External clock source on T0 pin. Clock on rising edge. If external pin modes are used for the Timer/Counter0, transitions on the T0 pin will clock the counter even if the pin is configured as an output. This feature allows software control of the counting. Timer/Counter Register – TCNT0 Bit 7 6 5 4 3 2 1 0 TCNT0[7:0] TCNT0 Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 The Timer/Counter Register gives direct access, both for read and write operations, to the Timer/Counter unit 8-bit counter. Writing to the TCNT0 Register blocks (removes) the Compare Match on the following timer clock. Modifying the counter (TCNT0) while the counter is running, introduces a risk of missing a Compare Match between TCNT0 and the OCR0 Register. Output Compare Register – OCR0 Bit 7 6 5 4 3 2 1 0 OCR0[7:0] OCR0 Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 The Output Compare Register contains an 8-bit value that is continuously compared with the counter value (TCNT0). A match can be used to generate an output compare interrupt, or to generate a waveform output on the OC0 pin. Timer/Counter Interrupt Mask Register – TIMSK Bit 7 6 5 4 3 2 1 0 TOIE1 OCIE1A OCIE1B – TICIE1 – TOIE0 OCIE0 Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 TIMSK • Bit 1 – TOIE0: Timer/Counter0 Overflow Interrupt Enable When the TOIE0 bit is written to one, and the I-bit in the Status Register is set (one), the Timer/Counter0 Overflow interrupt is enabled. The corresponding interrupt is executed if an overflow in Timer/Counter0 occurs, i.e., when the TOV0 bit is set in the Timer/Counter Interrupt Flag Register – TIFR. • Bit 0 – OCIE0: Timer/Counter0 Output Compare Match Interrupt Enable When the OCIE0 bit is written to one, and the I-bit in the Status Register is set (one), the Timer/Counter0 Compare Match interrupt is enabled. The corresponding interrupt is executed if a Compare Match in Timer/Counter0 occurs, i.e., when the OCF0 bit is set in the Timer/Counter Interrupt Flag Register – TIFR. Timer/Counter Interrupt Flag Register – TIFR 92 Bit 7 6 5 4 3 2 1 0 ATmega8515(L) 2512G–AVR–03/05 4.10. COMPTEUR À 8 BITS AVEC PWM/CTC (TIMER 0) 147 ATmega8515(L) TOV1 OCF1A OCF1B – ICF1 – TOV0 OCF0 Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 TIFR • Bit 1 – TOV0: Timer/Counter0 Overflow Flag The bit TOV0 is set (one) when an overflow occurs in Timer/Counter0. TOV0 is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, TOV0 is cleared by writing a logic one to the flag. When the SREG I-bit, TOIE0 (Timer/Counter0 Overflow Interrupt Enable), and TOV0 are set (one), the Timer/Counter0 Overflow interrupt is executed. In phase correct PWM mode, this bit is set when Timer/Counter0 changes counting direction at $00. • Bit 0 – OCF0: Output Compare Flag 0 The OCF0 bit is set (one) when a Compare Match occurs between the Timer/Counter0 and the data in OCR0 – Output Compare Register0. OCF0 is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, OCF0 is cleared by writing a logic one to the flag. When the I-bit in SREG, OCIE0 (Timer/Counter0 Compare Match Interrupt Enable), and OCF0 are set (one), the Timer/Counter0 Compare Match Interrupt is executed. 93 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 148 4.11 Compteur à 16 bits (Timer 1) 16-bit Timer/Counter1 The 16-bit Timer/Counter unit allows accurate program execution timing (event management), wave generation, and signal timing measurement. The main features are: • True 16-bit Design (i.e., allows 16-bit PWM) • Two Independent Output Compare Units • Double Buffered Output Compare Registers • One Input Capture Unit • Input Capture Noise Canceler • Clear Timer on Compare Match (Auto Reload) • Glitch-free, Phase Correct Pulse Width Modulator (PWM) • Variable PWM Period • Frequency Generator • External Event Counter • Four Independent Interrupt Sources (TOV1, OCF1A, OCF1B, and ICF1) Overview Most register and bit references in this section are written in general form. A lower case “n” replaces the Timer/Counter number, and a lower case “x” replaces the Output Compare unit channel. However, when using the register or bit defines in a program, the precise form must be used, i.e., TCNT1 for accessing Timer/Counter1 counter value and so on. A simplified block diagram of the 16-bit Timer/Counter is shown in Figure 47. For the actual placement of I/O pins, refer to “Pin Configurations” on page 2. CPU accessible I/O Registers, including I/O bits and I/O pins, are shown in bold. The device-specific I/O Register and bit location are listed in the “16-bit Timer/Counter Register Description” on page 118. 96 ATmega8515(L) 2512G–AVR–03/05 4.11. COMPTEUR À 16 BITS (TIMER 1) 149 ATmega8515(L) Figure 47. 16-bit Timer/Counter Block Diagram(1) Count Clear Direction TOVn (Int.Req.) Control Logic clkTn Clock Select Edge Detector TOP Tn BOTTOM ( From Prescaler ) Timer/Counter TCNTn = =0 OCnA (Int.Req.) Waveform Generation = OCnA DATA BUS OCRnA OCnB (Int.Req.) Fixed TOP Values Waveform Generation = OCRnB OCnB ( From Analog Comparator Ouput ) ICFn (Int.Req.) Edge Detector ICRn Noise Canceler ICPn TCCRnA Note: Registers TCCRnB 1. Refer to Figure 1 on page 2, Table 29 on page 66, and Table 35 on page 71 for Timer/Counter1 pin placement and description. The Timer/Counter (TCNT1), Output Compare Registers (OCR1A/B), and Input Capture Register (ICR1) are all 16-bit registers. Special procedures must be followed when accessing the 16-bit registers. These procedures are described in the section “Accessing 16-bit Registers” on page 99. The Timer/Counter Control Registers (TCCR1A/B) are 8-bit registers and have no CPU access restrictions. Interrupt requests (abbreviated to Int.Req. in the figure) signals are all visible in the Timer Interrupt Flag Register (TIFR). All interrupts are individually masked with the Timer Interrupt Mask Register (TIMSK). TIFR and TIMSK are not shown in the figure since these registers are shared by other timer units. The Timer/Counter can be clocked internally, via the prescaler, or by an external clock source on the T1 pin. The Clock Select logic block controls which clock source and edge the Timer/Counter uses to increment (or decrement) its value. The Timer/Counter is inactive when no clock source is selected. The output from the clock select logic is referred to as the timer clock (clkT1). The double buffered Output Compare Registers (OCR1A/B) are compared with the Timer/Counter value at all time. The result of the compare can be used by the waveform generator to generate a PWM or variable frequency output on the Output Compare Pin (OC1A/B). See “Output Compare Units” on page 105. The Compare Match event will 97 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 150 also set the Compare Match Flag (OCF1A/B) which can be used to generate an output compare interrupt request. The Input Capture Register can capture the Timer/Counter value at a given external (edge triggered) event on either the Input Capture Pin (ICP1) or on the Analog Comparator pins (See “Analog Comparator” on page 162.) The Input Capture unit includes a digital filtering unit (Noise Canceler) for reducing the chance of capturing noise spikes. The TOP value, or maximum Timer/Counter value, can in some modes of operation be defined by either the OCR1A Register, the ICR1 Register, or by a set of fixed values. When using OCR1A as TOP value in a PWM mode, the OCR1A Register can not be used for generating a PWM output. However, the TOP value will in this case be double buffered allowing the TOP value to be changed in run time. If a fixed TOP value is required, the ICR1 Register can be used as an alternative, freeing the OCR1A to be used as PWM output. Definitions The following definitions are used extensively throughout the document: Table 49. Definitions Compatibility BOTTOM The counter reaches the BOTTOM when it becomes 0x0000. MAX The counter reaches its MAXimum when it becomes 0xFFFF (decimal 65535). TOP The counter reaches the TOP when it becomes equal to the highest value in the count sequence. The TOP value can be assigned to be one of the fixed values: 0x00FF, 0x01FF, or 0x03FF, or to the value stored in the OCR1A or ICR1 Register. The assignment is dependent of the mode of operation. The 16-bit Timer/Counter has been updated and improved from previous versions of the 16-bit AVR Timer/Counter. This 16-bit Timer/Counter is fully compatible with the earlier version regarding: • All 16-bit Timer/Counter related I/O Register address locations, including Timer Interrupt Registers. • Bit locations inside all 16-bit Timer/Counter Registers, including Timer Interrupt Registers. • Interrupt Vectors. The following control bits have changed name, but have same functionality and register location: • PWM10 is changed to WGM10. • PWM11 is changed to WGM11. • CTC1 is changed to WGM12. The following bits are added to the 16-bit Timer/Counter Control Registers: • FOC1A and FOC1B are added to TCCR1A. • WGM13 is added to TCCR1B. The 16-bit Timer/Counter has improvements that will affect the compatibility in some special cases. 98 ATmega8515(L) 2512G–AVR–03/05 4.11. COMPTEUR À 16 BITS (TIMER 1) 151 ATmega8515(L) Accessing 16-bit Registers The TCNT1, OCR1A/B, and ICR1 are 16-bit registers that can be accessed by the AVR CPU via the 8-bit data bus. The 16-bit register must be byte accessed using two read or write operations. Each 16-bit timer has a single 8-bit register for temporary storing of the high byte of the 16-bit access. The same temporary register is shared between all 16-bit registers within each 16-bit timer. Accessing the low byte triggers the 16-bit read or write operation. When the low byte of a 16-bit register is written by the CPU, the high byte stored in the temporary register, and the low byte written are both copied into the 16-bit register in the same clock cycle. When the low byte of a 16-bit register is read by the CPU, the high byte of the 16-bit register is copied into the temporary register in the same clock cycle as the low byte is read. Not all 16-bit accesses uses the temporary register for the high byte. Reading the OCR1A/B 16-bit registers does not involve using the temporary register. To do a 16-bit write, the high byte must be written before the low byte. For a 16-bit read, the low byte must be read before the high byte. The following code examples show how to access the 16-bit timer registers assuming that no interrupts updates the temporary register. The same principle can be used directly for accessing the OCR1A/B and ICR1 Registers. Note that when using “C”, the compiler handles the 16-bit access. Assembly Code Examples(1) ... ; Set TCNT1 to 0x01FF ldi r17,0x01 ldi r16,0xFF out TCNT1H,r17 out TCNT1L,r16 ; Read TCNT1 into r17:r16 in r16,TCNT1L in r17,TCNT1H ... C Code Examples(1) unsigned int i; ... /* Set TCNT1 to 0x01FF */ TCNT1 = 0x1FF; /* Read TCNT1 into i */ i = TCNT1; ... Note: 1. See “About Code Examples” on page 6. The assembly code example returns the TCNT1 value in the r17:r16 register pair. It is important to notice that accessing 16-bit registers are atomic operations. If an interrupt occurs between the two instructions accessing the 16-bit register, and the interrupt code updates the temporary register by accessing the same or any other of the 16-bit timer registers, then the result of the access outside the interrupt will be corrupted. Therefore, when both the main code and the interrupt code update the temporary register, the main code must disable the interrupts during the 16-bit access. 99 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 152 The following code examples show how to do an atomic read of the TCNT1 Register contents. Reading any of the OCR1A/B or ICR1 Registers can be done by using the same principle. Assembly Code Example(1) TIM16_ReadTCNT1: ; Save global interrupt flag in r18,SREG ; Disable interrupts cli ; Read TCNT1 into r17:r16 in r16,TCNT1L in r17,TCNT1H ; Restore global interrupt flag out SREG,r18 ret C Code Example(1) unsigned int TIM16_ReadTCNT1( void ) { unsigned char sreg; unsigned int i; /* Save global interrupt flag */ sreg = SREG; /* Disable interrupts */ _CLI(); /* Read TCNT1 into i */ i = TCNT1; /* Restore global interrupt flag */ SREG = sreg; return i; } Note: 1. See “About Code Examples” on page 6. The assembly code example returns the TCNT1 value in the r17:r16 register pair. 100 ATmega8515(L) 2512G–AVR–03/05 4.11. COMPTEUR À 16 BITS (TIMER 1) 153 ATmega8515(L) The following code examples show how to do an atomic write of the TCNT1 Register contents. Writing any of the OCR1A/B or ICR1 Registers can be done by using the same principle. Assembly Code Example(1) TIM16_WriteTCNT1: ; Save global interrupt flag in r18,SREG ; Disable interrupts cli ; Set TCNT1 to r17:r16 out TCNT1H,r17 out TCNT1L,r16 ; Restore global interrupt flag out SREG,r18 ret C Code Example(1) void TIM16_WriteTCNT1( unsigned int i ) { unsigned char sreg; unsigned int i; /* Save global interrupt flag */ sreg = SREG; /* Disable interrupts */ _CLI(); /* Set TCNT1 to i */ TCNT1 = i; /* Restore global interrupt flag */ SREG = sreg; } Note: 1. See “About Code Examples” on page 6. The assembly code example requires that the r17:r16 register pair contains the value to be written to TCNT1. Reusing the Temporary High Byte Register If writing to more than one 16-bit register where the high byte is the same for all registers written, then the high byte only needs to be written once. However, note that the same rule of atomic operation described previously also applies in this case. 101 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 154 ATmega8515(L) Timer/Counter1 Control Register B – TCCR1B Bit 7 6 5 4 3 2 1 0 ICNC1 ICES1 – WGM13 WGM12 CS12 CS11 CS10 Read/Write R/W R/W R R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 TCCR1B • Bit 7 – ICNC1: Input Capture Noise Canceler Setting this bit (to one) activates the Input Capture Noise Canceler. When the Noise Canceler is activated, the input from the Input Capture Pin (ICP1) is filtered. The filter function requires four successive equal valued samples of the ICP1 pin for changing its output. The Input Capture is therefore delayed by four Oscillator cycles when the noise canceler is enabled. • Bit 6 – ICES1: Input Capture Edge Select This bit selects which edge on the Input Capture Pin (ICP1) that is used to trigger a capture event. When the ICES1 bit is written to zero, a falling (negative) edge is used as trigger, and when the ICES1 bit is written to one, a rising (positive) edge will trigger the capture. When a capture is triggered according to the ICES1 setting, the counter value is copied into the Input Capture Register (ICR1). The event will also set the Input Capture Flag (ICF1), and this can be used to cause an Input Capture Interrupt, if this interrupt is enabled. When the ICR1 is used as TOP value (see description of the WGM13:0 bits located in the TCCR1A and the TCCR1B Register), the ICP1 is disconnected and consequently the Input Capture function is disabled. • Bit 5: Reserved Bit This bit is reserved for future use. For ensuring compatibility with future devices, this bit must be written to zero when TCCR1B is written. • Bit 4:3 – WGM13:2: Waveform Generation Mode See TCCR1A Register description. • Bit 2:0 – CS12:0: Clock Select The three Clock Select bits select the clock source to be used by the Timer/Counter, see Figure 56 and Figure 57. Table 54. Clock Select Bit Description CS12 CS11 CS10 Description 0 0 0 No clock source (Timer/counter stopped). 0 0 1 clkI/O/1 (No prescaling) 0 1 0 clkI/O/8 (From prescaler) 0 1 1 clkI/O/64 (From prescaler) 1 0 0 clkI/O/256 (From prescaler) 1 0 1 clkI/O/1024 (From prescaler) 1 1 0 External clock source on T1 pin. Clock on falling edge. 1 1 1 External clock source on T1 pin. Clock on rising edge. If external pin modes are used for the Timer/Counter1, transitions on the T1 pin will clock the counter even if the pin is configured as an output. This feature allows software control of the counting. 121 2512G–AVR–03/05 4.11. COMPTEUR À 16 BITS (TIMER 1) Timer/Counter1 – TCNT1H and TCNT1L Bit 155 7 6 5 4 3 2 1 0 TCNT1[15:8] TCNT1H TCNT1[7:0] TCNT1L Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 The two Timer/Counter I/O locations (TCNT1H and TCNT1L, combined TCNT1) give direct access, both for read and for write operations, to the Timer/Counter unit 16-bit counter. To ensure that both the high and low bytes are read and written simultaneously when the CPU accesses these registers, the access is performed using an 8-bit temporary High Byte Register (TEMP). This temporary register is shared by all the other 16-bit registers. See “Accessing 16-bit Registers” on page 99. Modifying the counter (TCNT1) while the counter is running introduces a risk of missing a Compare Match between TCNT1 and one of the OCR1x Registers. Writing to the TCNT1 Register blocks (removes) the Compare Match on the following timer clock for all compare units. Output Compare Register 1 A – OCR1AH and OCR1AL Bit 7 6 5 4 3 2 1 0 OCR1A[15:8] OCR1AH OCR1A[7:0] Output Compare Register 1 B – OCR1BH and OCR1BL OCR1AL Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 OCR1B[15:8] OCR1BH OCR1B[7:0] OCR1BL Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 The Output Compare Registers contain a 16-bit value that is continuously compared with the counter value (TCNT1). A match can be used to generate an output compare interrupt, or to generate a waveform output on the OC1x pin. The Output Compare Registers are 16-bit in size. To ensure that both the high and low bytes are written simultaneously when the CPU writes to these registers, the access is performed using an 8-bit temporary High Byte Register (TEMP). This temporary register is shared by all the other 16-bit registers. See “Accessing 16-bit Registers” on page 99. 122 ATmega8515(L) 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 156 ATmega8515(L) Input Capture Register 1 – ICR1H and ICR1L Bit 7 6 5 4 3 2 1 0 ICR1[15:8] ICR1H ICR1[7:0] ICR1L Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 The Input Capture is updated with the counter (TCNT1) value each time an event occurs on the ICP1 pin (or optionally on the Analog Comparator output for Timer/Counter1). The Input Capture can be used for defining the counter TOP value. The Input Capture Register is 16-bit in size. To ensure that both the high and low bytes are read simultaneously when the CPU accesses these registers, the access is performed using an 8-bit temporary High Byte Register (TEMP). This temporary register is shared by all the other 16-bit registers. See “Accessing 16-bit Registers” on page 99. Timer/Counter Interrupt Mask Register – TIMSK(1) Bit 7 6 5 4 3 2 1 0 TOIE1 OCIE1A OCIE1B OCIE2 TICIE1 TOIE2 TOIE0 OCIE0 Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Note: TIMSK 1. This register contains interrupt control bits for several Timer/Counters, but only Timer1 bits are described in this section. The remaining bits are described in their respective timer sections. • Bit 7 – TOIE1: Timer/Counter1, Overflow Interrupt Enable When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally enabled), the Timer/Counter1 overflow interrupt is enabled. The corresponding Interrupt Vector (see “Interrupts” on page 53) is executed when the TOV1 Flag, located in TIFR, is set. • Bit 6 – OCIE1A: Timer/Counter1, Output Compare A Match Interrupt Enable When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally enabled), the Timer/Counter1 Output Compare A Match interrupt is enabled. The corresponding Interrupt Vector (see “Interrupts” on page 53) is executed when the OCF1A Flag, located in TIFR, is set. • Bit 5 – OCIE1B: Timer/Counter1, Output Compare B Match Interrupt Enable When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally enabled), the Timer/Counter1 Output Compare B Match interrupt is enabled. The corresponding Interrupt Vector (see “Interrupts” on page 53) is executed when the OCF1B Flag, located in TIFR, is set. • Bit 3 – TICIE1: Timer/Counter1, Input Capture Interrupt Enable When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally enabled), the Timer/Counter1 Input Capture interrupt is enabled. The corresponding Interrupt Vector (see “Interrupts” on page 53) is executed when the ICF1 Flag, located in TIFR, is set. 123 2512G–AVR–03/05 4.11. COMPTEUR À 16 BITS (TIMER 1) Timer/Counter Interrupt Flag Register – TIFR(1) 157 Bit 7 6 5 4 3 2 1 0 TOV1 OCF1A OC1FB – ICF1 – TOV0 OCF0 Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Note: TIFR 1. This register contains flag bits for several Timer/Counters, but only Timer1 bits are described in this section. The remaining bits are described in their respective timer sections. • Bit 7 – TOV1: Timer/Counter1, Overflow Flag The setting of this flag is dependent of the WGM13:0 bits setting. In Normal and CTC modes, the TOV1 Flag is set when the timer overflows. Refer to Table 53 on page 120 for the TOV1 Flag behavior when using another WGM13:0 bit setting. TOV1 is automatically cleared when the Timer/Counter1 Overflow Interrupt Vector is executed. Alternatively, TOV1 can be cleared by writing a logic one to its bit location. • Bit 6 – OCF1A: Timer/Counter1, Output Compare A Match Flag This flag is set in the timer clock cycle after the counter (TCNT1) value matches the Output Compare Register A (OCR1A). Note that a Forced Output Compare (FOC1A) strobe will not set the OCF1A Flag. OCF1A is automatically cleared when the Output Compare Match A Interrupt Vector is executed. Alternatively, OCF1A can be cleared by writing a logic one to its bit location. • Bit 5 – OCF1B: Timer/Counter1, Output Compare B Match Flag This flag is set in the timer clock cycle after the counter (TCNT1) value matches the Output Compare Register B (OCR1B). Note that a Forced Output Compare (FOC1B) strobe will not set the OCF1B Flag. OCF1B is automatically cleared when the Output Compare Match B Interrupt vector is executed. Alternatively, OCF1B can be cleared by writing a logic one to its bit location. • Bit 3 – ICF1: Timer/Counter1, Input Capture Flag This flag is set when a capture event occurs on the ICP1 pin. When the Input Capture Register (ICR1) is set by the WGM13:0 to be used as the TOP value, the ICF1 Flag is set when the counter reaches the TOP value. ICF1 is automatically cleared when the Input Capture Interrupt Vector is executed. Alternatively, ICF1 can be cleared by writing a logic one to its bit location. 124 ATmega8515(L) 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 158 4.12 Module de communication SPI ATmega8515(L) Serial Peripheral Interface – SPI The Serial Peripheral Interface (SPI) allows high-speed synchronous data transfer between the ATmega8515 and peripheral devices or between several AVR devices. The ATmega8515 SPI includes the following features: • Full Duplex, 3-wire Synchronous Data Transfer • Master or Slave Operation • LSB First or MSB First Data Transfer • Seven Programmable Bit Rates • End of Transmission Interrupt Flag • Write Collision Flag Protection • Wake-up from Idle Mode • Double Speed (CK/2) Master SPI Mode Figure 60. SPI Block Diagram(1) SPI2X SPI2X DIVIDER /2/4/8/16/32/64/128 Note: 1. Refer to Figure 1 on page 2, and Table 29 on page 66 for SPI pin placement. The interconnection between Master and Slave CPUs with SPI is shown in Figure 61. The system consists of two Shift Registers, and a Master clock generator. The SPI Master initiates the communication cycle when pulling low the Slave Select SS pin of the desired Slave. Master and Slave prepare the data to be sent in their respective Shift Registers, and the Master generates the required clock pulses on the SCK line to interchange data. Data is always shifted from Master to Slave on the Master Out – Slave In, MOSI, line, and from Slave to Master on the Master In – Slave Out, MISO, line. After each data packet, the Master will synchronize the Slave by pulling high the Slave Select, SS, line. 125 2512G–AVR–03/05 4.12. MODULE DE COMMUNICATION SPI 159 When configured as a Master, the SPI interface has no automatic control of the SS line. This must be handled by user software before communication can start. When this is done, writing a byte to the SPI Data Register starts the SPI clock generator, and the hardware shifts the 8 bits into the Slave. After shifting one byte, the SPI clock generator stops, setting the end of Transmission Flag (SPIF). If the SPI Interrupt Enable bit (SPIE) in the SPCR Register is set, an interrupt is requested. The Master may continue to shift the next byte by writing it into SPDR, or signal the end of packet by pulling high the Slave Select, SS line. The last incoming byte will be kept in the Buffer Register for later use. When configured as a Slave, the SPI interface will remain sleeping with MISO tri-stated as long as the SS pin is driven high. In this state, software may update the contents of the SPI Data Register, SPDR, but the data will not be shifted out by incoming clock pulses on the SCK pin until the SS pin is driven low. As one byte has been completely shifted, the end of Transmission Flag, SPIF is set. If the SPI Interrupt Enable bit, SPIE, in the SPCR Register is set, an interrupt is requested. The Slave may continue to place new data to be sent into SPDR before reading the incoming data. The last incoming byte will be kept in the Buffer Register for later use. Figure 61. SPI Master-Slave Interconnection MSB MASTER LSB MSB MISO SLAVE LSB MISO 8-BIT SHIFT REGISTER 8-BIT SHIFT REGISTER MOSI MOSI SHIFT ENABLE SPI CLOCK GENERATOR SCK SS VCC SCK SS The system is single buffered in the transmit direction and double buffered in the receive direction. This means that bytes to be transmitted cannot be written to the SPI Data Register before the entire shift cycle is completed. When receiving data, however, a received character must be read from the SPI Data Register before the next character has been completely shifted in. Otherwise, the first byte is lost. In SPI Slave mode, the control logic will sample the incoming signal of the SCK pin. To ensure correct sampling of the clock signal, the frequency of the SPI clock should never exceed fosc/4. When the SPI is enabled, the data direction of the MOSI, MISO, SCK, and SS pins is overridden according to Table 55. For more details on automatic port overrides, refer to “Alternate Port Functions” on page 63. Table 55. SPI Pin Overrides(1) Pin Direction, Master SPI Direction, Slave SPI MOSI User Defined Input MISO Input User Defined SCK User Defined Input SS User Defined Input Note: 126 1. See “Alternate Functions Of Port B” on page 66 for a detailed description of how to define the direction of the user defined SPI pins. ATmega8515(L) 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 160 ATmega8515(L) The following code examples show how to initialize the SPI as a Master and how to perform a simple transmission. DDR_SPI in the examples must be replaced by the actual Data Direction Register controlling the SPI pins. DD_MOSI, DD_MISO and DD_SCK must be replaced by the actual data direction bits for these pins. For example, if MOSI is placed on pin PB5, replace DD_MOSI with DDB5 and DDR_SPI with DDRB. Assembly Code Example(1) SPI_MasterInit: ; Set MOSI and SCK output, all others input ldi r17,(1<<DD_MOSI)|(1<<DD_SCK) out DDR_SPI,r17 ; Enable SPI, Master, set clock rate fck/16 ldi r17,(1<<SPE)|(1<<MSTR)|(1<<SPR0) out SPCR,r17 ret SPI_MasterTransmit: ; Start transmission of data (r16) out SPDR,r16 Wait_Transmit: ; Wait for transmission complete sbis SPSR,SPIF rjmp Wait_Transmit ret C Code Example(1) void SPI_MasterInit(void) { /* Set MOSI and SCK output, all others input */ DDR_SPI = (1<<DD_MOSI)|(1<<DD_SCK); /* Enable SPI, Master, set clock rate fck/16 */ SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0); } void SPI_MasterTransmit(char cData) { /* Start transmission */ SPDR = cData; /* Wait for transmission complete */ while(!(SPSR & (1<<SPIF))) ; } Note: 1. See “About Code Examples” on page 6. 127 2512G–AVR–03/05 4.12. MODULE DE COMMUNICATION SPI 161 The following code examples show how to initialize the SPI as a Slave and how to perform a simple reception. Assembly Code Example(1) SPI_SlaveInit: ; Set MISO output, all others input ldi r17,(1<<DD_MISO) out DDR_SPI,r17 ; Enable SPI ldi r17,(1<<SPE) out SPCR,r17 ret SPI_SlaveReceive: ; Wait for reception complete sbis SPSR,SPIF rjmp SPI_SlaveReceive ; Read received data and return in r16,SPDR ret C Code Example(1) void SPI_SlaveInit(void) { /* Set MISO output, all others input */ DDR_SPI = (1<<DD_MISO); /* Enable SPI */ SPCR = (1<<SPE); } char SPI_SlaveReceive(void) { /* Wait for reception complete */ while(!(SPSR & (1<<SPIF))) ; /* Return data register */ return SPDR; } Note: 128 1. See “About Code Examples” on page 6. ATmega8515(L) 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 162 ATmega8515(L) SS Pin Functionality Slave Mode When the SPI is configured as a Slave, the Slave Select (SS) pin is always input. When SS is held low, the SPI is activated, and MISO becomes an output if configured so by the user. All other pins are inputs. When SS is driven high, all pins are inputs, and the SPI is passive, which means that it will not receive incoming data. Note that the SPI logic will be reset once the SS pin is driven high. The SS pin is useful for packet/byte synchronization to keep the Slave bit counter synchronous with the master clock generator. When the SS pin is driven high, the SPI Slave will immediately reset the send and receive logic, and drop any partially received data in the Shift Register. Master Mode When the SPI is configured as a Master (MSTR in SPCR is set), the user can determine the direction of the SS pin. If SS is configured as an output, the pin is a general output pin which does not affect the SPI system. Typically, the pin will be driving the SS pin of the SPI Slave. If SS is configured as an input, it must be held high to ensure Master SPI operation. If the SS pin is driven low by peripheral circuitry when the SPI is configured as a Master with the SS pin defined as an input, the SPI system interprets this as another Master selecting the SPI as a Slave and starting to send data to it. To avoid bus contention, the SPI system takes the following actions: 1. The MSTR bit in SPCR is cleared and the SPI system becomes a Slave. As a result of the SPI becoming a Slave, the MOSI and SCK pins become inputs. 2. The SPIF Flag in SPSR is set, and if the SPI interrupt is enabled, and the I-bit in SREG is set, the interrupt routine will be executed. Thus, when interrupt-driven SPI transmission is used in Master mode, and there exists a possibility that SS is driven low, the interrupt should always check that the MSTR bit is still set. If the MSTR bit has been cleared by a Slave Select, it must be set by the user to re-enable SPI Master mode. SPI Control Register – SPCR Bit 7 6 5 4 3 2 1 0 SPIE SPE DORD MSTR CPOL CPHA SPR1 SPR0 Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 SPCR • Bit 7 – SPIE: SPI Interrupt Enable This bit causes the SPI interrupt to be executed if SPIF bit in the SPSR Register is set and the if the Global Interrupt Enable bit in SREG is set. • Bit 6 – SPE: SPI Enable When the SPE bit is written to one, the SPI is enabled. This bit must be set to enable any SPI operations. • Bit 5 – DORD: Data Order When the DORD bit is written to one, the LSB of the data word is transmitted first. When the DORD bit is written to zero, the MSB of the data word is transmitted first. • Bit 4 – MSTR: Master/Slave Select This bit selects Master SPI mode when written to one, and Slave SPI mode when written logic zero. If SS is configured as an input and is driven low while MSTR is set, MSTR will 129 2512G–AVR–03/05 4.12. MODULE DE COMMUNICATION SPI 163 be cleared, and SPIF in SPSR will become set. The user will then have to set MSTR to re-enable SPI Master mode. • Bit 3 – CPOL: Clock Polarity When this bit is written to one, SCK is high when idle. When CPOL is written to zero, SCK is low when idle. Refer to Figure 62 and Figure 63 for an example. The CPOL functionality is summarized below: Table 56. CPOL Functionality CPOL Leading Edge Trailing Edge 0 Rising Falling 1 Falling Rising • Bit 2 – CPHA: Clock Phase The settings of the Clock Phase bit (CPHA) determine if data is sampled on the leading (first) or trailing (last) edge of SCK. Refer to Figure 62 and Figure 63 for an example. The CPHA functionality is summarized below: Table 57. CPHA Functionality CPHA Leading Edge Trailing Edge 0 Sample Setup 1 Setup Sample • Bits 1, 0 – SPR1, SPR0: SPI Clock Rate Select 1 and 0 These two bits control the SCK rate of the device configured as a Master. SPR1 and SPR0 have no effect on the Slave. The relationship between SCK and the Oscillator Clock frequency fosc is shown in the following table: Table 58. Relationship Between SCK and the Oscillator Frequency 130 SPI2X SPR1 SPR0 0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 SCK Frequency fosc/4 fosc/16 fosc/64 fosc/128 fosc/2 fosc/8 fosc/32 fosc/64 ATmega8515(L) 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 164 ATmega8515(L) SPI Status Register – SPSR Bit 7 6 5 4 3 2 1 0 SPIF WCOL – – – – – SPI2X Read/Write R R R R R R R R/W Initial Value 0 0 0 0 0 0 0 0 SPSR • Bit 7 – SPIF: SPI Interrupt Flag When a serial transfer is complete, the SPIF Flag is set. An interrupt is generated if SPIE in SPCR is set and global interrupts are enabled. If SS is an input and is driven low when the SPI is in Master mode, this will also set the SPIF Flag. SPIF is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, the SPIF bit is cleared by first reading the SPI Status Register with SPIF set, then accessing the SPI Data Register (SPDR). • Bit 6 – WCOL: Write COLlision Flag The WCOL bit is set if the SPI Data Register (SPDR) is written during a data transfer. The WCOL bit (and the SPIF bit) are cleared by first reading the SPI Status Register with WCOL set, and then accessing the SPI Data Register. • Bit 5..1 – Res: Reserved Bits These bits are reserved bits in the ATmega8515 and will always read as zero. • Bit 0 – SPI2X: Double SPI Speed Bit When this bit is written logic one the SPI speed (SCK Frequency) will be doubled when the SPI is in Master mode (see Table 58). This means that the minimum SCK period will be two CPU clock periods. When the SPI is configured as Slave, the SPI is only guaranteed to work at fosc/4 or lower. The SPI interface on the ATmega8515 is also used for Program memory and EEPROM downloading or uploading. See page 191 for Serial Programming and verification. SPI Data Register – SPDR Bit 7 6 5 4 3 2 1 MSB 0 LSB Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value X X X X X X X X SPDR Undefined The SPI Data Register is a read/write register used for data transfer between the Register File and the SPI Shift Register. Writing to the register initiates data transmission. Reading the register causes the Shift Register Receive buffer to be read. 131 2512G–AVR–03/05 4.12. MODULE DE COMMUNICATION SPI Data Modes 165 There are four combinations of SCK phase and polarity with respect to serial data, which are determined by control bits CPHA and CPOL. The SPI data transfer formats are shown in Figure 62 and Figure 63. Data bits are shifted out and latched in on opposite edges of the SCK signal, ensuring sufficient time for data signals to stabilize. This is clearly seen by summarizing Table 56 and Table 57, as done below: Table 59. CPOL and CPHA Functionality Leading Edge Trailing Edge SPI Mode CPOL=0, CPHA=0 Sample (Rising) Setup (Falling) 0 CPOL=0, CPHA=1 Setup (Rising) Sample (Falling) 1 CPOL=1, CPHA=0 Sample (Falling) Setup (Rising) 2 CPOL=1, CPHA=1 Setup (Falling) Sample (Rising) 3 Figure 62. SPI Transfer Format with CPHA = 0 SCK (CPOL = 0) mode 0 SCK (CPOL = 1) mode 2 SAMPLE I MOSI/MISO CHANGE 0 MOSI PIN CHANGE 0 MISO PIN SS MSB first (DORD = 0) MSB LSB first (DORD = 1) LSB Bit 6 Bit 1 Bit 5 Bit 2 Bit 4 Bit 3 Bit 3 Bit 4 Bit 2 Bit 5 Bit 1 Bit 6 LSB MSB Figure 63. SPI Transfer Format with CPHA = 1 SCK (CPOL = 0) mode 1 SCK (CPOL = 1) mode 3 SAMPLE I MOSI/MISO CHANGE 0 MOSI PIN CHANGE 0 MISO PIN SS MSB first (DORD = 0) LSB first (DORD = 1) 132 MSB LSB Bit 6 Bit 1 Bit 5 Bit 2 Bit 4 Bit 3 Bit 3 Bit 4 Bit 2 Bit 5 Bit 1 Bit 6 LSB MSB ATmega8515(L) 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 166 4.13 Résumé des registres d’entrées/sorties ATmega8515(L) Register Summary Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 $3F ($5F) SREG I T H S V N Z C Page 9 $3E ($5E) SPH SP15 SP14 SP13 SP12 SP11 SP10 SP9 SP8 11 SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 11 56, 77 $3D ($5D) SPL $3C ($5C) Reserved $3B ($5B) GICR INT1 INT0 INT2 - - - IVSEL IVCE $3A ($5A) GIFR INTF1 INTF0 INTF2 - - - - - 78 $39 ($59) TIMSK TOIE1 OCIE1A OCIE1B - TICIE1 - TOIE0 OCIE0 92, 123 92, 124 - $38 ($58) TIFR TOV1 OCF1A OCF1B - ICF1 - TOV0 OCF0 $37 ($57) SPMCR SPMIE RWWSB - RWWSRE BLBSET PGWRT PGERS SPMEN 168 $36 ($56) EMCUCR SM0 SRL2 SRL1 SRL0 SRW01 SRW00 SRW11 ISC2 28,41,77 $35 ($55) MCUCR SRE SRW10 SE SM1 ISC11 ISC10 ISC01 ISC00 28,40,76 $34 ($54) MCUCSR - - SM2 - WDRF BORF EXTRF PORF 40,48 $33 ($53) TCCR0 FOC0 WGM00 COM01 COM00 WGM01 CS02 CS01 CS00 $32 ($52) TCNT0 Timer/Counter0 (8 Bits) $31 ($51) OCR0 $30 ($50) SFIOR - XMBK XMM2 XMM1 90 92 Timer/Counter0 Output Compare Register 92 XMM0 PUD - PSR10 30,65,95 $2F ($4F) TCCR1A COM1A1 COM1A0 COM1B1 COM1B0 FOC1A FOC1B WGM11 WGM10 118 $2E ($4E) TCCR1B ICNC1 ICES1 - WGM13 WGM12 CS12 CS11 CS10 121 $2D ($4D) TCNT1H Timer/Counter1 - Counter Register High Byte 122 $2C ($4C) TCNT1L Timer/Counter1 - Counter Register Low Byte 122 $2B ($4B) OCR1AH Timer/Counter1 - Output Compare Register A High Byte 122 $2A ($4A) OCR1AL Timer/Counter1 - Output Compare Register A Low Byte 122 $29 ($49) OCR1BH Timer/Counter1 - Output Compare Register B High Byte 122 $28 ($48) OCR1BL Timer/Counter1 - Output Compare Register B Low Byte 122 $27 ($47) Reserved - - $26 ($46) Reserved - - $25 ($45) ICR1H Timer/Counter1 - Input Capture Register High Byte 123 $24 ($44) ICR1L Timer/Counter1 - Input Capture Register Low Byte 123 $23 ($43) Reserved - - $22 ($42) Reserved - $21 ($41) WDTCR - - - WDCE WDE WDP2 WDP1 WDP0 50 UBRRH URSEL - - - UCSRC URSEL UMSEL UPM1 UPM0 USBS UCSZ1 UCSZ0 UCPOL 155 $1F ($3F) EEARH - - - - - - - EEAR8 18 $1E ($3E) EEARL EEPROM Address Register Low Byte 18 $1D ($3D) EEDR EEPROM Data Register 19 $20(1) ($40)(1) UBRR[11:8] 157 $1C ($3C) EECR - - - - EERIE EEMWE EEWE EERE $1B ($3B) PORTA PORTA7 PORTA6 PORTA5 PORTA4 PORTA3 PORTA2 PORTA1 PORTA0 74 $1A ($3A) DDRA DDA7 DDA6 DDA5 DDA4 DDA3 DDA2 DDA1 DDA0 74 19 $19 ($39) PINA PINA7 PINA6 PINA5 PINA4 PINA3 PINA2 PINA1 PINA0 74 $18 ($38) PORTB PORTB7 PORTB6 PORTB5 PORTB4 PORTB3 PORTB2 PORTB1 PORTB0 74 74 $17 ($37) DDRB DDB7 DDB6 DDB5 DDB4 DDB3 DDB2 DDB1 DDB0 $16 ($36) PINB PINB7 PINB6 PINB5 PINB4 PINB3 PINB2 PINB1 PINB0 74 $15 ($35) PORTC PORTC7 PORTC6 PORTC5 PORTC4 PORTC3 PORTC2 PORTC1 PORTC0 74 $14 ($34) DDRC DDC7 DDC6 DDC5 DDC4 DDC3 DDC2 DDC1 DDC0 74 $13 ($33) PINC PINC7 PINC6 PINC5 PINC4 PINC3 PINC2 PINC1 PINC0 75 75 $12 ($32) PORTD PORTD7 PORTD6 PORTD5 PORTD4 PORTD3 PORTD2 PORTD1 PORTD0 $11 ($31) DDRD DDD7 DDD6 DDD5 DDD4 DDD3 DDD2 DDD1 DDD0 75 $10 ($30) PIND PIND7 PIND6 PIND5 PIND4 PIND3 PIND2 PIND1 PIND0 75 131 $0F ($2F) SPDR $0E ($2E) SPSR SPIF WCOL - - SPI Data Register - - - SPI2X 131 $0D ($2D) SPCR SPIE SPE DORD MSTR CPOL CPHA SPR1 SPR0 $0C ($2C) UDR USART I/O Data Register 129 153 $0B ($2B) UCSRA RXC TXC UDRE FE DOR PE U2X MPCM 153 $0A ($2A) UCSRB RXCIE TXCIE UDRIE RXEN TXEN UCSZ2 RXB8 TXB8 154 $09 ($29) UBRRL $08 ($28) ACSR ACD ACBG ACO ACI ACIE ACIC ACIS1 ACIS0 162 $07 ($27) PORTE - - - - - PORTE2 PORTE1 PORTE0 75 $06 ($26) DDRE - - - - - DDE2 DDE1 DDE0 75 $05 ($25) PINE - - - - - PINE2 PINE1 PINE0 $04 ($24) OSCCAL Notes: USART Baud Rate Register Low Byte Oscillator Calibration Register 157 75 38 1. Refer to the USART description for details on how to access UBRRH and UCSRC. 2. For compatibility with future devices, reserved bits should be written to zero if accessed. Reserved I/O memory addresses should never be written. 237 2512G–AVR–03/05 4.13. RÉSUMÉ DES REGISTRES D’ENTRÉES/SORTIES 167 3. Some of the Status Flags are cleared by writing a logical one to them. Note that the CBI and SBI instructions will operate on all bits in the I/O Register, writing a one back into any flag read as set, thus clearing the flag. The CBI and SBI instructions work with registers $00 to $1F only. 238 ATmega8515(L) 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 168 4.14 Résumé du jeu d’instructions AVR ATmega8515(L) Instruction Set Summary Mnemonics Operands Description Operation Flags #Clocks ARITHMETIC AND LOGIC INSTRUCTIONS ADD Rd, Rr Add two Registers Rd Rd + Rr Z,C,N,V,H ADC Rd, Rr Add with Carry two Registers Rd Rd + Rr + C Z,C,N,V,H 1 ADIW Rdl,K Add Immediate to Word Rdh:Rdl Rdh:Rdl + K Z,C,N,V,S 2 1 SUB Rd, Rr Subtract two Registers Rd Rd - Rr Z,C,N,V,H 1 SUBI Rd, K Subtract Constant from Register Rd Rd - K Z,C,N,V,H 1 SBC Rd, Rr Subtract with Carry two Registers Rd Rd - Rr - C Z,C,N,V,H 1 SBCI Rd, K Subtract with Carry Constant from Reg. Rd Rd - K - C Z,C,N,V,H 1 SBIW Rdl,K Subtract Immediate from Word Rdh:Rdl Rdh:Rdl - K Z,C,N,V,S 2 AND Rd, Rr Logical AND Registers Rd Rd N Rr Z,N,V 1 ANDI Rd, K Logical AND Register and Constant Rd Rd NK Z,N,V 1 OR Rd, Rr Logical OR Registers Rd Rd v Rr Z,N,V 1 ORI Rd, K Logical OR Register and Constant Rd Rd v K Z,N,V 1 EOR Rd, Rr Exclusive OR Registers Rd Rd V Rr Z,N,V 1 COM Rd One’s Complement Rd $FF Rd Z,C,N,V 1 NEG Rd Two’s Complement Rd $00 Rd Z,C,N,V,H 1 SBR Rd,K Set Bit(s) in Register Rd Rd v K Z,N,V 1 CBR Rd,K Clear Bit(s) in Register Rd Rd N ($FF - K) Z,N,V 1 INC Rd Increment Rd Rd + 1 Z,N,V 1 DEC Rd Decrement Rd Rd 1 Z,N,V 1 TST Rd Test for Zero or Minus Rd Rd N Rd Z,N,V 1 CLR Rd Clear Register Rd Rd V Rd Z,N,V 1 SER Rd Set Register Rd $FF None 1 MUL Rd, Rr Multiply Unsigned R1:R0 Rd x Rr Z,C 2 MULS Rd, Rr Multiply Signed R1:R0 Rd x Rr Z,C 2 MULSU Rd, Rr Multiply Signed with Unsigned R1:R0 Rd x Rr Z,C 2 FMUL Rd, Rr Fractional Multiply Unsigned R1:R0 (Rd x Rr) << Z,C 2 FMULS Rd, Rr Fractional Multiply Signed FMULSU Rd, Rr Fractional Multiply Signed with Unsigned 1 R1:R0 (Rd x Rr) << 1 R1:R0 (Rd x Rr) << 1 Z,C 2 Z,C 2 2 BRANCH INSTRUCTIONS RJMP k IJMP RCALL k Relative Jump PC PC + k + 1 None Indirect Jump to (Z) PC Z None 2 Relative Subroutine Call PC PC + k + 1 None 3 3 ICALL Indirect Call to (Z) PC Z None RET Subroutine Return PC STACK None 4 RETI Interrupt Return PC STACK I 4 CPSE Rd,Rr Compare, Skip if Equal if (Rd = Rr) PC PC + 2 or 3 None CP Rd,Rr Compare Rd Rr Z, N,V,C,H 1/2/3 1 CPC Rd,Rr Compare with Carry Rd Rr C Z, N,V,C,H 1 CPI Rd,K Compare Register with Immediate Rd K Z, N,V,C,H SBRC Rr, b Skip if Bit in Register Cleared if (Rr(b)=0) PC PC + 2 or 3 None 1/2/3 1 SBRS Rr, b Skip if Bit in Register is Set if (Rr(b)=1) PC PC + 2 or 3 None 1/2/3 SBIC P, b Skip if Bit in I/O Register Cleared if (P(b)=0) PC PC + 2 or 3 None 1/2/3 SBIS P, b Skip if Bit in I/O Register is Set if (P(b)=1) PC PC + 2 or 3 None 1/2/3 BRBS s, k Branch if Status Flag Set if (SREG(s) = 1) then PCPC+k + 1 None 1/2 BRBC s, k Branch if Status Flag Cleared if (SREG(s) = 0) then PCPC+k + 1 None 1/2 BREQ k Branch if Equal if (Z = 1) then PC PC + k + 1 None 1/2 BRNE k Branch if Not Equal if (Z = 0) then PC PC + k + 1 None 1/2 BRCS k Branch if Carry Set if (C = 1) then PC PC + k + 1 None 1/2 BRCC k Branch if Carry Cleared if (C = 0) then PC PC + k + 1 None 1/2 BRSH k Branch if Same or Higher if (C = 0) then PC PC + k + 1 None 1/2 BRLO k Branch if Lower if (C = 1) then PC PC + k + 1 None 1/2 BRMI k Branch if Minus if (N = 1) then PC PC + k + 1 None 1/2 BRPL k Branch if Plus if (N = 0) then PC PC + k + 1 None 1/2 BRGE k Branch if Greater or Equal, Signed if (N V V= 0) then PC PC + k + 1 None 1/2 BRLT k Branch if Less Than Zero, Signed if (N V V= 1) then PC PC + k + 1 None 1/2 BRHS k Branch if Half Carry Flag Set if (H = 1) then PC PC + k + 1 None 1/2 BRHC k Branch if Half Carry Flag Cleared if (H = 0) then PC PC + k + 1 None 1/2 BRTS k Branch if T Flag Set if (T = 1) then PC PC + k + 1 None 1/2 BRTC k Branch if T Flag Cleared if (T = 0) then PC PC + k + 1 None 1/2 BRVS k Branch if Overflow Flag is Set if (V = 1) then PC PC + k + 1 None 1/2 BRVC k Branch if Overflow Flag is Cleared if (V = 0) then PC PC + k + 1 None 1/2 BRIE k Branch if Interrupt Enabled if ( I = 1) then PC PC + k + 1 None 1/2 BRID k Branch if Interrupt Disabled if ( I = 0) then PC PC + k + 1 None 1/2 239 2512G–AVR–03/05 4.14. RÉSUMÉ DU JEU D’INSTRUCTIONS AVR Mnemonics Operands 169 Description Operation Flags Rd Rr Rd+1:Rd Rr+1:Rr None 1 None 1 1 #Clocks DATA TRANSFER INSTRUCTIONS MOV Rd, Rr Move Between Registers MOVW Rd, Rr Copy Register Word LDI Rd, K Load Immediate Rd K None LD Rd, X Load Indirect Rd (X) None 2 LD Rd, X+ Load Indirect and Post-Inc. Rd (X), X X + 1 None 2 2 LD Rd, - X Load Indirect and Pre-Dec. X X - 1, Rd (X) None LD Rd, Y Load Indirect Rd (Y) None 2 LD Rd, Y+ Load Indirect and Post-Inc. Rd (Y), Y Y + 1 None 2 2 LD Rd, - Y Load Indirect and Pre-Dec. Y Y - 1, Rd (Y) None LDD Rd,Y+q Load Indirect with Displacement Rd (Y + q) None 2 LD Rd, Z Load Indirect Rd (Z) None 2 LD Rd, Z+ Load Indirect and Post-Inc. Rd (Z), Z Z+1 None 2 LD Rd, -Z Load Indirect and Pre-Dec. Z Z - 1, Rd (Z) None 2 2 LDD Rd, Z+q Load Indirect with Displacement Rd (Z + q) None LDS Rd, k Load Direct from SRAM Rd (k) None 2 ST X, Rr Store Indirect (X) Rr None 2 2 ST X+, Rr Store Indirect and Post-Inc. (X) Rr, X X + 1 None ST - X, Rr Store Indirect and Pre-Dec. X X - 1, (X) Rr None 2 ST Y, Rr Store Indirect (Y) Rr None 2 ST Y+, Rr Store Indirect and Post-Inc. (Y) Rr, Y Y + 1 None 2 ST - Y, Rr Store Indirect and Pre-Dec. Y Y - 1, (Y) Rr None 2 STD Y+q,Rr Store Indirect with Displacement (Y + q) Rr None 2 ST Z, Rr Store Indirect (Z) Rr None 2 ST Z+, Rr Store Indirect and Post-Inc. (Z) Rr, Z Z + 1 None 2 ST -Z, Rr Store Indirect and Pre-Dec. Z Z - 1, (Z) Rr None 2 STD Z+q,Rr Store Indirect with Displacement (Z + q) Rr None 2 STS k, Rr Store Direct to SRAM (k) Rr None 2 Load Program memory R0 (Z) None 3 LPM LPM Rd, Z Load Program memory Rd (Z) None 3 LPM Rd, Z+ Load Program memory and Post-Inc Rd (Z), Z Z+1 None 3 Store Program memory (Z) R1:R0 None - IN Rd, P In Port Rd P None 1 SPM OUT P, Rr Out Port P Rr None 1 PUSH Rr Push Register on Stack STACK Rr None 2 POP Rd Pop Register from Stack Rd STACK None 2 BIT AND BIT-TEST INSTRUCTIONS SBI P,b Set Bit in I/O Register I/O(P,b) 1 None 2 CBI P,b Clear Bit in I/O Register I/O(P,b) 0 None 2 LSL Rd Logical Shift Left Rd(n+1) Rd(n), Rd(0) 0 Z,C,N,V 1 LSR Rd Logical Shift Right Rd(n) Rd(n+1), Rd(7) 0 Z,C,N,V 1 ROL Rd Rotate Left Through Carry Rd(0)C,Rd(n+1) Rd(n),CRd(7) Z,C,N,V 1 ROR Rd Rotate Right Through Carry Rd(7)C,Rd(n) Rd(n+1),CRd(0) Z,C,N,V 1 ASR Rd Arithmetic Shift Right Rd(n) Rd(n+1), n=0..6 Z,C,N,V 1 SWAP Rd Swap Nibbles Rd(3..0)Rd(7..4),Rd(7..4)Rd(3..0) None 1 BSET s Flag Set SREG(s) 1 SREG(s) 1 BCLR s Flag Clear SREG(s) 0 SREG(s) 1 BST Rr, b Bit Store from Register to T T Rr(b) T 1 BLD Rd, b Bit load from T to Register Rd(b) T None 1 1 SEC Set Carry C1 C CLC Clear Carry C0 C 1 SEN Set Negative Flag N1 N 1 CLN Clear Negative Flag N0 N 1 SEZ Set Zero Flag Z1 Z 1 1 CLZ Clear Zero Flag Z0 Z SEI Global Interrupt Enable I1 I 1 CLI Global Interrupt Disable I 0 I 1 SES Set Signed Test Flag S1 S 1 CLS Clear Signed Test Flag S0 S 1 SEV Set Twos Complement Overflow. V1 V 1 CLV Clear Twos Complement Overflow V0 V 1 SET Set T in SREG T1 T 1 CLT Clear T in SREG T0 T 1 SEH CLH Set Half Carry Flag in SREG Clear Half Carry Flag in SREG H1 H0 H H 1 1 MCU CONTROL INSTRUCTIONS 240 ATmega8515(L) 2512G–AVR–03/05 CHAPITRE 4. SPÉCIFICATIONS DU AVR ATMEGA8515 DE ATMEL 170 ATmega8515(L) Mnemonics Operands Description NOP No Operation SLEEP Sleep WDR Watchdog Reset Operation Flags #Clocks None 1 (see specific descr. for Sleep function) None 1 (see specific descr. for WDR/timer) None 1 241 2512G–AVR–03/05 Chapitre 5 Spécifications du PIC16F676 de Microchip PIC16F630/676 Data Sheet 14-Pin FLASH-Based 8-Bit CMOS Microcontrollers 2003 Microchip Technology Inc. DS40039C Ces spécifications sont tirées de la datasheet du PIC16F676, disponible gratuitement sur le site de Microchip : www.microchip.com 171 CHAPITRE 5. SPÉCIFICATIONS DU PIC16F676 DE MICROCHIP 172 5.1 Pinout PIC16F630/676 Pin Diagrams 14-pin PDIP, SOIC, TSSOP DS40039C-page 2 1 2 3 4 5 6 7 PIC16F676 VDD RA5/T1CKI/OSC1/CLKIN RA4/T1G/OSC2/AN3/CLKOUT RA3/MCLR/VPP RC5 RC4 RC3/AN7 1 2 3 4 5 6 7 PIC16F630 VDD RA5/T1CKI/OSC1/CLKIN RA4/T1G/OSC2/CLKOUT RA3/MCLR/VPP RC5 RC4 RC3 14 13 12 11 10 9 8 14 13 12 11 10 9 8 VSS RA0/CIN+/ICSPDAT RA1/CIN-/ICSPCLK RA2/COUT/T0CKI/INT RC0 RC1 RC2 VSS RA0/AN0/CIN+/ICSPDAT RA1/AN1/CIN-/VREF/ICSPCLK RA2/AN2/COUT/T0CKI/INT RC0/AN4 RC1/AN5 RC2/AN6 2003 Microchip Technology Inc. 5.2. SCHÉMA-BLOC 173 5.2 Schéma-bloc PIC16F630/676 1.0 DEVICE OVERVIEW Sheet and is highly recommended reading for a better understanding of the device architecture and operation of the peripheral modules. This document contains device specific information for the PIC16F630/676. Additional information may be found in the PICmicroTM Mid-Range Reference Manual (DS33023), which may be obtained from your local Microchip Sales Representative or downloaded from the Microchip web site. The Reference Manual should be considered a complementary document to this Data FIGURE 1-1: The PIC16F630 and PIC16F676 devices are covered by this Data Sheet. They are identical, except the PIC16F676 has a 10-bit A/D converter. They come in 14-pin PDIP, SOIC and TSSOP packages. Figure 1-1 shows a block diagram of the PIC16F630/676 devices. Table 1-1 shows the pinout description. PIC16F630/676 BLOCK DIAGRAM INT Configuration 13 8 Data Bus Program Counter PORTA RA0 FLASH RA1 1K x 14 Program Memory Program Bus 8-Level Stack (13-bit) 14 RAM RA2 64 bytes RA3 RA4 File Registers RAM Addr RA5 9 Addr MUX Instruction reg 7 Direct Addr 8 Indirect Addr FSR reg STATUS reg 8 PORTC RC0 RC1 RC2 RC3 RC4 RC5 3 MUX Power-up Timer Instruction Decode & Control OSC1/CLKIN Oscillator Start-up Timer Power-on Reset Timing Generation ALU 8 Watchdog Timer Brown-out Detect OSC2/CLKOUT W reg Internal Oscillator T1G MCLR VDD VSS T1CKI Timer0 Timer1 T0CKI Analog to Digital Converter (PIC16F676 only) Analog Comparator and reference EEDATA 8 128 bytes DATA EEPROM EEADDR CIN- CIN+ COUT VREF AN0 AN1 AN2 AN3 AN4 AN5 AN6 AN7 2003 Microchip Technology Inc. DS40039C-page 5 CHAPITRE 5. SPÉCIFICATIONS DU PIC16F676 DE MICROCHIP 174 PIC16F630/676 TABLE 1-1: PIC16F630/676 PINOUT DESCRIPTION Name RA0/AN0/CIN+/ICSPDAT RA1/AN1/CIN-/VREF/ ICSPCLK RA2/AN2/COUT/T0CKI/INT RA3/MCLR/VPP RA4/T1G/AN3/OSC2/ CLKOUT RA5/T1CKI/OSC1/CLKIN RC0/AN4 RC1/AN5 RC2/AN6 RC3/AN7 RC4 RC5 VSS VDD Legend: Function Input Type Output Type RA0 TTL CMOS AN0 CIN+ ICSPDAT AN AN TTL — CMOS RA1 TTL CMOS AN1 CINVREF ICSPCLK AN AN AN ST — — — — RA2 ST CMOS AN2 COUT T0CKI INT RA3 MCLR VPP RA4 AN — ST ST TTL ST HV TTL — CMOS — — — — — CMOS T1G AN3 OSC2 CLKOUT ST AN3 — — — — XTAL CMOS RA5 TTL CMOS T1CKI ST OSC1 XTAL CLKIN ST RC0 TTL AN4 AN4 RC1 TTL AN5 AN5 RC2 TTL AN6 AN6 RC3 TTL AN7 AN7 RC4 TTL RC5 TTL VSS Power VDD Power Shade = PIC16F676 only TTL = TTL input buffer ST = Schmitt Trigger input buffer DS40039C-page 6 — — — CMOS — CMOS — CMOS — CMOS — CMOS CMOS — — Description Bi-directional I/O w/ programmable pull-up and Interrupt-on-change A/D Channel 0 input Comparator input Serial Programming Data I/O Bi-directional I/O w/ programmable pull-up and Interrupt-on-change A/D Channel 1 input Comparator input External Voltage reference Serial Programming Clock Bi-directional I/O w/ programmable pull-up and Interrupt-on-change A/D Channel 2 input Comparator output Timer0 clock input External Interrupt Input port with Interrupt-on-change Master Clear Programming voltage Bi-directional I/O w/ programmable pull-up and Interrupt-on-change Timer1 gate A/D Channel 3 input Crystal/Resonator FOSC/4 output Bi-directional I/O w/ programmable pull-up and Interrupt-on-change Timer1 clock Crystal/Resonator External clock input/RC oscillator connection Bi-directional I/O A/D Channel 4 input Bi-directional I/O A/D Channel 5 input Bi-directional I/O A/D Channel 6 input Bi-directional I/O A/D Channel 7 input Bi-directional I/O Bi-directional I/O Ground reference Positive supply 2003 Microchip Technology Inc. 5.3. ORGANISATION DE LA MÉMOIRE 175 5.3 Organisation de la mémoire PIC16F630/676 2.0 MEMORY ORGANIZATION 2.2 2.1 Program Memory Organization The data memory (see Figure 2-2) is partitioned into two banks, which contain the General Purpose registers and the Special Function registers. The Special Function registers are located in the first 32 locations of each bank. Register locations 20h-5Fh are General Purpose registers, implemented as static RAM and are mapped across both banks. All other RAM is unimplemented and returns ‘0’ when read. RP0 (STATUS<5>) is the bank select bit. The PIC16F630/676 devices have a 13-bit program counter capable of addressing an 8K x 14 program memory space. Only the first 1K x 14 (0000h - 03FFh) for the PIC16F630/676 devices is physically implemented. Accessing a location above these boundaries will cause a wrap around within the first 1K x 14 space. The RESET vector is at 0000h and the interrupt vector is at 0004h (see Figure 2-1). FIGURE 2-1: PROGRAM MEMORY MAP AND STACK FOR THE PIC16F630/676 PC<12:0> CALL, RETURN RETFIE, RETLW • RP0 = 0 Bank 0 is selected • RP0 = 1 Bank 1 is selected Note: 2.2.1 13 Data Memory Organization The IRP and RP1 bits STATUS<7:6> are reserved and should always be maintained as ‘0’s. GENERAL PURPOSE REGISTER FILE The register file is organized as 64 x 8 in the PIC16F630/676 devices. Each register is accessed, either directly or indirectly, through the File Select Register FSR (see Section 2.4). Stack Level 1 Stack Level 2 Stack Level 8 RESET Vector 000h Interrupt Vector 0004 0005 On-chip Program Memory 03FFh 0400h 1FFFh 2003 Microchip Technology Inc. DS40039C-page 7 CHAPITRE 5. SPÉCIFICATIONS DU PIC16F676 DE MICROCHIP 176 PIC16F630/676 2.2.2 SPECIAL FUNCTION REGISTERS The Special Function registers are registers used by the CPU and peripheral functions for controlling the desired operation of the device (see Table 2-1). These registers are static RAM. The special registers can be classified into two sets: core and peripheral. The Special Function registers associated with the “core” are described in this section. Those related to the operation of the peripheral features are described in the section of that peripheral feature. FIGURE 2-2: DATA MEMORY MAP OF THE PIC16F630/676 File Address Indirect addr.(1) TMR0 PCL STATUS FSR PORTA PORTC PCLATH INTCON PIR1 TMR1L TMR1H T1CON CMCON ADRESH(2) ADCON0(2) 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 General Purpose Registers File Address Indirect addr.(1) OPTION_REG PCL STATUS FSR TRISA TRISC PCLATH INTCON PIE1 PCON OSCCAL ANSEL(2) WPUA IOCA VRCON EEDAT EEADR EECON1 EECON2(1) ADRESL(2) ADCON1(2) 80h 81h 82h 83h 84h 85h 86h 87h 88h 89h 8Ah 8Bh 8Ch 8Dh 8Eh 8Fh 90h 91h 92h 93h 94h 95h 96h 97h 98h 99h 9Ah 9Bh 9Ch 9Dh 9Eh 9Fh A0h accesses 20h-5Fh 64 Bytes 5Fh 60h DFh E0h 7Fh Bank 0 FFh Bank 1 Unimplemented data memory locations, read as '0'. 1: Not a physical register. 2: PIC16F676 only. DS40039C-page 8 2003 Microchip Technology Inc. 5.3. ORGANISATION DE LA MÉMOIRE 177 PIC16F630/676 TABLE 2-1: Addr Name PIC16F630/676 SPECIAL REGISTERS SUMMARY BANK 0 Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Value on POR, BOD Page Bank 0 00h INDF Addressing this location uses contents of FSR to address data memory (not a physical register) xxxx xxxx 18,61 01h TMR0 Timer0 Module’s Register xxxx xxxx 29 02h PCL Program Counter's (PC) Least Significant Byte 0000 0000 17 03h STATUS 0001 1xxx 11 04h FSR 05h PORTA 06h 07h IRP(2) RP1(2) RP0 TO PD Z DC C xxxx xxxx 18 — I/O Control Registers --xx xxxx 19 — — — I/O Control Registers --xx xxxx 26 — Indirect data memory address pointer — PORTC — Unimplemented — 08h — Unimplemented — 09h — Unimplemented — — ---0 0000 17 — — — INTCON GIE PEIE T0IE INTE RAIE T0IF INTF RAIF 0000 0000 13 PIR1 EEIF ADIF — — CMIF — — TMR1IF 00-- 0--0 15 0Ah PCLATH 0Bh 0Ch Write buffer for upper 5 bits of program counter 0Dh — 0Eh TMR1L Unimplemented Holding register for the Least Significant Byte of the 16-bit TMR1 0Fh TMR1H Holding register for the Most Significant Byte of the 16-bit TMR1 10h T1CON 11h — 12h — 13h — — xxxx xxxx 32 xxxx xxxx 32 -000 0000 34 Unimplemented — — Unimplemented — — — Unimplemented — — 14h — Unimplemented — — 15h — Unimplemented — — 16h — Unimplemented — — 17h — Unimplemented — — 18h — Unimplemented — — -0-0 0000 37 19h CMCON — — T1GE COUT T1CKPS1 — T1CKPS0 CINV T1OSCEN CIS T1SYNC TMR1CS CM2 CM1 TMR1ON CM0 1Ah — Unimplemented — — 1Bh — Unimplemented — — 1Ch — Unimplemented — — 1Dh — Unimplemented — — 1Eh ADRESH(3) xxxx xxxx 44 1Fh ADCON0(3) 00-0 0000 45,61 Legend: Note 1: 2: 3: Most Significant 8 bits of the left shifted A/D result or 2 bits of right shifted result ADFM VCFG — CHS2 CHS1 CHS0 GO/DONE ADON — = Unimplemented locations read as ‘0’, u = unchanged, x = unknown, q = value depends on condition shaded = unimplemented Other (non Power-up) Resets include MCLR Reset, Brown-out Detect and Watchdog Timer Reset during normal operation. IRP & RP1 bits are reserved, always maintain these bits clear. PIC16F676 only. 2003 Microchip Technology Inc. DS40039C-page 9 CHAPITRE 5. SPÉCIFICATIONS DU PIC16F676 DE MICROCHIP 178 PIC16F630/676 TABLE 2-2: PIC16F630/676 SPECIAL FUNCTION REGISTERS SUMMARY BANK 1 Value on POR, BOD Page xxxx xxxx 1111 1111 18,61 12,30 82h INDF Addressing this location uses contents of FSR to address data memory (not a physical register) OPTION_REG INTEDG T0CS T0SE PSA PS2 PS1 PS0 RAPU PCL Program Counter's (PC) Least Significant Byte 0000 0000 17 83h STATUS 0001 1xxx 11 84h FSR IRP(2) RP1(2) RP0 Indirect data memory address pointer 85h 86h TRISA — — — Unimplemented TRISA5 TRISA4 TRISA3 TRISA2 TRISA1 87h 88h TRISC — — — Unimplemented TRISC5 TRISC4 TRISC3 TRISC2 TRISC1 Addr Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Bank 1 80h 81h 89h — 8Ah 8Bh PCLATH INTCON 8Ch 8Dh PIE1 8Eh PCON 8Fh 90h — OSCCAL 91h 92h ANSEL(3) — — 93h 94h — — TO PD Z DC C xxxx xxxx 18 TRISA0 --11 1111 — 19 — TRISC0 --11 1111 — — — Unimplemented — GIE — PEIE EEIE ADIE Unimplemented — CAL5 — — T0IE Write buffer for upper 5 bits of program counter INTE RAIE T0IF INTF RAIF — — ---0 0000 0000 0000 17 13 — — CMIE — — TMR1IE 00-- 0--0 — 14 — — — — — POR BOD ---- --qq 16 — 1000 00-- 16 1111 1111 — 46 — — — — — CAL4 CAL3 CAL2 CAL1 CAL0 — — ANS7 ANS6 Unimplemented ANS5 ANS4 ANS3 ANS2 ANS1 ANS0 Unimplemented Unimplemented 95h WPUA — — WPUA5 WPUA4 — WPUA2 WPUA1 WPUA0 --11 -111 20 96h IOCA — — IOCA5 IOCA4 IOCA3 IOCA2 IOCA1 IOCA0 --00 0000 21 — — — — 0-0- 0000 0000 0000 42 49 0000 0000 ---- x000 49 50 ---- ---xxxx xxxx 49 44 -000 ---- 45,61 97h 98h — — 99h 9Ah VRCON EEDAT 9Bh 9Ch EEADR EECON1 9Dh 9Eh EECON2 ADRESL(3) 9Fh ADCON1(3) Legend: Note 1: 2: 3: Unimplemented Unimplemented — VREN EEPROM data register — — VRR EEPROM address register — — — VR3 VR2 VR1 VR0 — WRERR WREN WR RD EEPROM control register 2 (not a physical register) Least Significant 2 bits of the left shifted result or 8 bits of the right shifted result — ADCS2 ADCS1 ADCS0 — — — — — = Unimplemented locations read as ‘0’, u = unchanged, x = unknown, q = value depends on condition, shaded = unimplemented Other (non Power-up) Resets include MCLR Reset, Brown-out Detect and Watchdog Timer Reset during normal operation. IRP & RP1 bits are reserved, always maintain these bits clear. PIC16F676 only. DS40039C-page 10 2003 Microchip Technology Inc. 5.4. REGISTRE D’ÉTAT (STATUS) 179 5.4 Registre d’état (STATUS) PIC16F630/676 2.2.2.1 STATUS Register The STATUS register, shown in Register 2-1, contains: • the arithmetic status of the ALU • the RESET status • the bank select bits for data memory (SRAM) It is recommended, therefore, that only BCF, BSF, SWAPF and MOVWF instructions are used to alter the STATUS register, because these instructions do not affect any STATUS bits. For other instructions not affecting any STATUS bits, see the “Instruction Set Summary”. Note 1: Bits IRP and RP1 (STATUS<7:6>) are not used by the PIC16F630/676 and should be maintained as clear. Use of these bits is not recommended, since this may affect upward compatibility with future products. The STATUS register can be the destination for any instruction, like any other register. If the STATUS register is the destination for an instruction that affects the Z, DC or C bits, then the write to these three bits is disabled. These bits are set or cleared according to the device logic. Furthermore, the TO and PD bits are not writable. Therefore, the result of an instruction with the STATUS register as destination may be different than intended. 2: The C and DC bits operate as a Borrow and Digit Borrow out bit, respectively, in subtraction. See the SUBLW and SUBWF instructions for examples. For example, CLRF STATUS will clear the upper three bits and set the Z bit. This leaves the STATUS register as 000u u1uu (where u = unchanged). REGISTER 2-1: STATUS — STATUS REGISTER (ADDRESS: 03h OR 83h) Reserved Reserved IRP RP1 R/W-0 R-1 R-1 R/W-x R/W-x R/W-x RP0 TO PD Z DC C bit 7 bit 7 bit 0 IRP: This bit is reserved and should be maintained as ‘0’ bit 6 RP1: This bit is reserved and should be maintained as ‘0’ bit 5 RP0: Register Bank Select bit (used for direct addressing) 1 = Bank 1 (80h - FFh) 0 = Bank 0 (00h - 7Fh) bit 4 TO: Time-out bit 1 = After power-up, CLRWDT instruction, or SLEEP instruction 0 = A WDT time-out occurred bit 3 PD: Power-down bit 1 = After power-up or by the CLRWDT instruction 0 = By execution of the SLEEP instruction bit 2 Z: Zero bit 1 = The result of an arithmetic or logic operation is zero 0 = The result of an arithmetic or logic operation is not zero bit 1 DC: Digit carry/borrow bit (ADDWF, ADDLW,SUBLW,SUBWF instructions) For borrow, the polarity is reversed. 1 = A carry-out from the 4th low order bit of the result occurred 0 = No carry-out from the 4th low order bit of the result bit 0 C: Carry/borrow bit (ADDWF, ADDLW, SUBLW, SUBWF instructions) 1 = A carry-out from the Most Significant bit of the result occurred 0 = No carry-out from the Most Significant bit of the result occurred Note: For borrow the polarity is reversed. A subtraction is executed by adding the two’s complement of the second operand. For rotate (RRF, RLF) instructions, this bit is loaded with either the high or low order bit of the source register Legend: R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’ - n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared 2003 Microchip Technology Inc. x = Bit is unknown DS40039C-page 11 CHAPITRE 5. SPÉCIFICATIONS DU PIC16F676 DE MICROCHIP 180 5.5 Compteur de programme, pile PIC16F630/676 2.3 PCL and PCLATH 2.3.2 The program counter (PC) is 13-bits wide. The low byte comes from the PCL register, which is a readable and writable register. The high byte (PC<12:8>) is not directly readable or writable and comes from PCLATH. On any RESET, the PC is cleared. Figure 2-3 shows the two situations for the loading of the PC. The upper example in Figure 2-3 shows how the PC is loaded on a write to PCL (PCLATH<4:0> → PCH). The lower example in Figure 2-3 shows how the PC is loaded during a CALL or GOTO instruction (PCLATH<4:3> → PCH). FIGURE 2-3: LOADING OF PC IN DIFFERENT SITUATIONS PCH PCL 12 8 7 0 PC 8 PCLATH<4:0> 5 Instruction with PCL as Destination ALU result PCLATH PCH 12 11 10 PCL 8 STACK The PIC16F630/676 family has an 8-level x 13-bit wide hardware stack (see Figure 2-1). The stack space is not part of either program or data space and the stack pointer is not readable or writable. The PC is PUSHed onto the stack when a CALL instruction is executed or an interrupt causes a branch. The stack is POPed in the event of a RETURN, RETLW or a RETFIE instruction execution. PCLATH is not affected by a PUSH or POP operation. The stack operates as a circular buffer. This means that after the stack has been PUSHed eight times, the ninth push overwrites the value that was stored from the first push. The tenth push overwrites the second push (and so on). Note 1: There are no STATUS bits to indicate stack overflow or stack underflow conditions. 2: There are no instructions/mnemonics called PUSH or POP. These are actions that occur from the execution of the CALL, RETURN, RETLW and RETFIE instructions or the vectoring to an interrupt address. 0 7 GOTO, CALL PC 2 PCLATH<4:3> 11 Opcode <10:0> PCLATH 2.3.1 COMPUTED GOTO A computed GOTO is accomplished by adding an offset to the program counter (ADDWF PCL). When performing a table read using a computed GOTO method, care should be exercised if the table location crosses a PCL memory boundary (each 256-byte block). Refer to the Application Note “Implementing a Table Read" (AN556). 2003 Microchip Technology Inc. DS40039C-page 17 5.6. ADRESSAGE INDIRECT 181 5.6 Adressage indirect PIC16F630/676 2.4 Indirect Addressing, INDF and FSR Registers A simple program to clear RAM location 20h-2Fh using indirect addressing is shown in Example 2-1. The INDF register is not a physical register. Addressing the INDF register will cause indirect addressing. EXAMPLE 2-1: Indirect addressing is possible by using the INDF register. Any instruction using the INDF register actually accesses data pointed to by the File Select register (FSR). Reading INDF itself indirectly will produce 00h. Writing to the INDF register indirectly results in a no operation (although STATUS bits may be affected). An effective 9-bit address is obtained by concatenating the 8-bit FSR register and the IRP bit (STATUS<7>), as shown in Figure 2-4. FIGURE 2-4: movlw movwf clrf incf btfss goto NEXT RP1 RP0 0x20 FSR INDF FSR FSR,4 NEXT CONTINUE ;initialize pointer ;to RAM ;clear INDF register ;inc pointer ;all done? ;no clear next ;yes continue DIRECT/INDIRECT ADDRESSING PIC16F630/676 Direct Addressing (1) INDIRECT ADDRESSING 6 From Opcode Indirect Addressing 0 IRP (1) 7 Bank Select Bank Select Location Select 00 01 10 FSR Register 0 Location Select 11 00h 180h Data Memory Not Used 7Fh 1FFh Bank 0 Bank 1 Bank 2 Bank 3 For memory map detail see Figure 2-2. Note 1: The RP1 and IRP bits are reserved; always maintain these bits clear. DS40039C-page 18 2003 Microchip Technology Inc. CHAPITRE 5. SPÉCIFICATIONS DU PIC16F676 DE MICROCHIP 182 5.7 Port A PIC16F630/676 3.0 PORTS A AND C There are as many as twelve general purpose I/O pins available. Depending on which peripherals are enabled, some or all of the pins may not be available as general purpose I/O. In general, when a peripheral is enabled, the associated pin may not be used as a general purpose I/O pin. Note: 3.1 Additional information on I/O ports may be found in the PICmicro™ Mid-Range Reference Manual, (DS33023) PORTA and the TRISA Registers PORTA is an 6-bit wide, bi-directional port. The corresponding data direction register is TRISA. Setting a TRISA bit (= 1) will make the corresponding PORTA pin an input (i.e., put the corresponding output driver in a Hi-impedance mode). Clearing a TRISA bit (= 0) will make the corresponding PORTA pin an output (i.e., put the contents of the output latch on the selected pin). The exception is RA3, which is input only and its TRIS bit will always read as ‘1’. Example 3-1 shows how to initialize PORTA. Reading the PORTA register reads the status of the pins, whereas writing to it will write to the port latch. All write operations are read-modify-write operations. Therefore, a write to a port implies that the port pins are read, this value is modified and then written to the port data latch. RA3 reads ‘0’ when MCLREN = 1. The TRISA register controls the direction of the PORTA pins, even when they are being used as analog inputs. The user must ensure the bits in the TRISA REGISTER 3-1: register are maintained set when using them as analog inputs. I/O pins configured as analog input always read ‘0’. Note: The ANSEL (9Fh) and CMCON (19h) registers must be initialized to configure an analog channel as a digital input. Pins configured as analog inputs will read ‘0’. The ANSEL register is defined for the PIC16F676. EXAMPLE 3-1: bcf clrf movlw movwf bsf clrf movlw movwf STATUS,RP0 PORTA 05h CMCON STATUS,RP0 ANSEL 0Ch TRISA bcf STATUS,RP0 3.2 INITIALIZING PORTA ;Bank 0 ;Init PORTA ;Set RA<2:0> to ;digital I/O ;Bank 1 ;digital I/O ;Set RA<3:2> as inputs ;and set RA<5:4,1:0> ;as outputs ;Bank 0 Additional Pin Functions Every PORTA pin on the PIC16F630/676 has an interrupt-on-change option and every PORTA pin, except RA3, has a weak pull-up option. The next two sections describe these functions. 3.2.1 WEAK PULL-UP Each of the PORTA pins, except RA3, has an individually configurable weak internal pull-up. Control bits WPUAx enable or disable each pull-up. Refer to Register 3-3. Each weak pull-up is automatically turned off when the port pin is configured as an output. The pull-ups are disabled on a Power-on Reset by the RAPU bit (OPTION<7>). PORTA — PORTA REGISTER (ADDRESS: 05h) U-0 U-0 R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x — — RA5 RA4 RA3 RA2 RA1 RA0 bit 7 bit 0 bit 7-6: Unimplemented: Read as ’0’ bit 5-0: PORTA<5:0>: PORTA I/O pin 1 = Port pin is >VIH 0 = Port pin is <VIL Legend: R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’ - n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared 2003 Microchip Technology Inc. x = Bit is unknown DS40039C-page 19 5.7. PORT A 183 PIC16F630/676 REGISTER 3-2: TRISA — PORTA TRISTATE REGISTER (ADDRESS: 85h) U-0 U-0 R/W-x R/W-x R-1 R/W-x R/W-x R/W-x — — TRISA5 TRISA4 TRISA3 TRISA2 TRISA1 TRISA0 bit 7 bit 0 bit 7-6: Unimplemented: Read as ’0’ bit 5-0: TRISA<5:0>: PORTA Tri-State Control bit 1 = PORTA pin configured as an input (tri-stated) 0 = PORTA pin configured as an output Note: TRISA<3> always reads 1. Legend: REGISTER 3-3: R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’ - n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknown WPUA — WEAK PULL-UP REGISTER (ADDRESS: 95h) U-0 U-0 R/W-1 R/W-1 U-0 R/W-1 R/W-1 R/W-1 — — WPUA5 WPUA4 — WPUA2 WPUA1 WPUA0 bit 7 bit 0 bit 7-6 Unimplemented: Read as ‘0’ bit 5-4 WPUA<5:4>: Weak Pull-up Register bit 1 = Pull-up enabled 0 = Pull-up disabled bit 3 Unimplemented: Read as ‘0’ bit 2-0 WPUA<2:0>: Weak Pull-up Register bit 1 = Pull-up enabled 0 = Pull-up disabled Note 1: Global RAPU must be enabled for individual pull-ups to be enabled. 2: The weak pull-up device is automatically disabled if the pin is in Output mode (TRISA = 0). Legend: 3.2.2 R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’ - n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared INTERRUPT-ON-CHANGE Each of the PORTA pins is individually configurable as an interrupt-on-change pin. Control bits IOCAx enable or disable the interrupt function for each pin. Refer to Register 3-4. The interrupt-on-change is disabled on a Power-on Reset. For enabled interrupt-on-change pins, the values are compared with the old value latched on the last read of PORTA. The ‘mismatch’ outputs of the last read are OR'd together to set, the PORTA Change Interrupt flag bit (RAIF) in the INTCON register. DS40039C-page 20 x = Bit is unknown This interrupt can wake the device from SLEEP. The user, in the Interrupt Service Routine, can clear the interrupt in the following manner: a) b) Any read or write of PORTA. This will end the mismatch condition. Clear the flag bit RAIF. A mismatch condition will continue to set flag bit RAIF. Reading PORTA will end the mismatch condition and allow flag bit RAIF to be cleared. Note: If a change on the I/O pin should occur when the read operation is being executed (start of the Q2 cycle), then the RAIF interrupt flag may not get set. 2003 Microchip Technology Inc. CHAPITRE 5. SPÉCIFICATIONS DU PIC16F676 DE MICROCHIP 184 PIC16F630/676 REGISTER 3-4: IOCA — INTERRUPT-ON-CHANGE PORTA REGISTER (ADDRESS: 96h) U-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 — — IOCA5 IOCA4 IOCA3 IOCA2 IOCA1 IOCA0 bit 7 bit 0 bit 7-6 Unimplemented: Read as ‘0’ bit 5-0 IOCA<5:0>: Interrupt-on-Change PORTA Control bit 1 = Interrupt-on-change enabled 0 = Interrupt-on-change disabled Note: Global interrupt enable (GIE) must be enabled for individual interrupts to be recognized. Legend: R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’ - n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared 2003 Microchip Technology Inc. x = Bit is unknown DS40039C-page 21 5.7. PORT A 185 PIC16F630/676 TABLE 3-1: Address SUMMARY OF REGISTERS ASSOCIATED WITH PORTA Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Value on: POR, BOD Value on all other RESETS 05h PORTA — — RA5 RA4 RA3 RA2 RA1 RA0 --xx xxxx --uu uuuu 0Bh/8Bh INTCON GIE PEIE T0IE INTE RAIE T0IF INTF RAIF 0000 0000 0000 000u 19h CMCON 81h OPTION_REG 85h TRISA 91h ANSEL(1) — COUT — CINV CIS CM2 CM1 CM0 -0-0 0000 -0-0 0000 RAPU INTEDG T0CS T0SE PSA PS2 PS1 PS0 1111 1111 1111 1111 — — TRISA5 TRISA4 TRISA3 TRISA2 TRISA1 TRISA0 --11 1111 --11 1111 ANS7 ANS6 ANS5 ANS4 ANS3 ANS2 ANS1 ANS0 1111 1111 1111 1111 95h WPUA — — WPUA5 WPUA4 — WPUA2 WPUA1 WPUA0 --11 -111 --11 -111 96h IOCA — — IOCA5 IOCA4 IOCA3 IOCA2 IOCA1 IOCA0 --00 0000 --00 0000 Note 1: PIC16F676 only. Legend: x = unknown, u = unchanged, - = unimplemented locations read as '0'. Shaded cells are not used by PORTA. 2003 Microchip Technology Inc. DS40039C-page 25 CHAPITRE 5. SPÉCIFICATIONS DU PIC16F676 DE MICROCHIP 186 5.8 Port C PIC16F630/676 3.3 PORTC 3.3.2 PORTC is a general purpose I/O port consisting of 6 bidirectional pins. The pins can be configured for either digital I/O or analog input to A/D converter. For specific information about individual functions such as the comparator or the A/D, refer to the appropriate section in this Data Sheet. Note: The ANSEL register (9Fh) must be clear to configure an analog channel as a digital input. Pins configured as analog inputs will read ‘0’. The ANSEL register is defined for the PIC16F676. EXAMPLE 3-2: bcf clrf bsf clrf movlw movwf STATUS,RP0 PORTC STATUS,RP0 ANSEL 0Ch TRISC bcf STATUS,RP0 3.3.1 RC4 AND RC5 The RC4 and RC5 pins are configurable to function as a general purpose I/Os. FIGURE 3-7: BLOCK DIAGRAM OF RC4 AND RC5 PINS Data bus D WR PORTC CK Q VDD Q I/O Pin INITIALIZING PORTC D ;Bank 0 ;Init PORTC ;Bank 1 ;digital I/O ;Set RC<3:2> as inputs ;and set RC<5:4,1:0> ;as outputs ;Bank 0 WR TRISC CK Q Q VSS RD TRISC RD PORTC RC0/AN4, RC1/AN5, RC2/AN6, RC3/ AN7 The RC0/RC1/RC2/RC3 pins are configurable to function as one of the following: • a general purpose I/O • an analog input for the A/D Converter (PIC16F676 only) FIGURE 3-6: BLOCK DIAGRAM OF RC0/RC1/RC2/RC3 PINs Data bus D WR PORTC CK VDD Q Q I/O Pin D WR TRISC CK Q Q VSS Analog Input Mode RD TRISC RD PORTC To A/D Converter DS40039C-page 26 2003 Microchip Technology Inc. 5.8. PORT C 187 PIC16F630/676 REGISTER 3-5: PORTC — PORTC REGISTER (ADDRESS: 07h) U-0 U-0 R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x — — RC5 RC4 RC3 RC2 RC1 RC0 bit 7 bit 0 bit 7-6: Unimplemented: Read as ’0’ bit 5-0: PORTC<5:0>: General Purpose I/O pin 1 = Port pin is >VIH 0 = Port pin is <VIL Legend: REGISTER 3-6: R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’ - n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknown TRISC — PORTC TRISTATE REGISTER (ADDRESS: 87h) U-0 — U-0 R/W-1 R/W-1 R/W-1 R/W-1 R/W-1 R/W-1 — TRISC5 TRISC4 TRISC3 TRISC2 TRISC1 TRISC0 bit 7 bit 0 bit 7-6: Unimplemented: Read as ’0’ bit 5-0: TRISC<5:0>: PORTC Tri-State Control bit 1 = PORTC pin configured as an input (tri-stated) 0 = PORTC pin configured as an output Legend: TABLE 3-2: Address R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’ - n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknown SUMMARY OF REGISTERS ASSOCIATED WITH PORTC Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Value on: POR, BOD Value on all other RESETS --uu uuuu 07h PORTC — — RC5 RC4 RC3 RC2 RC1 RC0 --xx xxxx 87h TRISC — — TRISC5 TRISC4 TRISC3 TRISC2 TRISC1 TRISC0 --11 1111 --11 1111 91h ANSEL(1) ANS7 ANS6 ANS5 ANS4 ANS3 ANS2 ANS1 ANS0 1111 1111 1111 1111 Note 1: PIC16F676 only. Legend: x = unknown, u = unchanged, - = unimplemented locations read as '0'. Shaded cells are not used by PORTC. 2003 Microchip Technology Inc. DS40039C-page 27 CHAPITRE 5. SPÉCIFICATIONS DU PIC16F676 DE MICROCHIP 188 5.9 Timer 0 PIC16F630/676 4.0 TIMER0 MODULE Counter mode is selected by setting the T0CS bit (OPTION_REG<5>). In this mode, the Timer0 module will increment either on every rising or falling edge of pin RA2/T0CKI. The incrementing edge is determined by the source edge (T0SE) control bit (OPTION_REG<4>). Clearing the T0SE bit selects the rising edge. The Timer0 module timer/counter has the following features: • • • • • • 8-bit timer/counter Readable and writable 8-bit software programmable prescaler Internal or external clock select Interrupt on overflow from FFh to 00h Edge select for external clock Note: Figure 4-1 is a block diagram of the Timer0 module and the prescaler shared with the WDT. Note: 4.1 4.2 Additional information on the Timer0 module is available in the PICmicroTM MidRange Reference Manual, (DS33023). Timer0 Interrupt A Timer0 interrupt is generated when the TMR0 register timer/counter overflows from FFh to 00h. This overflow sets the T0IF bit. The interrupt can be masked by clearing the T0IE bit (INTCON<5>). The T0IF bit (INTCON<2>) must be cleared in software by the Timer0 module Interrupt Service Routine before reenabling this interrupt. The Timer0 interrupt cannot wake the processor from SLEEP since the timer is shut-off during SLEEP. Timer0 Operation Timer mode is selected by clearing the T0CS bit (OPTION_REG<5>). In Timer mode, the Timer0 module will increment every instruction cycle (without prescaler). If TMR0 is written, the increment is inhibited for the following two instruction cycles. The user can work around this by writing an adjusted value to the TMR0 register. FIGURE 4-1: Counter mode has specific external clock requirements. Additional information on these requirements is available in the Mid-Range Reference PICmicroTM Manual, (DS33023). BLOCK DIAGRAM OF THE TIMER0/WDT PRESCALER CLKOUT (= FOSC/4) Data Bus 0 8 1 SYNC 2 Cycles 1 T0CKI pin 0 T0SE T0CS 8-bit Prescaler Set Flag bit T0IF on Overflow PSA 1 PSA TMR0 0 8 PS0 - PS2 Watchdog Timer WDTE 1 WDT Time-out 0 PSA Note 1: T0SE, T0CS, PSA, PS0-PS2 are bits in the Option register. 2003 Microchip Technology Inc. DS40039C-page 29 5.9. TIMER 0 189 PIC16F630/676 4.3 Using Timer0 with an External Clock a small RC delay of 20 ns) and low for at least 2TOSC (and a small RC delay of 20 ns). Refer to the electrical specification of the desired device. When no prescaler is used, the external clock input is the same as the prescaler output. The synchronization of T0CKI, with the internal phase clocks, is accomplished by sampling the prescaler output on the Q2 and Q4 cycles of the internal phase clocks. Therefore, it is necessary for T0CKI to be high for at least 2TOSC (and REGISTER 4-1: Note: The ANSEL (9Fh) and CMCON (19h) registers must be initialized to configure an analog channel as a digital input. Pins configured as analog inputs will read ‘0’. The ANSEL register is defined for the PIC16F676. OPTION_REG — OPTION REGISTER (ADDRESS: 81h) R/W-1 R/W-1 R/W-1 R/W-1 R/W-1 R/W-1 R/W-1 R/W-1 RAPU INTEDG T0CS T0SE PSA PS2 PS1 PS0 bit 7 bit 0 bit 7 RAPU: PORTA Pull-up Enable bit 1 = PORTA pull-ups are disabled 0 = PORTA pull-ups are enabled by individual port latch values bit 6 INTEDG: Interrupt Edge Select bit 1 = Interrupt on rising edge of RA2/INT pin 0 = Interrupt on falling edge of RA2/INT pin bit 5 T0CS: TMR0 Clock Source Select bit 1 = Transition on RA2/T0CKI pin 0 = Internal instruction cycle clock (CLKOUT) bit 4 T0SE: TMR0 Source Edge Select bit 1 = Increment on high-to-low transition on RA2/T0CKI pin 0 = Increment on low-to-high transition on RA2/T0CKI pin bit 3 PSA: Prescaler Assignment bit 1 = Prescaler is assigned to the WDT 0 = Prescaler is assigned to the Timer0 module bit 2-0 PS2:PS0: Prescaler Rate Select bits Bit Value 000 001 010 011 100 101 110 111 TMR0 Rate WDT Rate 1:2 1:4 1:8 1 : 16 1 : 32 1 : 64 1 : 128 1 : 256 1:1 1:2 1:4 1:8 1 : 16 1 : 32 1 : 64 1 : 128 Legend: DS40039C-page 30 R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’ - n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknown 2003 Microchip Technology Inc. CHAPITRE 5. SPÉCIFICATIONS DU PIC16F676 DE MICROCHIP 190 PIC16F630/676 4.4 Prescaler EXAMPLE 4-1: An 8-bit counter is available as a prescaler for the Timer0 module, or as a postscaler for the Watchdog Timer. For simplicity, this counter will be referred to as “prescaler” throughout this Data Sheet. The prescaler assignment is controlled in software by the control bit PSA (OPTION_REG<3>). Clearing the PSA bit will assign the prescaler to Timer0. Prescale values are selectable via the PS2:PS0 bits (OPTION_REG<2:0>). bcf STATUS,RP0 clrwdt clrf TMR0 bsf SWITCHING PRESCALER ASSIGNMENT The prescaler assignment is fully under software control (i.e., it can be changed “on the fly” during program execution). To avoid an unintended device RESET, the following instruction sequence (Example 4-1) must be executed when changing the prescaler assignment from Timer0 to WDT. To change prescaler from the WDT to the TMR0 module, use the sequence shown in Example 4-2. This precaution must be taken even if the WDT is disabled. EXAMPLE 4-2: Address CHANGING PRESCALER (WDT→TIMER0) clrwdt ;Clear WDT and ; postscaler ;Bank 1 bsf STATUS,RP0 movlw b’xxxx0xxx’ ;Select TMR0, ; prescale, and ; clock source OPTION_REG ; STATUS,RP0 ;Bank 0 movwf bcf TABLE 4-1: STATUS,RP0 ;Bank 0 ;Clear WDT ;Clear TMR0 and ; prescaler ;Bank 1 movlw b’00101111’ ;Required if desired movwf OPTION_REG ; PS2:PS0 is clrwdt ; 000 or 001 ; movlw b’00101xxx’ ;Set postscaler to movwf OPTION_REG ; desired WDT rate bcf STATUS,RP0 ;Bank 0 The prescaler is not readable or writable. When assigned to the Timer0 module, all instructions writing to the TMR0 register (e.g., CLRF 1, MOVWF 1, BSF 1, x....etc.) will clear the prescaler. When assigned to WDT, a CLRWDT instruction will clear the prescaler along with the Watchdog Timer. 4.4.1 CHANGING PRESCALER (TIMER0→WDT) REGISTERS ASSOCIATED WITH TIMER0 Name 01h TMR0 0Bh/8Bh INTCON Bit 7 Bit 6 Bit 3 Bit 2 Bit 1 Bit 0 Value on POR, BOD T0IE INTE RAIE T0IF INTF RAIF 0000 0000 0000 000u T0CS T0SE PSA PS2 PS1 PS0 1111 1111 1111 1111 Timer0 Module Register GIE PEIE RAPU INTEDG — — xxxx xxxx uuuu uuuu 81h OPTION_REG 85h TRISA Legend: — = Unimplemented locations, read as ‘0’, u = unchanged, x = unknown. Shaded cells are not used by the Timer0 module. 2003 Microchip Technology Inc. Value on all other RESETS Bit 4 Bit 5 TRISA5 TRISA4 TRISA3 TRISA2 TRISA1 TRISA0 --11 1111 --11 1111 DS40039C-page 31 5.10. TIMER 1 191 5.10 Timer 1 PIC16F630/676 5.0 TIMER1 MODULE WITH GATE CONTROL The Timer1 Control register (T1CON), shown in Register 5-1, is used to enable/disable Timer1 and select the various features of the Timer1 module. The PIC16F630/676 devices have a 16-bit timer. Figure 5-1 shows the basic block diagram of the Timer1 module. Timer1 has the following features: • • • • • • • • Note: Additional information on timer modules is available in the PICmicroTM Mid-Range Reference Manual, (DS33023). 16-bit timer/counter (TMR1H:TMR1L) Readable and writable Internal or external clock selection Synchronous or asynchronous operation Interrupt on overflow from FFFFh to 0000h Wake-up upon overflow (Asynchronous mode) Optional external enable input (T1G) Optional LP oscillator FIGURE 5-1: TIMER1 BLOCK DIAGRAM TMR1ON TMR1GE T1G TMR1ON TMR1GE Set Flag bit TMR1IF on Overflow TMR1 Synchronized Clock Input 0 TMR1H TMR1L 1 LP Oscillator T1SYNC OSC1 OSC2 INTOSC w/o CLKOUT T1OSCEN 1 FOSC/4 Internal Clock Prescaler 1, 2, 4, 8 Synchronize Detect 0 2 T1CKPS<1:0> SLEEP Input TMR1CS LP DS40039C-page 32 2003 Microchip Technology Inc. CHAPITRE 5. SPÉCIFICATIONS DU PIC16F676 DE MICROCHIP 192 PIC16F630/676 5.1 Timer1 Modes of Operation Timer1 can operate in one of three modes: • 16-bit timer with prescaler • 16-bit synchronous counter • 16-bit asynchronous counter In Timer mode, Timer1 is incremented on every instruction cycle. In Counter mode, Timer1 is incremented on the rising edge of the external clock input T1CKI. In addition, the Counter mode clock can be synchronized to the microcontroller system clock or run asynchronously. 5.2 The Timer1 register pair (TMR1H:TMR1L) increments to FFFFh and rolls over to 0000h. When Timer1 rolls over, the Timer1 interrupt flag bit (PIR1<0>) is set. To enable the interrupt on rollover, you must set these bits: • Timer1 interrupt Enable bit (PIE1<0>) • PEIE bit (INTCON<6>) • GIE bit (INTCON<7>). The interrupt is cleared by clearing the TMR1IF in the Interrupt Service Routine. Note: In Counter and Timer modules, the counter/timer clock can be gated by the T1G input. If an external clock oscillator is needed (and the microcontroller is using the INTOSC w/o CLKOUT), Timer1 can use the LP oscillator as a clock source. Note: In Counter mode, a falling edge must be registered by the counter prior to the first incrementing rising edge. FIGURE 5-2: Timer1 Interrupt 5.3 The TMR1H:TTMR1L register pair and the TMR1IF bit should be cleared before enabling interrupts. Timer1 Prescaler Timer1 has four prescaler options allowing 1, 2, 4, or 8 divisions of the clock input. The T1CKPS bits (T1CON<5:4>) control the prescale counter. The prescale counter is not directly readable or writable; however, the prescaler counter is cleared upon a write to TMR1H or TMR1L. TIMER1 INCREMENTING EDGE T1CKI = 1 when TMR1 Enabled T1CKI = 0 when TMR1 Enabled Note 1: Arrows indicate counter increments. 2: In Counter mode, a falling edge must be registered by the counter prior to the first incrementing rising edge of the clock. 2003 Microchip Technology Inc. DS40039C-page 33 5.10. TIMER 1 193 PIC16F630/676 REGISTER 5-1: T1CON — TIMER1 CONTROL REGISTER (ADDRESS: 10h) U-0 — R/W-0 R/W-0 R/W-0 R/W-0 TMR1GE T1CKPS1 T1CKPS0 T1OSCEN R/W-0 R/W-0 R/W-0 T1SYNC TMR1CS TMR1ON bit 7 bit 0 bit 7 Unimplemented: Read as ‘0’ bit 6 TMR1GE: Timer1 Gate Enable bit If TMR1ON = 0: This bit is ignored If TMR1ON = 1: 1 = Timer1 is on if T1G pin is low 0 = Timer1 is on bit 5-4 T1CKPS1:T1CKPS0: Timer1 Input Clock Prescale Select bits 11 = 1:8 Prescale Value 10 = 1:4 Prescale Value 01 = 1:2 Prescale Value 00 = 1:1 Prescale Value bit 3 T1OSCEN: LP Oscillator Enable Control bit If INTOSC without CLKOUT oscillator is active: 1 = LP oscillator is enabled for Timer1 clock 0 = LP oscillator is off Else: This bit is ignored bit 2 T1SYNC: Timer1 External Clock Input Synchronization Control bit TMR1CS = 1: 1 = Do not synchronize external clock input 0 = Synchronize external clock input TMR1CS = 0: This bit is ignored. Timer1 uses the internal clock. bit 1 TMR1CS: Timer1 Clock Source Select bit 1 = External clock from T1OSO/T1CKI pin (on the rising edge) 0 = Internal clock (FOSC/4) bit 0 TMR1ON: Timer1 On bit 1 = Enables Timer1 0 = Stops Timer1 Legend: DS40039C-page 34 R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’ - n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknown 2003 Microchip Technology Inc. CHAPITRE 5. SPÉCIFICATIONS DU PIC16F676 DE MICROCHIP 194 PIC16F630/676 5.4 5.5 Timer1 Operation in Asynchronous Counter Mode If control bit T1SYNC (T1CON<2>) is set, the external clock input is not synchronized. The timer continues to increment asynchronous to the internal phase clocks. The timer will continue to run during SLEEP and can generate an interrupt on overflow, which will wake-up the processor. However, special precautions in software are needed to read/write the timer (Section 5.4.1). Note: 5.4.1 The ANSEL (9Fh) and CMCON (19h) registers must be initialized to configure an analog channel as a digital input. Pins configured as analog inputs will read ‘0’. The ANSEL register is defined for the PIC16F676. The Timer1 oscillator is shared with the system LP oscillator. Thus, Timer1 can use this mode only when the system clock is derived from the internal oscillator. As with the system LP oscillator, the user must provide a software time delay to ensure proper oscillator start-up. TRISA5 and TRISA4 bits are set when the Timer1 oscillator is enabled. RA5 and RA4 read as ‘0’ and TRISA5 and TRISA4 bits read as ‘1’. Note: Reading TMR1H or TMR1L, while the timer is running from an external asynchronous clock, will ensure a valid read (taken care of in hardware). However, the user should keep in mind that reading the 16-bit timer in two 8-bit values itself, poses certain problems, since the timer may overflow between the reads. For writes, it is recommended that the user simply stop the timer and write the desired values. A write contention may occur by writing to the timer registers, while the register is incrementing. This may produce an unpredictable value in the timer register. Reading the 16-bit value requires some care. Examples 12-2 and 12-3 in the PICmicro™ Mid-Range MCU Family Reference Manual (DS33023) show how to read and write Timer1 when it is running in Asynchronous mode. Address A crystal oscillator circuit is built-in between pins OSC1 (input) and OSC2 (amplifier output). It is enabled by setting control bit T1OSCEN (T1CON<3>). The oscillator is a low power oscillator rated up to 32 kHz. It will continue to run during SLEEP. It is primarily intended for a 32 kHz crystal. Table 9-2 shows the capacitor selection for the Timer1 oscillator. READING AND WRITING TIMER1 IN ASYNCHRONOUS COUNTER MODE TABLE 5-1: Name Timer1 Oscillator 5.6 The oscillator requires a start-up and stabilization time before use. Thus, T1OSCEN should be set and a suitable delay observed prior to enabling Timer1. Timer1 Operation During SLEEP Timer1 can only operate during SLEEP when setup in Asynchronous Counter mode. In this mode, an external crystal or clock source can be used to increment the counter. To setup the timer to wake the device: • Timer1 must be on (T1CON<0>) • TMR1IE bit (PIE1<0>) must be set • PEIE bit (INTCON<6>) must be set The device will wake-up on an overflow. If the GIE bit (INTCON<7>) is set, the device will wake-up and jump to the Interrupt Service Routine on an overflow. REGISTERS ASSOCIATED WITH TIMER1 AS A TIMER/COUNTER Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 0Bh/8Bh INTCON GIE PEIE T0IE INTE RAIE T0IF INTF 0Ch EEIF ADIF — — CMIF — — PIR1 Value on all other RESETS Bit 0 Value on POR, BOD RAIF 0000 0000 0000 000u TMR1IF 00-- 0--0 00-- 0--0 0Eh TMR1L Holding Register for the Least Significant Byte of the 16-bit TMR1 Register xxxx xxxx uuuu uuuu 0Fh TMR1H Holding Register for the Most Significant Byte of the 16-bit TMR1 Register xxxx xxxx uuuu uuuu — TMR1GE T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON -000 0000 -uuu uuuu 10h T1CON 8Ch PIE1 Legend: x = unknown, u = unchanged, - = unimplemented, read as '0'. Shaded cells are not used by the Timer1 module. EEIE ADIE 2003 Microchip Technology Inc. — — CMIE — — TMR1IE 00-- 0--0 00-- 0--0 DS40039C-page 35 5.11. COMPARATEUR 195 5.11 Comparateur PIC16F630/676 6.0 COMPARATOR MODULE Voltage Reference that can also be applied to an input of the comparator. In addition, RA2 can be configured as the comparator output. The Comparator Control Register (CMCON), shown in Register 6-1, contains the bits to control the comparator. The PIC16F630/676 devices have one analog comparator. The inputs to the comparator are multiplexed with the RA0 and RA1 pins. There is an on-chip Comparator REGISTER 6-1: CMCON — COMPARATOR CONTROL REGISTER (ADDRESS: 19h) U-0 R-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 — COUT — CINV CIS CM2 CM1 CM0 bit 7 bit 0 bit 7 Unimplemented: Read as ‘0’ bit 6 COUT: Comparator Output bit When CINV = 0: 1 = VIN+ > VIN0 = VIN+ < VINWhen CINV = 1: 1 = VIN+ < VIN0 = VIN+ > VIN- bit 5 Unimplemented: Read as ‘0’ bit 4 CINV: Comparator Output Inversion bit 1 = Output inverted 0 = Output not inverted bit 3 CIS: Comparator Input Switch bit When CM2:CM0 = 110 or 101: 1 = VIN- connects to CIN+ 0 = VIN- connects to CIN- bit 2-0 CM2:CM0: Comparator Mode bits Figure 6-2 shows the Comparator modes and CM2:CM0 bit settings Legend: R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’ - n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared 2003 Microchip Technology Inc. x = Bit is unknown DS40039C-page 37 CHAPITRE 5. SPÉCIFICATIONS DU PIC16F676 DE MICROCHIP 196 PIC16F630/676 6.1 Comparator Operation A single comparator is shown in Figure 6-1, along with the relationship between the analog input levels and the digital output. When the analog input at VIN+ is less than the analog input VIN-, the output of the comparator is a digital low level. When the analog input at VIN+ is greater than the analog input VIN-, the output of the comparator is a digital high level. The shaded areas of the output of the comparator in Figure 6-1 represent the uncertainty due to input offsets and response time. Note: To use CIN+ and CIN- pins as analog inputs, the appropriate bits must be programmed in the CMCON (19h) register. The polarity of the comparator output can be inverted by setting the CINV bit (CMCON<4>). Clearing CINV results in a non-inverted output. A complete table showing the output state versus input conditions and the polarity bit is shown in Table 6-1. TABLE 6-1: OUTPUT STATE VS. INPUT CONDITIONS Input Conditions CINV VIN- > VIN+ 0 0 VIN- < VIN+ 0 1 VIN- > VIN+ 1 1 VIN- < VIN+ 1 0 FIGURE 6-1: COUT SINGLE COMPARATOR VIN+ + VIN- – Output VINVIN+ Output Note: DS40039C-page 38 CINV bit (CMCON<4>) is clear. 2003 Microchip Technology Inc. 5.11. COMPARATEUR 197 PIC16F630/676 6.2 Comparator Configuration There are eight modes of operation for the comparator. The CMCON register, shown in Register 6-1, is used to select the mode. Figure 6-2 shows the eight possible modes. The TRISA register controls the data direction of the comparator pins for each mode. If the FIGURE 6-2: Comparator mode is changed, the comparator output level may not be valid for a specified period of time. Refer to the specifications in Section 12.0. Note: Comparator interrupts should be disabled during a Comparator mode change. Otherwise, a false interrupt may occur. COMPARATOR I/O OPERATING MODES Comparator Reset (POR Default Value - low power) Comparator Off (Lowest power) CM2:CM0 = 000 CM2:CM0 = 111 RA1/CIN- A RA0/CIN+ A RA2/COUT D Off (Read as '0') RA1/CIN- D RA0/CIN+ D RA2/COUT D Off (Read as '0') Comparator without Output Comparator w/o Output and with Internal Reference CM2:CM0 = 010 CM2:CM0 = 100 RA1/CIN- A RA0/CIN+ A RA2/COUT D COUT RA1/CIN- A RA0/CIN+ D RA2/COUT D COUT From CVREF Module Comparator with Output and Internal Reference Multiplexed Input with Internal Reference and Output CM2:CM0 = 011 CM2:CM0 = 101 RA1/CIN- A RA0/CIN+ D RA2/COUT D COUT RA1/CIN- A RA0/CIN+ A RA2/COUT D CIS = 0 CIS = 1 COUT From CVREF Module From CVREF Module Comparator with Output Multiplexed Input with Internal Reference CM2:CM0 = 001 CM2:CM0 = 110 RA1/CIN- A RA0/CIN+ A RA2/COUT D COUT RA1/CIN- A RA0/CIN+ A RA2/COUT D CIS = 0 CIS = 1 COUT From CVREF Module A = Analog Input, ports always reads ‘0’ D = Digital Input CIS = Comparator Input Switch (CMCON<3>) 2003 Microchip Technology Inc. DS40039C-page 39 CHAPITRE 5. SPÉCIFICATIONS DU PIC16F676 DE MICROCHIP 198 PIC16F630/676 6.3 Analog Input Connection Considerations range by more than 0.6V in either direction, one of the diodes is forward biased and a latchup may occur. A maximum source impedance of 10 kΩ is recommended for the analog sources. Any external component connected to an analog input pin, such as a capacitor or a Zener diode, should have very little leakage current. A simplified circuit for an analog input is shown in Figure 6-3. Since the analog pins are connected to a digital output, they have reverse biased diodes to VDD and VSS. The analog input, therefore, must be between VSS and VDD. If the input voltage deviates from this FIGURE 6-3: ANALOG INPUT MODE VDD VT = 0.6V Rs < 10K RIC AIN CPIN 5 pF VA Legend: 6.4 CPIN VT ILEAKAGE RIC RS VA VT = 0.6V Leakage ±500 nA Vss = Input Capacitance = Threshold Voltage = Leakage Current at the pin due to Various Junctions = Interconnect Resistance = Source Impedance = Analog Voltage Comparator Output The TRISA<2> bit functions as an output enable/ disable for the RA2 pin while the comparator is in an Output mode. The comparator output, COUT, is read through the CMCON register. This bit is read-only. The comparator output may also be directly output to the RA2 pin in three of the eight possible modes, as shown in Figure 6-2. When in one of these modes, the output on RA2 is asynchronous to the internal clock. Figure 6-4 shows the comparator output block diagram. Note 1: When reading the PORTA register, all pins configured as analog inputs will read as a ‘0’. Pins configured as digital inputs will convert an analog input according to the TTL input specification. 2: Analog levels on any pin that is defined as a digital input, may cause the input buffer to consume more current than is specified. FIGURE 6-4: MODIFIED COMPARATOR OUTPUT BLOCK DIAGRAM RA0/CIN+ RA1/CIN- To RA2/T0CKI pin To Data Bus Q RD CMCON Set CMIF bit CVREF D EN Q CINV CM2:CM0 D RD CMCON EN RESET DS40039C-page 40 2003 Microchip Technology Inc. 5.11. COMPARATEUR 199 PIC16F630/676 6.5 Comparator Reference The following equations determine the output voltages: The comparator module also allows the selection of an internally generated voltage reference for one of the comparator inputs. The internal reference signal is used for four of the eight Comparator modes. The VRCON register, Register 6-2, controls the voltage reference module shown in Figure 6-5. VRR = 1 (low range): CVREF = (VR3:VR0 / 24) x VDD 6.5.1 The full range of VSS to VDD cannot be realized due to the construction of the module. The transistors on the top and bottom of the resistor ladder network (Figure 6-5) keep CVREF from approaching VSS or VDD. The Voltage Reference is VDD derived and therefore, the CVREF output changes with fluctuations in VDD. The tested absolute accuracy of the Comparator Voltage Reference can be found in Section 12.0. CONFIGURING THE VOLTAGE REFERENCE The voltage reference can output 32 distinct voltage levels, 16 in a high range and 16 in a low range. FIGURE 6-5: VRR = 0 (high range): CVREF = (VDD / 4) + (VR3:VR0 x VDD / 32) 6.5.2 VOLTAGE REFERENCE ACCURACY/ERROR COMPARATOR VOLTAGE REFERENCE BLOCK DIAGRAM 16 Stages 8R R R R R VDD 8R VRR 16-1 Analog MUX VREN CVREF to Comparator Input VR3:VR0 6.6 Comparator Response Time Response time is the minimum time, after selecting a new reference voltage or input source, before the comparator output is ensured to have a valid level. If the internal reference is changed, the maximum delay of the internal voltage reference must be considered when using the comparator outputs. Otherwise, the maximum delay of the comparators should be used (Table 12-7). 6.7 Operation During SLEEP Both the comparator and voltage reference, if enabled before entering SLEEP mode, remain active during SLEEP. This results in higher SLEEP currents than shown in the power-down specifications. The additional current consumed by the comparator and the voltage reference is shown separately in the specifications. To minimize power consumption while in SLEEP mode, turn off the comparator, CM2:CM0 = 111, and voltage reference, VRCON<7> = 0. 2003 Microchip Technology Inc. While the comparator is enabled during SLEEP, an interrupt will wake-up the device. If the device wakes up from SLEEP, the contents of the CMCON and VRCON registers are not affected. 6.8 Effects of a RESET A device RESET forces the CMCON and VRCON registers to their RESET states. This forces the comparator module to be in the Comparator Reset mode, CM2:CM0 = 000 and the voltage reference to its off state. Thus, all potential inputs are analog inputs with the comparator and voltage reference disabled to consume the smallest current possible. DS40039C-page 41 CHAPITRE 5. SPÉCIFICATIONS DU PIC16F676 DE MICROCHIP 200 PIC16F630/676 REGISTER 6-2: VRCON — VOLTAGE REFERENCE CONTROL REGISTER (ADDRESS: 99h) R/W-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 VREN — VRR — VR3 VR2 VR1 VR0 bit 7 bit 7 bit 0 VREN: CVREF Enable bit 1 = CVREF circuit powered on 0 = CVREF circuit powered down, no IDD drain bit 6 Unimplemented: Read as '0' bit 5 VRR: CVREF Range Selection bit 1 = Low range 0 = High range bit 4 Unimplemented: Read as '0' bit 3-0 VR3:VR0: CVREF value selection 0 ≤ VR [3:0] ≤ 15 When VRR = 1: CVREF = (VR3:VR0 / 24) * VDD When VRR = 0: CVREF = VDD/4 + (VR3:VR0 / 32) * VDD Legend: 6.9 R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’ - n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared Comparator Interrupts The user, in the Interrupt Service Routine, can clear the interrupt in the following manner: The comparator interrupt flag is set whenever there is a change in the output value of the comparator. Software will need to maintain information about the status of the output bits, as read from CMCON<6>, to determine the actual change that has occurred. The CMIF bit, PIR1<3>, is the comparator interrupt flag. This bit must be reset in software by clearing it to ‘0’. Since it is also possible to write a '1' to this register, a simulated interrupt may be initiated. a) b) Any read or write of CMCON. This will end the mismatch condition. Clear flag bit CMIF. A mismatch condition will continue to set flag bit CMIF. Reading CMCON will end the mismatch condition and allow flag bit CMIF to be cleared. Note: The CMIE bit (PIE1<3>) and the PEIE bit (INTCON<6>) must be set to enable the interrupt. In addition, the GIE bit must also be set. If any of these bits are cleared, the interrupt is not enabled, though the CMIF bit will still be set if an interrupt condition occurs. TABLE 6-2: Address If a change in the CMCON register (COUT) should occur when a read operation is being executed (start of the Q2 cycle), then the CMIF (PIR1<3>) interrupt flag may not get set. REGISTERS ASSOCIATED WITH COMPARATOR MODULE Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 0Bh/8Bh INTCON GIE PEIE T0IE INTE RAIE T0IF INTF 0Ch PIR1 EEIF ADIF — — CMIF — — 19h CMCON — COUT — CINV CIS CM2 CM1 8Ch PIE1 EEIE ADIE — — CMIE — — — — VREN — 85h TRISA 99h VRCON Legend: x = Bit is unknown TRISA5 TRISA4 VRR — TRISA3 TRISA2 VR3 VR2 Value on all other RESETS Bit 0 Value on POR, BOD RAIF 0000 0000 0000 000u TMR1IF 00-- 0--0 00-- 0--0 CM0 -0-0 0000 -0-0 0000 TMR1IE 00-- 0--0 00-- 0--0 TRISA1 TRISA0 --11 1111 --11 1111 VR1 VR0 0-0- 0000 0-0- 0000 x = unknown, u = unchanged, - = unimplemented, read as ‘0’. Shaded cells are not used by the comparator module. DS40039C-page 42 2003 Microchip Technology Inc. 5.12. CONVERTISSEUR ANALOGIQUE-NUMÉRIQUE 201 5.12 Convertisseur analogique-numérique PIC16F630/676 7.0 ANALOG-TO-DIGITAL CONVERTER (A/D) MODULE (PIC16F676 ONLY) The output of the sample and hold is connected to the input of the converter. The converter generates a binary result via successive approximation and stores the result in a 10-bit register. The voltage reference used in the conversion is software selectable to either VDD or a voltage applied by the VREF pin. Figure 7-1 shows the block diagram of the A/D on the PIC16F676. The analog-to-digital converter (A/D) allows conversion of an analog input signal to a 10-bit binary representation of that signal. The PIC16F676 has eight analog inputs, multiplexed into one sample and hold circuit. FIGURE 7-1: A/D BLOCK DIAGRAM VDD VCFG = 0 VREF VCFG = 1 RA0/AN0 RA1/AN1/VREF ADC RA2/AN2 10 GO/DONE RA4/AN3 RC0/AN4 ADFM RC1/AN5 10 ADON RC2/AN6 ADRESH RC3/AN7 ADRESL VSS CHS2:CHS0 7.1 A/D Configuration and Operation There are three registers available to control the functionality of the A/D module: 1. 2. 3. ADCON0 (Register 7-1) ADCON1 (Register 7-2) ANSEL (Register 7-3) 7.1.1 ANALOG PORT PINS The ANS7:ANS0 bits (ANSEL<7:0>) and the TRISA bits control the operation of the A/D port pins. Set the corresponding TRISA bits to set the pin output driver to its high impedance state. Likewise, set the corresponding ANS bit to disable the digital input buffer. Note: 7.1.2 Analog voltages on any pin that is defined as a digital input may cause the input buffer to conduct excess current. CHANNEL SELECTION There are eight analog channels on the PIC16F676, AN0 through AN7. The CHS2:CHS0 bits (ADCON0<4:2>) control which channel is connected to the sample and hold circuit. 2003 Microchip Technology Inc. 7.1.3 VOLTAGE REFERENCE There are two options for the voltage reference to the A/D converter: either VDD is used, or an analog voltage applied to VREF is used. The VCFG bit (ADCON0<6>) controls the voltage reference selection. If VCFG is set, then the voltage on the VREF pin is the reference; otherwise, VDD is the reference. 7.1.4 CONVERSION CLOCK The A/D conversion cycle requires 11 TAD. The source of the conversion clock is software selectable via the ADCS bits (ADCON1<6:4>). There are seven possible clock options: • • • • • • • FOSC/2 FOSC/4 FOSC/8 FOSC/16 FOSC/32 FOSC/64 FRC (dedicated internal oscillator) For correct conversion, the A/D conversion clock (1/TAD) must be selected to ensure a minimum TAD of 1.6 µs. Table 7-1 shows a few TAD calculations for selected frequencies. DS40039C-page 43 CHAPITRE 5. SPÉCIFICATIONS DU PIC16F676 DE MICROCHIP 202 PIC16F630/676 TABLE 7-1: TAD vs. DEVICE OPERATING FREQUENCIES A/D Clock Source (TAD) Device Frequency Operation ADCS2:ADCS0 20 MHz 5 MHz 4 MHz 1.25 MHz 2 TOSC 000 100 ns(2) 400 ns(2) 500 ns(2) 1.6 µs 4 TOSC 100 200 ns(2) 800 ns(2) 1.0 µs(2) 3.2 µs 400 ns(2) 1.6 µs 2.0 µs 6.4 µs 8 TOSC 001 800 ns(2) 3.2 µs 4.0 µs 12.8 µs(3) 16 TOSC 101 8.0 µs(3) 25.6 µs(3) 32 TOSC 010 1.6 µs 6.4 µs 64 TOSC 110 3.2 µs 12.8 µs(3) 16.0 µs(3) 51.2 µs(3) (1,4) (1,4) (1,4) A/D RC x11 2 - 6 µs 2 - 6 µs 2 - 6 µs 2 - 6 µs(1,4) Legend: Shaded cells are outside of recommended range. Note 1: The A/D RC source has a typical TAD time of 4 µs for VDD > 3.0V. 2: These values violate the minimum required TAD time. 3: For faster conversion times, the selection of another clock source is recommended. 4: When the device frequency is greater than 1 MHz, the A/D RC clock source is only recommended if the conversion will be performed during SLEEP. 7.1.5 STARTING A CONVERSION previous conversion. After an aborted conversion, a 2 TAD delay is required before another acquisition can be initiated. Following the delay, an input acquisition is automatically started on the selected channel. The A/D conversion is initiated by setting the GO/DONE bit (ADCON0<1>). When the conversion is complete, the A/D module: Note: • Clears the GO/DONE bit • Sets the ADIF flag (PIR1<6>) • Generates an interrupt (if enabled). 7.1.6 If the conversion must be aborted, the GO/DONE bit can be cleared in software. The ADRESH:ADRESL registers will not be updated with the partially complete A/D conversion sample. Instead, the ADRESH:ADRESL registers will retain the value of the FIGURE 7-2: The GO/DONE bit should not be set in the same instruction that turns on the A/D. CONVERSION OUTPUT The A/D conversion can be supplied in two formats: left or right shifted. The ADFM bit (ADCON0<7>) controls the output format. Figure 7-2 shows the output formats. 10-BIT A/D RESULT FORMAT ADRESH (ADFM = 0) ADRESL MSB LSB bit 7 bit 0 bit 7 10-bit A/D Result (ADFM = 1) Unimplemented: Read as ‘0’ MSB bit 7 Unimplemented: Read as ‘0 DS40039C-page 44 bit 0 LSB bit 0 bit 7 bit 0 10-bit A/D Result 2003 Microchip Technology Inc. 5.12. CONVERTISSEUR ANALOGIQUE-NUMÉRIQUE 203 PIC16F630/676 REGISTER 7-1: ADCON0 — A/D CONTROL REGISTER (ADDRESS: 1Fh) R/W-0 R/W-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 ADFM VCFG — CHS2 CHS1 CHS0 GO/DONE ADON bit 7 bit 0 bit 7 ADFM: A/D Result Formed Select bit 1 = Right justified 0 = Left justified bit 6 VCFG: Voltage Reference bit 1 = VREF pin 0 = VDD bit 5 Unimplemented: Read as zero bit 4-2 CHS2:CHS0: Analog Channel Select bits 000 =Channel 00 (AN0) 001 =Channel 01 (AN1) 010 =Channel 02 (AN2) 011 =Channel 03 (AN3) 100 =Channel 04 (AN4) 101 =Channel 05 (AN5) 110 =Channel 06 (AN6) 111 =Channel 07 (AN7) bit 1 GO/DONE: A/D Conversion STATUS bit 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: A/D Conversion STATUS bit 1 = A/D converter module is operating 0 = A/D converter is shut-off and consumes no operating current Legend: REGISTER 7-2: R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’ - n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknown ADCON1 — A/D CONTROL REGISTER 1 (ADRESS: 9Fh) U-0 R/W-0 R/W-0 R/W-0 U-0 U-0 U-0 U-0 — ADCS2 ADCS1 ADCS0 — — — — bit 7 bit 0 bit 7: Unimplemented: Read as ‘0’. bit 6-4: ADCS<2:0>: A/D Conversion Clock Select bits 000 = 001 = 010 = x11 = 100 = 101 = 110 = bit 3-0: FOSC/2 FOSC/8 FOSC/32 FRC (clock derived from a dedicated internal oscillator = 500 kHz max) FOSC/4 FOSC/16 FOSC/64 Unimplemented: Read as ‘0’. Legend: R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’ - n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared 2003 Microchip Technology Inc. x = Bit is unknown DS40039C-page 45 CHAPITRE 5. SPÉCIFICATIONS DU PIC16F676 DE MICROCHIP 204 PIC16F630/676 REGISTER 7-3: ANSEL — ANALOG SELECT REGISTER (ADRESS: 91h) (PIC16F676 ONLY) R/W-1 R/W-1 R/W-1 R/W-1 R/W-1 R/W-1 R/W-1 R/W-1 ANS7 ANS6 ANS5 ANS4 ANS3 ANS2 ANS1 ANS0 bit 7 bit 7-0: bit 0 ANS<7:0>: Analog Select between analog or digital function on pins AN<7:0>, respectively. 1 = Analog input. Pin is assigned as analog input.(1) 0 = Digital I/O. Pin is assigned to port or special function. Note 1: Setting a pin to an analog input automatically disables the digital input circuitry, weak pull-ups, and interrupt-on-change if available. The corresponding TRIS bit must be set to Input mode in order to allow external control of the voltage on the pin. Legend: DS40039C-page 46 R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’ - n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknown 2003 Microchip Technology Inc. 5.12. CONVERTISSEUR ANALOGIQUE-NUMÉRIQUE 205 PIC16F630/676 7.3 A/D Operation During SLEEP The A/D converter module can operate during SLEEP. This requires the A/D clock source to be set to the internal oscillator. When the RC clock source is selected, the A/D waits one instruction before starting the conversion. This allows the SLEEP instruction to be executed, thus eliminating much of the switching noise from the conversion. When the conversion is complete, the GO/DONE bit is cleared, and the result is loaded into the ADRESH:ADRESL registers. If the A/D interrupt is enabled, the device awakens from SLEEP. If the A/D interrupt is not enabled, the A/D module is turned off, although the ADON bit remains set. TABLE 7-2: Address When the A/D clock source is something other than RC, a SLEEP instruction causes the present conversion to be aborted, and the A/D module is turned off. The ADON bit remains set. 7.4 Effects of RESET A device RESET forces all registers to their RESET state. Thus, the A/D module is turned off and any pending conversion is aborted. The ADRESH:ADRESL registers are unchanged. SUMMARY OF A/D REGISTERS Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Value on: POR, BOD Value on all other RESETS 05h PORTA — — PORTA5 PORTA4 PORTA3 PORTA2 PORTA1 PORTA0 --xx xxxx --uu uuuu 07h PORTC — — PORTC5 PORTC4 PORTC3 PORTC2 PORTC1 PORTC0 --xx xxxx --uu uuuu 0Bh, 8Bh INTCON GIE PEIE T0IE INTE RAIE T0IF INTF 0Ch PIR1 EEIF ADIF — — CMIF — — RAIF 0000 0000 0000 000u TMR1IF 00-- 0--0 00-- 0--0 1Eh ADRESH Most Significant 8 bits of the Left Shifted A/D result or 2 bits of the Right Shifted Result xxxx xxxx uuuu uuuu 1Fh ADCON0 00-0 0000 00-0 0000 85h TRISA 87h TRISC 8Ch PIE1 91h ANSEL ANS7 ANS0 1111 1111 1111 1111 9Eh ADRESL Least Significant 2 bits of the Left Shifted A/D Result or 8 bits of the Right Shifted Result xxxx xxxx uuuu uuuu 9Fh ADCON1 ADFM VCFG — CHS2 CHS1 CHS0 GO — — TRISA5 TRISA4 TRISA3 TRISA2 TRISA1 — — TRISC5 TRISC4 TRISC3 TRISC2 TRISC1 TRISC0 --11 1111 --11 1111 EEIE ADIE — — CMIE — — TMR1IE 00-- 0--0 00-- 0--0 ANS6 ANS5 ANS4 ANS3 ANS2 ANS1 — ADCS2 ADCS1 ADCS0 — — — ADON TRISA0 --11 1111 --11 1111 — -000 ---- -000 ---- Legend: x = unknown, u = unchanged, - = unimplemented read as '0'. Shaded cells are not used for A/D converter module. DS40039C-page 48 2003 Microchip Technology Inc. CHAPITRE 5. SPÉCIFICATIONS DU PIC16F676 DE MICROCHIP 206 5.13 Interruptions PIC16F630/676 9.4 Interrupts The PIC16F630/676 has 7 sources of interrupt: • • • • • • • External Interrupt RA2/INT TMR0 Overflow Interrupt PORTA Change Interrupts Comparator Interrupt A/D Interrupt (PIC16F676 only) TMR1 Overflow Interrupt EEPROM Data Write Interrupt The Interrupt Control register (INTCON) and Peripheral Interrupt register (PIR) record individual interrupt requests in flag bits. The INTCON register also has individual and global interrupt enable bits. interrupt flag bit(s) must be cleared in software before re-enabling interrupts to avoid multiple interrupt requests. Note 1: Individual interrupt flag bits are set, regardless of the status of their corresponding mask bit or the GIE bit. 2: When an instruction that clears the GIE bit is executed, any interrupts that were pending for execution in the next cycle are ignored. The interrupts which were ignored are still pending to be serviced when the GIE bit is set again. A global interrupt enable bit, GIE (INTCON<7>) enables (if set) all unmasked interrupts, or disables (if cleared) all interrupts. Individual interrupts can be disabled through their corresponding enable bits in INTCON register and PIE register. GIE is cleared on RESET. The return from interrupt instruction, RETFIE, exits interrupt routine, as well as sets the GIE bit, which reenables unmasked interrupts. The following interrupt flags are contained in the INTCON register: • INT pin interrupt • PORTA change interrupt • TMR0 overflow interrupt The peripheral interrupt flags are contained in the special register PIR1. The corresponding interrupt enable bit is contained in Special Register PIE1. The following interrupt flags are contained in the PIR register: • • • • EEPROM data write interrupt A/D interrupt Comparator interrupt Timer1 overflow interrupt When an interrupt is serviced: • The GIE is cleared to disable any further interrupt • The return address is pushed onto the stack • The PC is loaded with 0004h Once in the Interrupt Service Routine, the source(s) of the interrupt can be determined by polling the interrupt flag bits. The interrupt flag bit(s) must be cleared in software before re-enabling interrupts to avoid RA2/INT recursive interrupts. For external interrupt events, such as the INT pin, or PORTA change interrupt, the interrupt latency will be three or four instruction cycles. The exact latency depends upon when the interrupt event occurs (see Figure 9-11). The latency is the same for one or twocycle instructions. Once in the Interrupt Service Routine, the source(s) of the interrupt can be determined by polling the interrupt flag bits. The 2003 Microchip Technology Inc. DS40039C-page 63 5.13. INTERRUPTIONS 207 PIC16F630/676 FIGURE 9-10: INTERRUPT LOGIC IOCA-RA0 IOCA0 IOCA-RA1 IOCA1 IOCA-RA2 IOCA2 IOCA-RA3 IOCA3 IOCA-RA4 IOCA4 IOCA-RA5 IOCA5 TMR1IF TMR1IE CMIF CMIE ADIF ADIE T0IF T0IE Wake-up (If in SLEEP mode) INTF INTE RAIF RAIE Interrupt to CPU PEIE (1) GIE EEIF EEIE Note 1: PIC16F676 only. DS40039C-page 64 2003 Microchip Technology Inc. CHAPITRE 5. SPÉCIFICATIONS DU PIC16F676 DE MICROCHIP 208 PIC16F630/676 9.4.1 9.4.2 RA2/INT INTERRUPT An overflow (FFh → 00h) in the TMR0 register will set the T0IF (INTCON<2>) bit. The interrupt can be enabled/disabled by setting/clearing T0IE (INTCON<5>) bit. For operation of the Timer0 module, see Section 4.0. External interrupt on RA2/INT pin is edge-triggered; either rising if INTEDG bit (OPTION<6>) is set, or falling, if INTEDG bit is clear. When a valid edge appears on the RA2/INT pin, the INTF bit (INTCON<1>) is set. This interrupt can be disabled by clearing the INTE control bit (INTCON<4>). The INTF bit must be cleared in software in the Interrupt Service Routine before re-enabling this interrupt. The RA2/INT interrupt can wake-up the processor from SLEEP if the INTE bit was set prior to going into SLEEP. The status of the GIE bit decides whether or not the processor branches to the interrupt vector following wake-up. See Section 9.7 for details on SLEEP and Figure 9-13 for timing of wake-up from SLEEP through RA2/INT interrupt. Note: TMR0 INTERRUPT 9.4.3 PORTA INTERRUPT An input change on PORTA change sets the RAIF (INTCON<0>) bit. The interrupt can be enabled/ disabled by setting/clearing the RAIE (INTCON<3>) bit. Plus individual pins can be configured through the IOCA register. Note: The ANSEL 9Fh) and CMCON (19h) registers must be initialized to configure an analog channel as a digital input. Pins configured as analog inputs will read ‘0’. The ANSEL register is defined for the PIC16F676. If a change on the I/O pin should occur when the read operation is being executed (start of the Q2 cycle), then the RAIF interrupt flag may not get set. 9.4.4 COMPARATOR INTERRUPT See Section 6.9 for description of comparator interrupt. 9.4.5 A/D CONVERTER INTERRUPT After a conversion is complete, the ADIF flag (PIR<6>) is set. The interrupt can be enabled/disabled by setting or clearing ADIE (PIE<6>). See Section 7.0 for operation of the A/D converter interrupt. FIGURE 9-11: INT PIN INTERRUPT TIMING Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 OSC1 CLKOUT 3 4 INT pin 1 1 INTF Flag (INTCON<1>) Interrupt Latency 2 5 GIE bit (INTCON<7>) INSTRUCTION FLOW PC PC Instruction Fetched Inst (PC) Instruction Executed Inst (PC-1) PC+1 Inst (PC+1) Inst (PC) PC+1 — Dummy Cycle 0004h 0005h Inst (0004h) Inst (0005h) Dummy Cycle Inst (0004h) Note 1: INTF flag is sampled here (every Q1). 2: Asynchronous interrupt latency = 3-4 TCY. Synchronous latency = 3 TCY, where TCY = instruction cycle time. Latency is the same whether Inst (PC) is a single cycle or a 2-cycle instruction. 3: CLKOUT is available only in RC Oscillator mode. 4: For minimum width of INT pulse, refer to AC specs. 5: INTF is enabled to be set any time during the Q4-Q1 cycles. 2003 Microchip Technology Inc. DS40039C-page 65 5.13. INTERRUPTIONS 209 PIC16F630/676 TABLE 9-8: Address SUMMARY OF INTERRUPT REGISTERS Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 0Bh, 8Bh INTCON GIE PEIE T0IE INTE RAIE T0IF INTF 0Ch 8Ch EEIF EEIE ADIF ADIE — — — — CMIF CMIE — — — — PIR1 PIE1 Value on all other RESETS Bit 0 Value on POR, BOD RAIF 0000 0000 0000 000u TMR1IF 00-- 0--0 00-- 0--0 TMR1IE 00-- 0--0 00-- 0--0 Legend: x = unknown, u = unchanged, - = unimplemented read as '0', q = value depends upon condition. Shaded cells are not used by the Interrupt module. 9.5 Context Saving During Interrupts During an interrupt, only the return PC value is saved on the stack. Typically, users may wish to save key registers during an interrupt (e.g., W register and STATUS register). This must be implemented in software. Example 9-2 stores and restores the STATUS and W registers. The user register, W_TEMP, must be defined in both banks and must be defined at the same offset from the bank base address (i.e., W_TEMP is defined at 0x20 in Bank 0 and it must also be defined at 0xA0 in Bank 1). The user register, STATUS_TEMP, must be defined in Bank 0. The Example 9-2: • • • • Stores the W register Stores the STATUS register in Bank 0 Executes the ISR code Restores the STATUS (and bank select bit register) • Restores the W register EXAMPLE 9-2: MOVWF W_TEMP SWAPF BCF STATUS,W STATUS,RP0 SAVING THE STATUS AND W REGISTERS IN RAM ;copy W to temp register, could be in either bank ;swap status to be saved into W ;change to bank 0 regardless of current bank ;save status to bank 0 register MOVWF STATUS_TEMP : :(ISR) : SWAPF STATUS_TEMP,W;swap STATUS_TEMP register into W, sets bank to original state MOVWF STATUS ;move W into STATUS register SWAPF W_TEMP,F ;swap W_TEMP SWAPF W_TEMP,W ;swap W_TEMP into W DS40039C-page 66 9.6 Watchdog Timer (WDT) The Watchdog Timer is a free running, on-chip RC oscillator, which requires no external components. This RC oscillator is separate from the external RC oscillator of the CLKIN pin. That means that the WDT will run, even if the clock on the OSC1 and OSC2 pins of the device has been stopped (for example, by execution of a SLEEP instruction). During normal operation, a WDT time-out generates a device RESET. If the device is in SLEEP mode, a WDT time-out causes the device to wake-up and continue with normal operation. The WDT can be permanently disabled by programming the configuration bit WDTE as clear (Section 9.1). 9.6.1 WDT PERIOD The WDT has a nominal time-out period of 18 ms, (with no prescaler). The time-out periods vary with temperature, VDD and process variations from part to part (see DC specs). If longer time-out periods are desired, a prescaler with a division ratio of up to 1:128 can be assigned to the WDT under software control by writing to the OPTION register. Thus, time-out periods up to 2.3 seconds can be realized. The CLRWDT and SLEEP instructions clear the WDT and the prescaler, if assigned to the WDT, and prevent it from timing out and generating a device RESET. The TO bit in the STATUS register will be cleared upon a Watchdog Timer time-out. 9.6.2 WDT PROGRAMMING CONSIDERATIONS It should also be taken in account that under worst case conditions (i.e., VDD = Min., Temperature = Max., Max. WDT prescaler) it may take several seconds before a WDT time-out occurs. 2003 Microchip Technology Inc. CHAPITRE 5. SPÉCIFICATIONS DU PIC16F676 DE MICROCHIP 210 5.14 Résumé du jeu d’instructions PIC16F630/676 10.0 INSTRUCTION SET SUMMARY The PIC16F630/676 instruction set is highly orthogonal and is comprised of three basic categories: For example, a CLRF PORTA instruction will read PORTA, clear all the data bits, then write the result back to PORTA. This example would have the unintended result of clearing the condition that set the RAIF flag. • Byte-oriented operations • Bit-oriented operations TABLE 10-1: • Literal and control operations Each PIC16 instruction is a 14-bit word divided into an opcode, which specifies the instruction type, and one or more operands, which further specify the operation of the instruction. The formats for each of the categories is presented in Figure 10-1, while the various opcode fields are summarized in Table 10-1. OPCODE FIELD DESCRIPTIONS Field Description f Register file address (0x00 to 0x7F) W Working register (accumulator) b Bit address within an 8-bit file register k Literal field, constant data or label Table 10-2 lists the instructions recognized by the MPASMTM assembler. A complete description of each instruction is also available in the PICmicro™ MidRange Reference Manual (DS33023). x Don't care location (= 0 or 1). The assembler will generate code with x = 0. It is the recommended form of use for compatibility with all Microchip software tools. For byte-oriented instructions, ‘f’ represents a file register designator and ‘d’ represents a destination designator. The file register designator specifies which file register is to be used by the instruction. d Destination select; d = 0: store result in W, d = 1: store result in file register f. Default is d = 1. PC Program Counter The destination designator specifies where the result of the operation is to be placed. If ‘d’ is zero, the result is placed in the W register. If ‘d’ is one, the result is placed in the file register specified in the instruction. TO Time-out bit PD Power-down bit For bit-oriented instructions, ‘b’ represents a bit field designator, which selects the bit affected by the operation, while ‘f’ represents the address of the file in which the bit is located. For literal and control operations, ‘k’ represents an 8-bit or 11-bit constant, or literal value One instruction cycle consists of four oscillator periods; for an oscillator frequency of 4 MHz, this gives a normal instruction execution time of 1 µs. All instructions are executed within a single instruction cycle, unless a conditional test is true, or the program counter is changed as a result of an instruction. When this occurs, the execution takes two instruction cycles, with the second cycle executed as a NOP. Note: To maintain upward compatibility with future products, do not use the OPTION and TRIS instructions. All instruction examples use the format ‘0xhh’ to represent a hexadecimal number, where ‘h’ signifies a hexadecimal digit. 10.1 READ-MODIFY-WRITE OPERATIONS Any instruction that specifies a file register as part of the instruction performs a Read-Modify-Write (R-M-W) operation. The register is read, the data is modified, and the result is stored according to either the instruction, or the destination designator ‘d’. A read operation is performed on a register even if the instruction writes to that register. 2003 Microchip Technology Inc. FIGURE 10-1: GENERAL FORMAT FOR INSTRUCTIONS Byte-oriented file register operations 13 8 7 6 OPCODE d f (FILE #) 0 d = 0 for destination W d = 1 for destination f f = 7-bit file register address Bit-oriented file register operations 13 10 9 7 6 0 OPCODE b (BIT #) f (FILE #) b = 3-bit bit address f = 7-bit file register address Literal and control operations General 13 8 7 OPCODE 0 k (literal) k = 8-bit immediate value CALL and GOTO instructions only 13 11 OPCODE 10 0 k (literal) k = 11-bit immediate value DS40039C-page 71 5.14. RÉSUMÉ DU JEU D’INSTRUCTIONS 211 PIC16F630/676 TABLE 10-2: PIC16F630/676 INSTRUCTION SET Mnemonic, Operands 14-Bit Opcode Description Cycles MSb LSb Status Affected Notes BYTE-ORIENTED FILE REGISTER OPERATIONS ADDWF ANDWF CLRF CLRW COMF DECF DECFSZ INCF INCFSZ IORWF MOVF MOVWF NOP RLF RRF SUBWF SWAPF XORWF 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 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 1 1 1 1 1 1 1(2) 1 1(2) 1 1 1 1 1 1 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 ffff ffff ffff xxxx ffff ffff ffff ffff ffff ffff ffff ffff 0000 ffff ffff ffff ffff ffff 00bb 01bb 10bb 11bb bfff bfff bfff bfff ffff ffff ffff ffff 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 C,DC,Z Z Z Z Z Z Z Z Z C C C,DC,Z Z 1,2 1,2 2 1,2 1,2 1,2,3 1,2 1,2,3 1,2 1,2 1,2 1,2 1,2 1,2 1,2 BIT-ORIENTED FILE REGISTER OPERATIONS BCF BSF BTFSC BTFSS f, b f, b f, b f, b Bit Clear f Bit Set f Bit Test f, Skip if Clear Bit Test f, Skip if Set 1 1 1 (2) 1 (2) 01 01 01 01 1,2 1,2 3 3 LITERAL AND CONTROL OPERATIONS ADDLW ANDLW CALL CLRWDT GOTO IORLW MOVLW RETFIE RETLW RETURN SLEEP SUBLW XORLW k k k k k k k k 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 1 1 2 1 2 1 1 2 2 2 1 1 1 11 11 10 00 10 11 11 00 11 00 00 11 11 C,DC,Z Z TO,PD Z TO,PD C,DC,Z Z Note 1: When an I/O register is modified as a function of itself (e.g., MOVF PORTA, 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. Note: Additional information on the mid-range instruction set is available in the PICmicro™ Mid-Range MCU Family Reference Manual (DS33023). DS40039C-page 72 2003 Microchip Technology Inc.