De la programmation en langage machine, à la
Transcription
De la programmation en langage machine, à la
IUFM de TOULOUSE – DEPARTEMENT GENIE ELECTRONIQUE De la programmation en langage machine, à la programmation graphique De l’assembleur 68HC11 à la synthèse fonctionnelle de REALIZER 0.\. Du microcontrôleur 68HC11 à l’architecture HARVARD des PIC de Microchip I.\. Réalisation d’un chenillard, synthétisé en langage machine ou assembleur dédié 68HC11 II.\. Réalisation du chenillard par symbolisme graphique (REALIZER BRONZE-GOLD) III.\. Introduction à la programmation graphique de REALIZER III.\.1 Mise en œuvre partielle de la synthèse schématique de REALIZER III.\.2 Symboles utilisés dans les exemples IV.\. Architecture du microcontrôleur cible, le PIC16F83 Didier PEYTAVI Généralités sur l’architecture des PIC L’architecture interne de la plupart des microcontrôleurs et microprocesseurs est organisée selon une structure dite de VON NEUMANN. La mémoire de programme contient les instructions et les données stockées les unes à la suite des autres ; c’est le bus de donnée seul, qui véhicule les codes des instructions et les données. Cette structure présente des problèmes dès lors que l’on souhaite augmenter la fréquence de fonctionnement de l’ensemble ; l’exécution d’une seule instruction demande plusieurs opérations sur le bus de données puisqu’il faut aller chercher le code opération de l’instruction à exécuter puis la ou les données qu’elle doit manipuler. Aussi préfèrerons nous faire appel à une structure de type HARVARD ou les instructions et les données sont manipulées sur des bus différents. L’utilisation de ces deux bus est transparente vis à vis de l’utilisateur et les vitesses d’exécutions obtenues sont remarquables. L’exécution d’une instruction ne fait plus alors appel qu’à un seul cycle machine puisque l’on peut simultanément grâce aux deux bus de données et d’instructions, rechercher le code opération de l’instruction et la ou les données manipulées. Les microcontrôleurs PIC de Microchip adoptent une structure interne de type HARVARD mais font également appel à une architecture RISC (reduced instruction set computer) signifiant entre autre « processeur à jeu d’instructions réduit ». L’objectif d’une architecture RISC étant l’augmentation de la vitesse de fonctionnement, un certain nombre de particularités doivent êtres prises en considération : - Les microcontrôleurs à architecture RISC utilisent des instructions codées sur 14 bits (cas du PIC 16F83) ; chaque emplacement de la mémoire de programme contient une instruction (x mots de 14 bits) et un seul cycle machine est nécessaire pour assurer la lecture du code de l’instruction, d’ou une vitesse de fonctionnement accrue. - Les circuits RISC utilisent une structure de type pipe-line permettant d’exécuter une instruction tout en recherchant la suivante en mémoire. - Sur les chronogrammes ci-après, le compteur programme est augmenté d’une unité à chaque cycle Q1, alors que les instructions sont recherchées en mémoire de programme et mémorisée dans le registre d’instructions à chaque cycle Q4 ; une instruction s’exécute donc alors que la suivante est en cours de recherche, c’est le propre de la structure pipe-line. - Toutes les instructions dans une architecture RISC sont exécutées en un seul cycle machine, l’ALU disposant en une seule fois de toutes les informations nécessaires à l’exécution de l’instruction. - Les instructions d’un circuit de type RISC peuvent être exécutées sur tous les registres avec tous les modes d’adressage ; il n’est donc pas nécessaire de retenir toutes les configurations particulières d’adressage. - Pour terminer, une architecture RISC ne fait appel qu’à un jeu d’instructions réduit (33 ou 35 instructions). La famille des PIC 16Cxxx Les PIC se destinent aux applications à base de microcontrôleurs ; ces boîtiers à taille réduite sont caractérisés par un niveau d’intégration élevé leur permettant de se passer de tout circuit externe pour l’horloge et le reset. Voici quelques exemples d’intégration : Organisation partielle de la mémoire (cf. section IV) Elle est particulière, car elle contient à la fois des registres des ressources internes et des registres à usage général que l’on peut considérer comme de la RAM de travail, et parce qu’elle fait aussi appel à un mécanisme de pagination. La mémoire de donnée des PIC contient à la fois les registres de l’unité centrale, les registres des ressources internes, et des registres à usage général ; elle est divisée artificiellement en pages de 128 octets, il suffit alors de 7 bits pour adresser n’importe quel élément au sein d’une page. Dans le cas du PIC 16F83 seules deux pages de 128 octets sont accessibles (bit RP1 à « 0 », RP0 est utilisé pour accéder à une page ou à l’autre). L’examen de l’organisation de la mémoire de donnée du PIC 16F83 donne un certain nombre d’informations : - Les registres à usage général que l’on peut utiliser comme mémoire vive de travail, se trouvent au dessus de l’adresse 0Bh de chaque page (0Ch en page 0, 8Ch en page 1). - Un certain nombre de registres sont toujours implantés aux mêmes adresses ; ce sont les registres correspondant aux fonctions de base de l’UC (de 00h à 0Bh en page 0). - Certains registres invariants se trouvent dupliqués dans toutes les pages (sauf entre autre TMR0 – OPTION); cela permet d’y accéder immédiatement quelle que soit la page et sans devoir positionner les bits RP0 et RP1. - Les registres de gestion par exemple, des ports d’E/S PORTA et TRISA, se retrouvent à la même adresse, mais dans deux pages différentes, et ce afin de pouvoir passer de l’un à l’autre par simple modification des bits RP0 et RP1. Bibliographie : - MICROCHIP TECHNICAL LIBRAIRIE www.microchip.com - Les microcontrôleurs PIC de Christian Tavernier - édition DUNOD I.\. Réalisation d’un chenillard, synthétisé en langage machine ou assembleur dédié 68HC11 Fichier CHENILLARD.ASC(Programme Source ou Mnémoniques, non exécutable par le 68HC11). portb equ org boucle ldaa deb staa jsr rora cmpa bne bra tempo ldx tpx ldab tpb decb bne dex bne rts end ( Prise en compte de 8 LEDS périphériques ) $1004 $b600 #$80 portb tempo Commentaires #$00 deb boucle #$03b1 #$44 tpb tpx Fichier CHENILLARD.LST M68HC11 Absolute Assembler Version 2.70C:\HC11\CHENIL.ASC 1 A 1004 portb equ $1004 2 A 0000 3 A B600 org $b600 4 A B600 8640 boucle ldaa #$40 5 A B602 B71004 deb staa portb 6 A B605 BDB60F jsr tempo 7 A B608 46 rora 8 A B609 8100 cmpa #$00 9 A B60B 26F5 bne deb 10 A B60D 20F1 bra boucle 11 A B60F 12 A B60F CE03B1 tempo ldx #$03b1 13 A B612 C644 tpx ldab #$44 14 A B614 5A tpb decb 15 A B615 26FD bne tpb 16 A B617 09 dex 17 A B618 26F8 bne tpx 18 A B61A 39 rts 19 A B61B 20 A end SYMBOL TABLE: boucle deb portb Total Entries= 6 B600 tempo B602 tpb 1004 tpx Total errors: 0 B60F B614 B612 Fichier CHENILLARD.S19 (Programme Objet). Programme exécutable par le 68HC11 S00B00002020202020202020F4 S11EB6008640B71004BDB60F46810026F520F1CE03B1C6445A26FD0926F839BC S903B60046 Développement d'un programme Début Correction du programme source. (1) Recherche des erreursen listant le fichier (1) . LST. Saisie (nouveau programme) ou Fichier d'extension édition (programme existant), du (1) . ASC programme source(mnémoniques). Assemblage ou Création du programme objet. NON Fichiers d'extensions (2) . S19 . LST Le fichier assemblé n'a pas d'erreurs. OUI Téléchargement du fichier.S19 dans la mémoire programme du 68HC11. (3) Essai du programme (3) Modification du programme (1) source NON Le programme fonctionne t-il? OUI Fin (1).Utilisation de l'éditeur de texte (2). Utilisation de l'assembleur 68HC11 ASMHC11 (3). Utilisation du logiciel de mise au point de programmes M11 II.\. Réalisation du chenillard par symbolisme graphique (REALIZER BRONZE) Les différentes combinaisons devant apparaître sur les lignes de sorties s0 à s7, sont contenues dans une table lue périodiquement Les lignes de sorties s0 à s7 pilotent les LEDS correspondantes s0 0 s1 0 s0 s0 B0 c1 u1 0.2 osc O Up 0 Val I Q(I) Clr Zero UBYTE table Pr 0 UBYTE essai 0 s1 B2 INDEX Dn s2 s1 B1 W s2 B3 s3 s2 B4 B5 1 s3 B6 s3 B7 s4 s4 B>A A B=A=C B B<C C 0 s4 s5 8 s5 s5 s6 0 s7 s6 s6 s7 0 s7 0 Rev: 0.02 Date: 10 Feb 2002 12:33 Project: CHENILLARD Company: Address: City: Country: Initial Date: 26/12/2001 Eng: Didier PEYTAVI Number: IUFM de TOULOUSE Page: 1 Of: 3 Utilisation d'un registre à décalage SORTIE SERIE s ls b0 s b1 Bitshifter osc1 s B0 Clr 8 bt O OSC1 D/U Cin 128 Out In Shift osc2 UINT 1 bt O OSC2 b2 B1 C RAD s B2 W B3 b3 B4 s B5 b4 B6 0 s B7 b5 s b6 s b7 Sortie C : Sérialisation au rythme de Shift, du contenu du registre à décalage Décalage à droite si D/U = 0 s Sortie OUT : Contenu décimal du registre à décalage Rev: TOSC1 = 8.TOSC2 * 8 décalages à droite et préchargement du registre à décalage à 128(d) * Le MSB apparaît sur la sortie C au 8ième décalage * La combinaison 0(d) apparaît dans le registre à décalage, (toutes les LEDS sont éteintes) 0.02 Date: 10/02/2002 CHENILLARD Eng: Didier PEYTAVI Project: Company: Address: City: Country: Initial Date: Number: IUFM de TOULOUSE 26/12/2001 Page: 2 Of: 3 OSC1 / OSC2 SORTIE SERIE 1 1 1 RAD 0 0 00:00:00.0000 64 00:00:25.0000 0 00:00:00.0000 00:00:25.0000 b0 0 b1 0 SORTIE SERIE s b0 s b1 Bitshifter osc1 s B0 Clr 8 bt O OSC1 128 D/U C Cin Out In Shift osc2 UINT 1 bt O OSC2 RAD B2 W B4 b3 b4 s B7 b4 0 0 1 b7 b5 s b6 s b7 s 0 b6 s B5 b3 b5 s B3 B6 0 b2 B1 b2 0 ls 0 Utilisation d'un registre à décalage SORTIE SERIE s ls b0 s b1 Bitshifter osc1 s B0 Clr 7 bt O OSC1 D/U Cin 128 In Shift osc2 UINT 1 bt O OSC2 Out b2 B1 C RAD s B2 W B3 b3 B4 s B5 b4 B6 0 s B7 b5 s b6 s b7 s TOSC1 = 7.TOSC2 * 7 décalages à droite et préchargement du registre à décalage à 128(d) * La combinaison 0(d) n'apparaît pas dans le registre à décalage, (au moins une LED est allumée) Rev: 0.02 Date: 10/02/2002 CHENILLARD Eng: Didier PEYTAVI Project: Company: Address: City: Country: Initial Date: Number: IUFM de TOULOUSE 26/12/2001 Page: 3 Of: 3 OSC1 / OSC2 SORTIE SERIE 1 1 1 RAD 0 0 00:00:00.0000 64 00:00:25.0000 0 00:00:00.0000 00:00:25.0000 b0 0 b1 0 SORTIE SERIE s b0 s b1 Bitshifter osc1 s B0 Clr 7 bt O OSC1 128 D/U C Cin Out In Shift osc2 UINT 1 bt O OSC2 RAD B2 W B4 b3 b4 s B7 b4 0 0 1 b7 b5 s b6 s b7 s 0 b6 s B5 b3 b5 s B3 B6 0 b2 B1 b2 0 ls 0 III.\. Introduction à la programmation graphique de REALIZER REALIZER est un logiciel permettant de charger directement une application dans un microcontrôleur, sans avoir à écrire une seule ligne de langage assembleur.A cette fin, l’utilisation de symboles permet de représenter des fonctions de programmation, qui une fois liées entres elles peuvent répondre à une application dédiée. Une bonne connaissance du microcontrôleur de destination est bien évidemment essentiel à la conduite du projet. REALIZER génère donc à partir d’un schéma représentatif de l’application, du code assembleur prêt à être utilisé. Le fonctionnement de REALIZER est organisé autour de deux étapes fondamentales : - la première consiste en l’initialisation du microcontrôleur, de ses entrées/sorties, de ses périphériques, de sa mémoire… - la seconde partie produit le code machine à partir de l’application conçue dans REALIZER. Créer une application revient à placer et à connecter des symboles dans un schéma; chaque symbole représentant graphiquement une macro en assembleur. Les différents symboles sont organisés sous la forme de librairies décrivant des fonctions, mathématiques, logiques, de conversion, de gestion de puissance, et permettant l’utilisation de constantes, de machines à états, ou encore de sous schémas. Une application est construite autour d’un microcontrôleur cible; les signaux d’entrée du schémas, devant faire référence aux broches, ports ou périphériques du microcontrôleur. Chaque symbole est associé à une macro en assembleur; les fils de liaison représentent le flux des données, et sont liés à des variables ou des constantes dont le type est paramétrable. Dans REALIZER, l’application s’organise autour d’un schéma, le schéma racine (ROOT); dans un soucis de lisibilité et de clarté dans la relecture graphique d’un fonctionnement, l’utilisation de sous-schémas (du schéma racine) est à privilégier; notons encore que l’analyse par machines à états est aussi possible. La programmation graphique permet aussi de prendre en compte des « évènements » tels qu’une demande d’interruption liée à un TIMER, une interruption matérielle, un changement de valeur d’entrée… III.\.1 Mise en œuvre partielle de la synthèse schématique de REALIZER A.\. Configuration de la saisie de schémas. A.\.1. Création d’un nouveau projet ou ouverture d’un projet existant (.RPF) (définition du composant cible destiné à recevoir le code machine; ici le PIC16F83). (choix automatique des librairies de symboles). A.\.2. Saisie du schéma racine (ROOT) ou ouverture d’un fichier schéma existant (.SCH) A.\.3. Analyse du schéma crée. A.\.4. Lancement d’une simulation (génération d’un fichier .SEF). * dans le menu TOOLS, choisir SIMULATOR. * Sélection graphique des signaux à visualiser par ajout « d’OBJECT » de type PROBE (NUMERIC) * Génération des stimulis (signaux de commandes) par ajout « d’OBJECT » de type ADJUSTER (NUMERIC) Visualisation des principaux résultats sous la forme de Fichiers .RRF .INC .SEF .ERR .LST .ASM .HEX .RRF: Fichier de report du projet crée (prise en compte du chipset de destination, taux d’occupation des ressources matérielles internes). .INC: Table d’équivalence associant à chaque ressource interne (registre, mémoire, entrée, sortie) son adresse physique. .SEF: Fichier résultant de la compilation et contenant les points de la simulation. .ERR: Fichier pointant les erreurs symboliques, syntaxiques, et de définitions des entrées/sorties. .LST: Fichier de mise au point de programme associant mnémoniques et code machine. .ASM: Fichier de description du programme en langage assembleur, dédié au circuit cible. .HEX: Fichier de programmation standard au format code machine. Fichier CHENILLARD.RRF ---------------------------------------------------------------------PIC16F83 Realizing Unit (V4.00) (c) 1990-2000 Actum Solutions Report file of project C:\WINDOWS\BUREAU\chenillard\chenillard.rpf Scheme Version : 1.00 Report timestamp : Tue Dec 26 00:19:45 2000 Analyze results : No errors ---------------------------------------------------------------------Optimisations: ---------------------------------------------------------------------Ram size optimisation: Disabled Sleeping code optimisation: Disabled Constant optimisation: Disabled Speed optimisation: Disabled Schematic dependencies and events: ---------------------------------------------------------------------C:\WINDOWS\BUREAU\chenillard\chenillard2.sch PIC16F83 (DIL18) connection overview: ---------------------------------------------------------------------Pin Name Alternative name Type I/O Description 1: RA2 b2 (BIT Output), Output 2: RA3 b3 (BIT Output), Output 3: RA4 b4 (BIT Output), Output 4: MCLR ( ), Reset, active low 5: Vss ( ), Power supply 6: RB0 b5 (BIT Output), Output 7: RB1 b6 (BIT Output), Output 8: RB2 b7 (BIT Output), Output 9: RB3 s (BIT Output), Output 10: RB4 (BIT Input ), Not connected 11: RB5 (BIT Input ), Not connected 12: RB6 (BIT Input ), Not connected 13: RB7 (BIT Input ), Not connected 14: Vdd ( ), Power supply 15: OSC2 ( ), Oscillator OUT 16: OSC1 ( ), Oscillator IN 17: RA0 b0 (BIT Output), Output 18: RA1 b1 (BIT Output), Output Hardware connections: ---------------------------------------------------------------------Symbolic name H/W name Description | Comment b0 RA0 Output | s b1 RA1 Output | s b2 RA2 Output | s b3 RA3 Output | s b4 RA4 Output | s b5 RB0 Output | s b6 RB1 Output | s b7 RB2 Output | s s RB3 Output | ls Variable overview: ---------------------------------------------------------------------Total used bits : 14 Total used events : 0 Total used unsigned bytes : 2 Total used signed bytes : 0 Total used unsigned integers : 3 Total used signed integers : 0 Total used longs : 0 Memory overview: ---------------------------------------------------------------------Total used RAM :22 byte (0CH->0DH,0FH->21H) Total used ROM :274 byte (0000H,0004H->0009H,000AH->0113H)of 03FFH Digital input Name: DIGIN Library: MAIN.LIB Symbol: Function: Converts a physical digital value to a binary value. Syntax: Pin Description In Physical digital input (type = Boolean). The user is prompted for the symbolic name (In). The connection is made to a physical micro controller pin and is invisible. Out Digital representation of digital value (type = Boolean). Remarks: The NAME attribute is used for connecting this symbol to a hardware port. For this, double-click the symbol or use the right mouse button. The COMMENT attribute is used in the report file. Digital output Name: DIGOUT Library: MAIN.LIB Symbol: Function: Converts a binary value to a physical digital output. Syntax: Pin Description In Digital representation of digital value (type = Boolean). Out Physical digital output (type = Boolean). The user is prompted for the symbolic name (In). The connection is made to a physical micro controller pin and is invisible. Remarks: the NAME attribute is used for connecting this symbol to a hardware port. For this, double-click the symbol or use the right mouse button. The COMMENT attribute is used in the report file. Constant bit Name: CONSTB Library: MAIN.LIB Symbol: Function: Constant Boolean. Syntax: Pin Description Value Constant value entered by the user (0 or 1). Out Binary value (type: Boolean). Remarks: None. Constant word Name: CONSTW Library: MAIN.LIB Symbol: Function: Constant Word. Syntax: Pin Description Value Constant value entered by the user. The following formats are allowed: Decimal 123 Hexadecimal: 0xD4 or 1FFH Octal: 345O Binary: 1100110B Out Remarks: Binary value (type: Word). None. Oscillator fixed Name: OSCF Library: MAIN.LIB Symbol: Function: Oscillator with a fixed oscillation time. Syntax: Pin Description Time Oscillation time value (in days:hrs:min:sec.xxx). The user is prompted to enter this value. where: days is the number of days, hrs is the number of hours, min is the number of minutes, sec is the number of seconds and xxx is a fraction of a second. O Delayed output (type: Boolean). O becomes I after the chosen time period Time Out Remarks: The time defines the pulse width of one level. Counter fixed Name: COUNTF Library: MAIN.LIB Symbol: Function: Counter with a fixed pre-set value Syntax: Pin Description Up Up, binary value (type = Boolean). Dn Down, binary value (type = Boolean). Clr Clear, binary value (type = Boolean). Pr Pre-set, binary value (type = Boolean). Value Pre-set value, the user is prompted to enter this value. Val if Clr = 1 Then Val = 0 else if Pr becomes 1 Then Val = Value if Up becomes 1 Then Val = Val + 1 if Dn becomes 1 Then Val = Val – 1 (type: depends on the type entered by the user) Zero Remarks: if Val = 0 Then Zero = 1 else Zero = 0 None. Comparator Name: COMP Library: MAIN.LIB Symbol: Function: Multi purpose comparator. Syntax: Pin Description A Binary value (type = Word). B Binary value (type = Word). C Binary value (type = Word). B>A When input B is larger than input A Then output = 1 Else output = 0 (type: Boolean) B=A=C When input B equals input A and equals input C Then output = 1 Else output = 0 (type: Boolean) B<C When input B is smaller than input C Then output = 1 Else output = 0 (type: Boolean) Remarks: None. Index table Name: INDEXTABLE Library: MAIN.LIB Symbol: Function: Index conversion table. Syntax: Pin Description In Binary value (type = Word). Out Convert the input to a non-linear output value, defined in a table. The input is used as an index to address the constant value from the table. (Type: depends on type entered by the user). Remarks: If the input exceeds the index size the default value is used. The values are stored as an ASCII file. Just double click the symbol or use the right mouse button (Enter) to edit the table. Byte unpack Name: BUNPACK Library: MAIN.LIB Symbol: Function: 1 Byte to bits unpacker. Syntax: Pin Description W Binary value (type = Word). B0 .. B7 The W input is unpacked to 8 separate Boolean outputs. B0 is the least significant bit (Type: Boolean). Remarks: Enables you to unpack a byte into eight (or less) bits. Shift register Name: SHIFT Library: MAIN.LIB Symbol: Function: Shift register Syntax: Pin Description Clr Clears the shift register, binary value (type = Boolean). D/U Selects the up (1) or down (0) shift direction, binary value (type = Boolean). Cin Latches input In into the shift register, binary value (type = Boolean). In Input, binary value, when a Boolean value is presented then the value is shifted into the register (serial in) otherwise the value will be copied into the register (parallel in). (type = All). Shift Shift, binary value, shifts the register up or down, depending on the D/U input (type = Boolean). Out if Clr = 1 Then Out = 0 else see the description of the input pins (type: depends on the type entered by the user) C Remarks: Carry Out, contains the Boolean shifted out (type Boolean) None. Converter Name: CONVERT Library: MAIN.LIB Symbol: Function: Multi purpose converter. Syntax: Pin Description In Binary value (type = All). Out Convert the input to any output type, this symbol enables the user to convert Booleans to Words and visa versa. (Type: depends on type entered by the user). Remarks: None. Appendix A: Variables and Attributes This appendix provides you with quick access to the type of information you'll need when you create Realizer applications. This information includes: A1 • A list of the type of variables you can define, and the rules that apply to variables. • A list of the attributes you can place on symbols and wires. Variable Types and Rules Realizer lets you define the following data types: Table A1 Data Types Name Range Data type BIT 0,1 Boolean Bit Number of bytes UBYTE 0...255 Unsigned byte 1 SBYTE -128...+127 Signed byte 1 UINT 0...65535 Unsigned integer 2 SINT -32768...32767 Signed integer 2 LONG -2147483648.. .2147483647 Signed long 4 WORD Represents any type, except BIT Any, except Boolean 1 through 4 Most of the symbols included with Realizer support multiple-type pins. This means that any variable types can be assigned to these pins. For example, the AND2 symbol can be used as an AND of either two BIT or two UINT variables. Realizer handles multiple type variables in two groups: • The BIT variables. • The UBYTE .. LONG (=WORD) variables. You cannot mix these variable groups, for example, an AND2 symbol cannot be used to perform an AND on a BIT and a UBYTE variable. Note that the type WORD covers any data type other than BIT. To define a variable type, you attach an attribute with the Tag TYPE and the name of the variable type in the Value field. Realizer User's guide Appendix A: Variables and Attributes • 173 PIC16F8X 18-pin Flash/EEPROM 8-Bit Microcontrollers Devices Included in this Data Sheet: Pin Diagrams PIC16F83 PIC16F84 PIC16CR83 PIC16CR84 Extended voltage range devices available (PIC16LF8X, PIC16LCR8X) PDIP, SOIC High Performance RISC CPU Features: • Only 35 single word instructions to learn • All instructions single cycle except for program branches which are two-cycle • Operating speed: DC - 10 MHz clock input DC - 400 ns instruction cycle Device Program Memory (words) Data Data RAM EEPROM (bytes) (bytes) Max. Freq (MHz) PIC16F83 512 Flash 36 64 PIC16F84 1 K Flash 68 64 10 PIC16CR83 512 ROM 36 64 10 PIC16CR84 1 K ROM 68 64 10 • • • • • • 10 14-bit wide instructions 8-bit wide data path 15 special function hardware registers Eight-level deep hardware stack Direct, indirect and relative addressing modes Four interrupt sources: - External RB0/INT pin - TMR0 timer overflow - PORTB<7:4> interrupt on change - Data EEPROM write complete • 1000 erase/write cycles Flash program memory • 10,000,000 erase/write cycles EEPROM data memory • EEPROM Data Retention > 40 years Peripheral Features: RA2 •1 18 RA1 RA3 2 17 RA0 RA4/T0CKI 3 16 OSC1/CLKIN MCLR 4 15 OSC2/CLKOUT VSS 5 14 VDD RB0/INT 6 13 RB7 RB1 7 12 RB6 RB2 8 11 RB5 RB3 9 10 RB4 PIC16F8X PIC16CR8X • • • • • Special Microcontroller Features: • In-Circuit Serial Programming (ICSP™) - via two pins (ROM devices support only Data EEPROM programming) • Power-on Reset (POR) • Power-up Timer (PWRT) • Oscillator Start-up Timer (OST) • Watchdog Timer (WDT) with its own on-chip RC oscillator for reliable operation • Code-protection • Power saving SLEEP mode • Selectable oscillator options CMOS Flash/EEPROM Technology: • Low-power, high-speed technology • Fully static design • Wide operating voltage range: - Commercial: 2.0V to 6.0V - Industrial: 2.0V to 6.0V • Low power consumption: - < 2 mA typical @ 5V, 4 MHz - 15 µA typical @ 2V, 32 kHz - < 1 µA typical standby current @ 2V • 13 I/O pins with individual direction control • High current sink/source for direct LED drive - 25 mA sink max. per pin - 20 mA source max. per pin • TMR0: 8-bit timer/counter with 8-bit programmable prescaler 1998 Microchip Technology Inc. DS30430C-page 1 PIC16F8X PIC16CXX devices contain an 8-bit ALU and working register. The ALU is a general purpose arithmetic unit. It performs arithmetic and Boolean functions between data in the working register and any register file. The W register is an 8-bit working register used for ALU operations. It is not an addressable register. Depending on the instruction executed, the ALU may affect the values of the Carry (C), Digit Carry (DC), and Zero (Z) bits in the STATUS register. 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. The ALU is 8-bits wide and capable of addition, subtraction, shift and logical operations. Unless otherwise mentioned, arithmetic operations are two’s complement in nature. In two-operand instructions, typically one operand is the working register (W register), and the other operand is a file register or an immediate constant. In single operand instructions, the operand is either the W register or a file register. FIGURE 3-1: PIC16F8X BLOCK DIAGRAM Data Bus 13 8 Program Counter Flash/ROM Program Memory PIC16F83/CR83 512 x 14 PIC16F84/CR84 1K x 14 Program Bus A simplified block diagram for the PIC16F8X is shown in Figure 3-1, its corresponding pin description is shown in Table 3-1. 8 Level Stack (13-bit) 14 EEPROM Data Memory RAM File Registers PIC16F83/CR83 36 x 8 PIC16F84/CR84 68 x 8 7 EEDATA RAM Addr EEPROM Data Memory 64 x 8 EEADR Addr Mux Instruction reg 7 Direct Addr 5 TMR0 Indirect Addr FSR reg RA4/T0CKI STATUS reg 8 MUX Power-up Timer Instruction Decode & Control Timing Generation Oscillator Start-up Timer 8 ALU Power-on Reset Watchdog Timer I/O Ports RA3:RA0 W reg RB7:RB1 RB0/INT OSC2/CLKOUT OSC1/CLKIN DS30430C-page 8 MCLR VDD, VSS 1998 Microchip Technology Inc. PIC16F8X TABLE 3-1 PIC16F8X PINOUT DESCRIPTION DIP No. SOIC No. I/O/P Type OSC1/CLKIN 16 16 I OSC2/CLKOUT 15 15 O — Oscillator crystal output. Connects to crystal or resonator in crystal oscillator mode. In RC mode, OSC2 pin outputs CLKOUT which has 1/4 the frequency of OSC1, and denotes the instruction cycle rate. MCLR 4 4 I/P ST Master clear (reset) input/programming voltage input. This pin is an active low reset to the device. Pin Name Buffer Type Description ST/CMOS (3) Oscillator crystal input/external clock source input. PORTA is a bi-directional I/O port. RA0 17 17 I/O TTL RA1 18 18 I/O TTL RA2 1 1 I/O TTL RA3 2 2 I/O TTL RA4/T0CKI 3 3 I/O ST Can also be selected to be the clock input to the TMR0 timer/ counter. Output is open drain type. PORTB is a bi-directional I/O port. PORTB can be software programmed for internal weak pull-up on all inputs. RB0/INT 6 6 I/O TTL/ST (1) RB1 7 7 I/O TTL RB2 8 8 I/O TTL RB0/INT can also be selected as an external interrupt pin. RB3 9 9 I/O TTL RB4 10 10 I/O TTL Interrupt on change pin. RB5 11 11 I/O TTL Interrupt on change pin. RB6 12 12 I/O TTL/ST (2) (2) TTL/ST Interrupt on change pin. Serial programming clock. Interrupt on change pin. Serial programming data. RB7 13 13 I/O VSS 5 5 P — Ground reference for logic and I/O pins. VDD 14 14 P — Positive supply for logic and I/O pins. Legend: I= input O = output I/O = Input/Output P = power — = Not used TTL = TTL input ST = Schmitt Trigger input Note 1: This buffer is a Schmitt Trigger input when configured as the external interrupt. 2: This buffer is a Schmitt Trigger input when used in serial programming mode. 3: This buffer is a Schmitt Trigger input when configured in RC oscillator mode and a CMOS input otherwise. 1998 Microchip Technology Inc. DS30430C-page 9 PIC16F8X MEMORY ORGANIZATION There are two memory blocks in the PIC16F8X. These are the program memory and the data memory. Each block has its own bus, so that access to each block can occur during the same oscillator cycle. The data memory can further be broken down into the general purpose RAM and the Special Function Registers (SFRs). The operation of the SFRs that control the “core” are described here. The SFRs used to control the peripheral modules are described in the section discussing each individual peripheral module. The data memory area also contains the data EEPROM memory. This memory is not directly mapped into the data memory, but is indirectly mapped. That is, an indirect address pointer specifies the address of the data EEPROM memory to read/write. The 64 bytes of data EEPROM memory have the address range 0h-3Fh. More details on the EEPROM memory can be found in Section 7.0. 4.1 FIGURE 4-1: PROGRAM MEMORY MAP AND STACK - PIC16F83/CR83 PC<12:0> 13 CALL, RETURN RETFIE, RETLW Stack Level 1 • • • Stack Level 8 User Memory Space 4.0 Reset Vector 0000h Peripheral Interrupt Vector 0004h 1FFh Program Memory Organization The PIC16FXX has a 13-bit program counter capable of addressing an 8K x 14 program memory space. For the PIC16F83 and PIC16CR83, the first 512 x 14 (0000h-01FFh) are physically implemented (Figure 4-1). For the PIC16F84 and PIC16CR84, the first 1K x 14 (0000h-03FFh) are physically implemented (Figure 4-2). Accessing a location above the physically implemented address will cause a wraparound. For example, for the PIC16F84 locations 20h, 420h, 820h, C20h, 1020h, 1420h, 1820h, and 1C20h will be the same instruction. 1FFFh FIGURE 4-2: PROGRAM MEMORY MAP AND STACK - PIC16F84/CR84 PC<12:0> 13 CALL, RETURN RETFIE, RETLW Stack Level 1 • • • Stack Level 8 Reset Vector 0000h Peripheral Interrupt Vector 0004h User Memory Space The reset vector is at 0000h and the interrupt vector is at 0004h. 3FFh 1FFFh 1998 Microchip Technology Inc. DS30430C-page 11 PIC16F8X 4.2 Data Memory Organization 4.2.1 GENERAL PURPOSE REGISTER FILE The data memory is partitioned into two areas. The first is the Special Function Registers (SFR) area, while the second is the General Purpose Registers (GPR) area. The SFRs control the operation of the device. All devices have some amount of General Purpose Register (GPR) area. Each GPR is 8 bits wide and is accessed either directly or indirectly through the FSR (Section 4.5). Portions of data memory are banked. This is for both the SFR area and the GPR area. The GPR area is banked to allow greater than 116 bytes of general purpose RAM. The banked areas of the SFR are for the registers that control the peripheral functions. Banking requires the use of control bits for bank selection. These control bits are located in the STATUS Register. Figure 4-1 and Figure 4-2 show the data memory map organization. The GPR addresses in bank 1 are mapped to addresses in bank 0. As an example, addressing location 0Ch or 8Ch will access the same GPR. Instructions MOVWF and MOVF can move values from the W register to any location in the register file (“F”), and vice-versa. The special function registers can be classified into two sets, core and peripheral. Those associated with the core functions are described in this section. Those related to the operation of the peripheral features are described in the section for that specific feature. The entire data memory can be accessed either directly using the absolute address of each register file or indirectly through the File Select Register (FSR) (Section 4.5). Indirect addressing uses the present value of the RP1:RP0 bits for access into the banked areas of data memory. 4.2.2 SPECIAL FUNCTION REGISTERS The Special Function Registers (Figure 4-1, Figure 4-2 and Table 4-1) are used by the CPU and Peripheral functions to control the device operation. These registers are static RAM. Data memory is partitioned into two banks which contain the general purpose registers and the special function registers. Bank 0 is selected by clearing the RP0 bit (STATUS<5>). Setting the RP0 bit selects Bank 1. Each Bank extends up to 7Fh (128 bytes). The first twelve locations of each Bank are reserved for the Special Function Registers. The remainder are General Purpose Registers implemented as static RAM. DS30430C-page 12 1998 Microchip Technology Inc. PIC16F8X FIGURE 4-1: REGISTER FILE MAP PIC16F83/CR83 File Address FIGURE 4-2: REGISTER FILE MAP PIC16F84/CR84 File Address File Address 80h 00h Indirect addr.(1) OPTION 81h 01h TMR0 OPTION 81h PCL 82h 02h PCL PCL 82h STATUS STATUS 83h 03h STATUS STATUS 83h FSR FSR 84h 04h FSR FSR 84h 05h PORTA TRISA 85h 05h PORTA TRISA 85h 06h PORTB TRISB 86h 06h PORTB TRISB 86h 87h 07h 08h EEDATA EECON1 88h 08h EEDATA EECON1 88h 09h EEADR EECON2(1) 89h 09h EEADR EECON2(1) 89h 0Ah PCLATH PCLATH 8Ah 0Ah PCLATH PCLATH 8Ah 0Bh INTCON INTCON 8Bh 0Bh INTCON INTCON 8Bh 8Ch 0Ch 00h Indirect addr.(1) 01h TMR0 02h PCL 03h 04h Indirect addr.(1) 07h 0Ch 36 General Purpose registers (SRAM) Mapped (accesses) in Bank 0 2Fh 30h File Address 8Ch Mapped (accesses) in Bank 0 4Fh 50h 7Fh FFh Bank 0 Bank 1 Unimplemented data memory location; read as ’0’. Note 1: Not a physical register. 1998 Microchip Technology Inc. 80h 87h 68 General Purpose registers (SRAM) AFh B0h Indirect addr.(1) CFh D0h 7Fh FFh Bank 0 Bank 1 Unimplemented data memory location; read as ’0’. Note 1: Not a physical register. DS30430C-page 13 PIC16F8X 4.5 A simple program to clear RAM locations 20h-2Fh using indirect addressing is shown in Example 4-2. Indirect Addressing; INDF and FSR Registers The INDF register is not a physical register. Addressing INDF actually addresses the register whose address is contained in the FSR register (FSR is a pointer). This is indirect addressing. EXAMPLE 4-2: EXAMPLE 4-1: NEXT INDIRECT ADDRESSING • • • • Register file 05 contains the value 10h Register file 06 contains the value 0Ah Load the value 05 into the FSR register A read of the INDF register will return the value of 10h • Increment the value of the FSR register by one (FSR = 06) • A read of the INDF register now will return the value of 0Ah. HOW TO CLEAR RAM USING INDIRECT ADDRESSING movlw movwf clrf incf btfss goto 0x20 FSR INDF FSR FSR,4 NEXT ;initialize pointer ; to RAM ;clear INDF register ;inc pointer ;all done? ;NO, clear next CONTINUE : ;YES, continue An effective 9-bit address is obtained by concatenating the 8-bit FSR register and the IRP bit (STATUS<7>), as shown in Figure 4-1. However, IRP is not used in the PIC16F8X. Reading INDF itself indirectly (FSR = 0) will produce 00h. Writing to the INDF register indirectly results in a no-operation (although STATUS bits may be affected). FIGURE 4-1: DIRECT/INDIRECT ADDRESSING Indirect Addressing Direct Addressing RP1 RP0 bank select 6 from opcode 0 IRP location select 7 bank select 00 01 10 11 not used not used Bank 2 Bank 3 (FSR) 0 location select 00h 00h 0Bh 0Ch Data Memory (3) Addresses map back to Bank 0 2Fh (1) 30h (1) 4Fh (2) 50h (2) 7Fh 7Fh Bank 0 Bank 1 Note 1: PIC16F83 and PIC16CR83 devices. 2: PIC16F84 and PIC16CR84 devices 3: For memory map detail see Figure 4-1. 1998 Microchip Technology Inc. DS30430C-page 19