Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
pt:avr:registers [2014/12/04 16:35] – created aalmeidapt:avr:registers [2020/07/20 09:00] (current) – external edit 127.0.0.1
Line 1: Line 1:
-====== Registers ======+====== Registros======
  
-One of the toughest things for beginners to understand in a microcontroller is typically a registerWhen dealing with microcontrollers, it is impossible to get by without knowing what this device is. This book is in no way different, as the reader is also expected to familiarize him/herself with the concept of a register and therefore the following text will try to explain it in simple enough terms so that even a beginner can grasp the idea of a register.+Um dos conceitos importantes que estão na base da compreensão dos microcontroladores são os registrosPara que possamos trabalhar com um microcontrolador é fundamental conhecer este dispositivo
  
-===== Essence =====+===== Essencial =====
  
-[{{  :images:logic:tape_buttons.jpg?240|Tape player's buttons}}]+[{{  :images:logic:tape_buttons.jpg?240|Botões do equipamento de cassetes}}]
  
-A register is like a panel of buttons on a home applianceIt has switcheswhich can be turned on or offOne of the best examples is a simple tape playerFor thosewho don't rememberthe tape player has (had) 6 buttons, left to right:+O registro é como um painel de botões num controlo domésticoTem botõesque podem estar ligados ou desligadosUm dos melhores exemplos é um radio de cassetesEstes equipamentoscomo deve recordartem seis botões de controlo:
  
-  * Record +  * Gravar 
-  * Rewind +  * Retrocesso rápido 
-  * Play +  * Tocar 
-  * Fast forward +  * Avanço rápido 
-  * Stop +  * Parar 
-  * Pause+  * Pausa
  
-Each button does somethingbut only when it is used correctlyFor examplethe stop button does nothing unless tape is playing - only then will it do something visible and stop the playbackForward and rewind buttonson the other handcan be pressed at any timebecause the tape can be wound in both directionsno matter if it is playing or stoppedThe recording begins only when the play and record buttons are pressed down simultaneouslySome may have tried to press down several or all buttons at once - in this casethe tape player might have done something unexpected or break altogether.+Cada botão faz algomas apenas quando corretamente acionadoPor exemploo botão Parar não faz nada caso cassete não esteja a Tocar – só no caso de estar a tocar é que a sua ativação resulta em algo observávelAvançar ou Retrocederpor sua vezpodem ser pressionados a qualquer momentodado que a cassete pode ser movimentada em ambas as direçõesindependentemente se está a Tocar ou nãoGravar começa quando o botão Tocar é Gravar são pressionados simultaneamentePoderá tentar pressionar vários botões ao mesmo tempo – caso em queo equipamento de cassetes poderá fazer algo inesperado ou mesmo deixar de funcionar
  
-Microcontroller registers behave like buttons on a tape player each button does somethingwhen used correctlyBy pressing the wrong buttonsa microcontroller usually won't breakbut it won't work eitherIn realitythere are no buttons in the registersinstead there are whole lot of transistors, which turn the electricity on and offSimpler microcontrollers have transistor-based switches in a single registerA register can be thought of as an 8-bit numberwhere every bit is marked by the state of one of those switchesFor examplebit value of can mean that the switch is on and that the switch is off.+Os registros do microcontrolador comportam-se da mesma forma – cada botão faz algoquando usado corretamenteQuando pressionamos o botão erradoo microcontrolador pode não deixar de funcionarmas também não irá funcionarNa realidadenão existem botões de registroem vez disso existe um conjunto de transístores, os quais ligam ou desligam eletricidadeOs microcontroladores mais simples tem comutadores com base em transístores de um só registoUm registo pode ser considerado como um número de bitsonde cada bit é registado no estado de cada um dos transístoresPor exemploum bit com o valor de pode significar que o comutador está ligado e com o valor que o comutador está desligado.
  
-[{{  :images:logic:register_buttons_and_bits.png?240|Register's "buttons" and bit values}}]+[{{  :images:logic:register_buttons_and_bits.png?240|Botões do Registo e valores dos bits}}]
  
-Since the state of register's switches can easily be displayed as a number, a register can be compared to a memory, which can hold data in the size of one numberBy this comparisonwe see that registers actually are memory slotsThe difference between register and a memory slot is that a memory slot only stores the informationbut in a register this information actually controls somethingFor exampleif a binary value of 01100001 is written to a registerthen three imaginary buttons are pressed down and something happens.+Uma vez que o estado dos registos pode facilmente ser mostrado como um número, um registo pode ser comparado com memória, a qual pode guardar dados do tamanho de um númeroCom esta comparaçãopodemos depreender que os registros são espaços de memóriaA diferença entre registos e espaços de memória é que ultima apenas guarda informaçãoenquanto o registo na realidade controla algo maisPor exemplose o valor binário 01100001 se encontrar escrito no registosignifica que três dos 8 botões encontram-se pressionados o que implicará algum acontecimento
  
-On a tape player it is possible to press each button separatelybut in a register it is more difficult to change the value of one "switch" or bit. Typically it is necessary to change the entire content of the registerBefore moving on to bit changingone should know that there are a lot of registers in a microcontrollerSome parts of the microcontroller use tens of registers to control themThe variety of registers means that there has to be a way to distinguish between different registers and that is done by naming the registersOne registerfor exampleis called PORTB. Actuallythese names are just to make things easier for the developer and each name corresponds to numeric address.+No equipamento de cassetes é possível pressionar cada botão separadamenteenquanto que num registo é mais difícil mudar o valor de um comutador ou bit. Normalmente é necessário alterar todo o conteúdo do registoAntes de avançar para a mudança de bit, devemos ter conhecimento que existem um grande número de registos no microcontroladorAlgumas partes do microcontrolador são controladas por dezenas de registrosA variedade de registos implica haver uma forma de distinguir entre diferentes os diferentes registos o que é feito nomeando-osUm registopor exemploe denominado PORTB. Na realidadeestes nomes existem apenas para tornar mais simples o desenvolvimento na medida que cada nome corresponde um endereço numérico
  
-===== Usage =====+===== Utilização =====
  
-To write to a register or read a value from itit has to be addressed as variable in C. The following example demonstrates writing binary value to an imaginary register REG and then reading it to variable //reg//Binary values are distinguished by 0b (leading zero), so that the compiler understands the numeric system.+Para escrever num registo ou ler um valor deledeve ser endereçada variável em C. O exemplo seguinte demonstra escrita de um valor binário num registo imaginário REG seguindo-se para a leitura de um valor da variável //reg//Os valores binários distinguem-se por 0b (zero à esquerda), de forma que o compilador interprete o sistema numérico
  
 <code c> <code c>
Line 35: Line 35:
 </code> </code>
  
-There is nothing difficult in writing and reading register valuesbut it gets a little tricky if only a single bit needs to be changedTo change bits, one needs to know how to do binary math and use different numeric systemsIt isn't forbidden to deal only with binary numbersbut they can be a bit troublesomebecause binary numbers are quite longand this is why most people use shorter hexadecimal numbers.+Não existe nada de difícil em escrever e ler valores de registomas pode ser um quanto complicado se se pretende alterar o valor de apenas um dos bitsPara alterar bits, precisamos de saber matemática binária e recorrer a sistemas numéricos diferentesNão é impossível lidar apenas com sistema bináriomas poderá tornar-se um quanto complicadouma vez que os números binários podem tornar-se longosrazão pela qual a maioria das pessoas recorre a números hexadecimais
  
-[{{  :images:logic:logic_hexadecimal.png?209|Hexadecimal numbers}}]+[{{  :images:logic:logic_hexadecimal.png?209|Números hexadecimais}}]
  
-In hexadecimal, the numbers are not only and as in binaryor to as in decimal, but instead to F. hexadecimal number consists of four bits. The table on the right shows the binary numbers and their hexadecimal counterpartsBinary numbers are converted to hexadecimal by reading bits four at a timestarting from the lowest rankRanks are read from right to left and their numbers start from 0. For examplethe lowest ranked (rank 0) bit is and the highest (rank 3) is 1. In the previous examplethe register's binary value is 01100001, which is 61 in hexadecimal and is written as 0x61 (leading zero) in C.+No sistema hexadecimal, os números não são apenas como no sistema binárioou no sistema decimal, mas antes de F. Um número hexadecimal consiste em quatro bits. A tabela ao lado mostra os números binários e os correspondentes hexadecimaisOs números binários são convertidos em hexadecimais lendo os bits ao mesmo tempocomeçando pelo de mais baixo nívelOs níveis são lidos da direita para a esquerda e os seus números começam em 0. Por exemploo bit de nível mais baixo (nível 0) é 0, e o de nível mais alto é 1. No exemplo anterioro valor binário do registo é 01100001, o que corresponde a 61 em hexadecimal sendo escrito como 0x61 (zero à esquerdaem C.
  
-To change single bits in a number (registervariable or anywhere else for that matterit is necessary to use binary operationsBinary operation is an operation between two binary numberswhere each bit of the numbers is subject to its own logical operationTypically a microcontroller supports four binary operationseach having several namesThe following section describes the logical operation behind each of these four binary operations with a single bit or multiple bits.+Para alterar os bits num número (registovariável ou noutro localé necessário realizar operações bináriasAs operações binárias é uma operação entre dois números bináriosonde cada um dos bits é sujeito à sua operação lógicaNormalmente um microcontrolador suporta quatro operações lógicascada qual tendo vários nomesA secção seguinte descreve as operações lógicas por detrás de cada uma destas operações binárias com um só bit ou com múltiplos bits.
  
-[{{  :images:logic:logic_all_4.png?550  |Negationlogical multiplicationlogical addition and exclusive disjunction }}]+[{{  :images:logic:logic_all_4.png?550  |NegaçãoMultiplicação lógicaAdição lógica and disjunção exclusiva  }}]
  
-~~PB~~+<pagebreak>
  
-  * **Negation Inversion** \\ Negation changes the bit's value to its oppositebecomes a and vice versa. In C, negation is marked with "~"+  * ** Negação Inversão** \\ A negação altera o valor do bit para o oposto, 0 torna-se vice-versa. Em C, a negação é representada por “~
-  * **Logical multiplication Conjunction** \\ When multiplying two bits, the answer is if both bits are and in any other case 0. In C, logical multiplication is marked with "&"+  * **Multiplicação lógica Conjugação** \\ Quando a multiplicar dois bits, a resposta é se ambos os bits são nos casos restantesEm C, a multiplicação lógica é representada por “&
-  * **Logical addition Disjunction** \\ When adding two bits, the answer is if at least one of the bits is and if both bits are 0. In C, logical addition is marked with "|"+  * **Adição lógica Disjunção** \\ Quando são adicionados dois bits, a resposta é se pelo menos um dos bits é quando ambos os bits são 0. Em C, a adição lógica é representada por “|
-  * **Exclusive disjunction Exclusive OR / XOR** \\ Exclusive OR operation will return if the two bits differ from each other (one is and the other 0), otherwise the answer is 0. In C, exclusive disjunction is marked with "^".+  * **Disjunção exclusiva / OR/OXOR exclusivos** \\ A operação OR exclusiva retornará se os dois bits forem diferentes um do outro (se um for e outro for 0), caso contrário a resposta será 0. Em C, a disjunção exclusiva é representada por “^.
  
-This is all one needs to know to change single bitsThe theory alone is probably not enoughthoughand that is why there are some typical examples with registers in the next few paragraphs.+Isto é tudo que precisamos saber para alterar apenas um bitA teoria per si poderá não ser suficienteno entantopelo que daremos alguns exemplos a seguir.
  
 ~~CL~~ ~~CL~~
  
-==== Setting a Single Bit High ====+==== Definindo um único bit positivo ====
  
-[{{  :images:logic:op_bit_set.png?230|Setting a single bit high}}]+[{{  :images:logic:op_bit_set.png?230| Definir um único bit como positivo}}]
  
-To set one or more bits in a register high (1) a logical addition operation is neededOne of the operands of the operation must be the register and the other a binary numberwhere the only high bit is the one that needs to be set high in the registerThis binary number is called a bitmaskBelow is the code for the operation shown on the right:+Para definir apenas um bit num registo para positivo (1) deve ser operada uma adição lógicaUm dos operandos da operação deve ser o registo em conjunto com outro número binárioonde o único bit positivo é aquele que se pretende ver ligado no registoO número binário é denominado de mascara de bitsAbaixo segue o código em para a operação em causa:
  
 ~~CL~~ ~~CL~~
  
 <code c> <code c>
-  // Let's suppose REG = 0x0F +  // Vamos supor que REG = 0x0F 
-  REG = REG | 0x11; // First method +  REG = REG | 0x11; // primeiro método 
-  REG |= 0x11;      // Second method +  REG |= 0x11;      // segundo método 
-  // Now REG = 0x1F+  // Novo REG = 0x1F
 </code> </code>
  
-==== Setting a Single Bit Low ====+==== Definindo um único bit negativo ====
  
-[{{  :images:logic:op_bit_clear.png?229|Setting a single bit low}}]+[{{  :images:logic:op_bit_clear.png?229|Definir um único bit como baixo}}]
  
-To set one or more bits in a register low (0) a logical multiplication operation is neededOne operand of the operation must be the register and the other bitmaskin which the only low bit is the one that needs to be set low in the registerBelow is the code for the operation shown on the right:+Para definir apenas um bit num registo para negativo (0) deve ser operada uma multiplicação lógicaUm dos operandos da operação deve o registo e outro mascara de bitsna qual o único bit negativo é o que precisa de ser definido como negativoA seguir segue o código em da operação em causa:
  
 ~~CL~~ ~~CL~~
  
 <code c> <code c>
-  // Let's suppose REG = 0x0F +  // Vamos supor que REG = 0x0F 
-  REG = REG & 0xFE; // First method +  REG = REG & 0xFE; // primeiro método 
-  REG &= 0xFE;      // Second method +  REG &= 0xFE;      // segundo método 
-  // Now REG = 0x0E+  // Novo REG = 0x0E
 </code> </code>
  
-~~PB~~+<pagebreak>
  
-==== Inverting a Single Bit ====+==== Inverter um só bit ====
  
-[{{  :images:logic:op_bit_invert.png?229|Inverting a single bit}}]+[{{  :images:logic:op_bit_invert.png?229|Inverter um só bit}}]
  
-To invert one or more bits in register an exclusive disjunction operation is requiredOne of the operands of the operation must be the register and the other bitmaskwhere the only high bit is the one that needs to be inverted in the registerBelow is the code for the operation shown on the right:+Para inverter um ou mais bits num registo é necessário recorrer uma disjunção exclusivaUm dos operandos na operação deve ser o registo e outro mascara de bitsonde o único bit positivo é aquele que precisa de ser invertido no registoSegue-se o exemplo de código em C:
  
 ~~CL~~ ~~CL~~
  
 <code c> <code c>
-  // Let's suppose REG = 0x0F +  // Vamos supor que  REG = 0x0F 
-  REG = REG ^ 0x11; // First method +  REG = REG ^ 0x11; // primeiro método 
-  REG ^= 0x11;      // Second method (use only one per inversion+  REG ^= 0x11;      // segundo método (usa apenas um por inversão
-  // Now REG = 0x1E+  // Novo REG = 0x1E
 </code> </code>
  
-==== Inverting the Whole Register ====+==== Invertendo todo o registo ====
  
-[{{  :images:logic:op_reg_invert.png?229|Inverting all bits}}]+[{{  :images:logic:op_reg_invert.png?229|Invertendo todo os bits}}]
  
-To invert all bits in a register, a negation operation is usedThis operation is unarywhich means it has only one operandBelow is the code for the operation shown on the right:+Para inverter todos os bits num registodeve ser usada negaçãoEsta operação é unitáriaoque significa que recorre apenas um operandoSegue um exemplo de código para tal operação:
  
 ~~CL~~ ~~CL~~
  
 <code c> <code c>
-  // Let's suppose REG = 0x0F+  // Vamos supor que REG = 0x0F
   REG = ~REG;   REG = ~REG;
-  // Now REG = 0xF0+  // Novo REG = 0xF0
 </code> </code>
  
-==== Reading the Value of a Single Bit ====+==== Ler um valor de um único bit ====
  
-[{{  :images:logic:op_bit_get.png?229|Reading the value of a bit}}]+[{{  :images:logic:op_bit_get.png?229|Ler um valor de um único bit}}]
  
-To read one or more bits from register the same operation is required as was used for setting a bit low - logical multiplicationOne of the operands of the operation must be the register and the other bitmaskwhere the only high bit is the one that needs to be read from the registerBelow is the code for the operation shown on the right:+Para ler um ou mais valores de um registo na mesma operação é necessário recorrer mesma operação para definição de um bit positivo – multiplicação logicaUm dos operandos deverá ser o registo e o outro mascara de bitsonde o único bit positivo é aquele que precisa de ser lido do registoA seguir apresenta-se um exemplo de código em para realizar esta operação:
  
 ~~CL~~ ~~CL~~
  
 <code c> <code c>
-  // Let's suppose REG = 0x0F+  // Vamos supor REG = 0x0F
   unsigned char x = REG & 0x01;   unsigned char x = REG & 0x01;
-  // Now x = 0x01+  // Novo x = 0x01
 </code> </code>
  
-~~PB~~+<pagebreak>
  
-==== Shifting a Bit ====+==== Deslocar um bit ====
  
-Many programming languages actually have a few additional bitwise operationswhich make it easier for programmersThese are bit shifting operations that shift bits left or right in binary numberThe main advantage of shift operations in dealing with registers is their ability to convert bit ranks to bitmasks and vice versa.+Algumas linguagens de programação tem na verdade umas quantas operações de bitsque tornam mais fácil a programaçãoEntre estas encontram-se as operações de deslocamento de bits as quais deslocam os bits da esquerda para direita no seio de um número binárioA maior vantagem das operações de deslocamento no seio de registos é a sua habilidade para converter níveis de bits em mascaras de bits e vice-versa.  
 +A imagem na direita mostra uma operação de deslocamento à esquerda. No entanto o deslocamento de bits não é uma operação lógica e não tem símbolo correspondente, sendo identificada em C por «”. O deslocamento à esquerda é usado para transformar um nível de bits numa mascara de bits. Por exemplo, para obter a mascara do 6º bit (NB! Nível 5), o numero 1 tem que ser deslocado à esquerda 5 vezes. Segue-se um exemplo da operação em C:
  
-[{{  :images:logic:op_bit_shift_left.png?241|Shift left}}] 
  
-The image on the right shows a shift-left operationAlthough bit shifting is not a logical operation and has no corresponding symbolin it is marked as "<<"Shift-left is used to transform a bit rank to a bitmaskFor exampleto get the mask for the 6th bit (NB! rank 5), number has to be shifted left timesThe example operation looks like this in C:+[{{  :images:logic:op_bit_shift_left.png?241|Deslocar à esquerda}}] 
 + 
 +A imagem na direita mostra uma operação de deslocamento à esquerda. No entanto o deslocamento de bits não é uma operação lógica e não tem símbolo correspondentesendo identificada em por «”O deslocamento à esquerda é usado para transformar um nível de bits numa mascara de bitsPor exemplopara obter a mascara do 6º bit (NB! Nível 5), o numero tem que ser deslocado à esquerda vezesSegue-se um exemplo da operação em C:
  
 ~~CL~~ ~~CL~~
Line 145: Line 147:
 <code c> <code c>
 REG = 0x01 << 5; REG = 0x01 << 5;
-// Now REG = 0x20+// Novo REG = 0x20
 </code> </code>
  
-[{{  :images:logic:op_bit_shift_right.png?241|Shift right}}]+[{{  :images:logic:op_bit_shift_right.png?241|Deslocar à direita}}]
  
-The shift-right operation works similarly to the shift-left operationIt is marked as ">>" in C. Right-shift is used to get the logical value of a bit from a bitmaskA previous example showed how to read the value of single bit. Let's suppose the bit to be read is not of the lowest rankbut for example of rank 5. In this casethe result would be either 0x20 or 0x00, but sometimes a result of or is needed and that is when the right-shift comes to the rescueThe example operation on the right looks like this in C:+A operação de deslocamento à direita funciona de forma semelhante ao deslocamento à esquerdaÉ representada em como “»”O deslocamento à direita é usado para obter um valor lógico de um único bit. Vamos supor que o bit ser lido não é o de mais baixo nívelmas por exemplo de nível 5. Neste casoo resultado poderá ser tanto 0x20 como 0x00, mas por vezes o resultado ou é necessário o que implica deslocamento à direitaSegue-se um exemplo de código em para o efeito:
  
 ~~CL~~ ~~CL~~
  
 <code c> <code c>
-// Let's suppose REG = 0x20+// Vamos supor que REG = 0x20
 unsigned char x = REG >> 5; unsigned char x = REG >> 5;
-// Now x = 0x01 (or simply 1)+// Novo x = 0x01 (or simply 1)
 </code> </code>
  
-If a bit is shifted right from the lowest rank or left from the highest rank by the bit shifting operationit disappearsSome programming languages also have rotating bit shift operationswhere the bit doesn't disappearbut moves from the lowest rank to the highest or vice versa. C doesn't have that kind of bit-shift operationsbut they can be written by the programmer if needed.+Se um bit for deslocado à direita de uma posição mais baixa ou à esquerda a partir de uma posição mais alta através a operação de deslocamento de bitseste desapareceAlgumas linguagens de programação incluem operações de rotação de bitsnas quais os bits não desaparecemmas movem-se da posição mais baixa para a mais alta e vice-versa. Em não existem tais operaçõesmas o programador poderá desenvolve-las.  
 +Todas as operações com bits funcionam com bits bem como com variáveis e constantes
  
-All bit operations work with not only registers, but with variables and constants as well. The latter can of course only be used as operands and not the result. 
  
-===== AVR Registers =====+===== Registos AVR  =====
  
-To actually do anything with the microcontroller's registersone needs to know how to use that particular microcontrollerEach microcontroller comes with one or several datasheets, which describe the whole structure and functionality of the microcontrollerThe datasheet also describes the registersThe following will help understand the register descriptions in AVR datasheets.+Para na realidade fazer algo nos registos do microcontrolador AVRprecisamos de saber como usar esse microcontrolador em particular. Cada microcontrolador vem dotado de vários folhas de dados (datasheets)as quais descrevem toda a estrutura e funcionalidades do microcontroladorA folha de dados também escreve os registosA seguir analisamos um exemplo da descrição dos registos de um microcontrolador AVR.
  
-[{{  :images:logic:avr_example_register.png?580  |One of AVRs registers from its datasheet}}]+[{{  :images:logic:avr_example_register.png?580  |Um dos registos AVRs a partir da folha de dados}}]
  
-The image shows ATmega128 microcontroller'UCSRnA registerwhich stands for "USART Control and Status Register A"This register is used to configure AVR'USART module and read its statesAll AVR register names are written in capital lettersbut as the reader might noticethe register name contains also a lower case nA lower n is used to mark some module's indexSince ATmega128 has almost identical USART modulesthey are not described twicebut only once and the must be read as or by the userTherefore ATmega128 has registers UCSR0A and UCSR1A.+A imagem mostra o registo UCSRnA do microcontrolador ATmega128nomenclatura que significa “USART Control and Status Register AO registo é usado para configurar o modulo do AVR denominado USART e ler os seus estadosTodos os nomes dos registos do AVR são identificados por caracteres em maiúsculasmas como poderá verificaros nomes de registo incluem também algumas letras minúsculasUma letra minúscula é usada para denotar o índex do moduloUma vez que o ATmega128 tem módulos muito semelhantese para evitar descreve-los duas vezessendo descritos apenas uma vez devendo neste caso o ser lido como ou 1. Neste sentido, o ATmega128 tem dois registos UCSR0A UCSR1A.
  
-The content of the register is marked by an 8-slot box with bold line around itEach slot marks one bit. Bit ranks are marked above the box - increasing from right to leftSince AVR is an 8-bit microcontrollermost of the registers are 8-bit as wellThere are some exceptionsa few registers are 16-bitbut they actually consist of two 8-bit registersJust as each register has a nameeach bit in the register also has a name - just like the buttons on a tape playerEach bit is described in the datasheetBit names are abbreviations as well and the lower must be substituted with the module's indexjust like with register namesSome registers don't use all 8 bits, in this case the bit's slot is marked with a hyphen.+O conceito de registo e marcada por uma caixa de retângulos com uma linha espessa sua voltaCada retângulo representa um bit. Os níveis dos bits são identificados por debaixo do retângulo – aumentando o numero da direita para a esquerdaUma vez que o AVR é um microcontrolador de bitsa maioria dos registos também o sãoExistem no entanto algumas exceçõesalguns registos de 16 bitsmas estes na verdade consistem em dois registos de bitsTal como cada registo é identificado por um nomecada bit num registo é identificado por um nome – tal como os botões no equipamento de cassetesCada bit descrito na folha de dadosOs nomes de bits também são abreviações devendo o mais baixo ser substituído pelo índice do modulotal como no nome dos registosAlguns registos não usam todos os 8 bits, caso em que o retângulo de tal bit é identificado por um hífen
  
-Below the register'bits are two lineswhich state whether the bit is readable (R), writable (W) or both (R/W). For examplethe status bits can't be overwritten and even if it's attempted in the programthe bit will remain unchangedIf the bit is marked as writablereading it will always result in one specific value stated in the datasheetThe second line specifies the default value of the bit, which it has after the reset of the microcontroller.+Debaixo dos bits do registo existem duas linhasque identificam se o bit é possível de ler (R), possível de escrever (W), ou ambos (R/W). Por exemploos estados dos bits não podem ser reescritos e mesmo que tal seja tentado num programabit continuara inalteradoSe o bit estiver identificado como possível de escrever (W)a sua leitura resultará sempre num valor especificado na folha de dadosA segunda linha especifica o valor por defeito do bit, o qual é assumido sempre que o microcontrolador é reiniciado
  
-While AVR register names point to an actual memory slot addressthe bit names hold the rank number of the corresponding bit. Therefore it is necessary to transform the names to bitmasks using shift operationin order to manipulate with bits in registerThe following code contains a few example lines for using the USART 0 module's register.+Enquanto  que os registos AVR apontam para espaços de memória reaisos nomes de bits identificam o número de nível do bit correspondentePelo que é necessário transformar os nomes em mascaras de bits recorrendo uma operação de deslocamentode forma manipular os bits do registoO código seguinte demonstra um exemplo que atua sobre o registo do modulo USART 0.
  
 <code c> <code c>
-  // Set TXC0 bit high+  // Define bit TXC0 como alto
   UCSR0A |= (1 << TXC0);   UCSR0A |= (1 << TXC0);
  
-  // Set U2X0 bit low+  // Define o bit U2X0 como baixo 
   UCSR0A &= ~(1 << U2X0);   UCSR0A &= ~(1 << U2X0);
  
-  // Read the value of UDRE0 bit(mask)+  // Lê o valor da mascara de bits UDRE0 
   unsigned char u = (UCSR0A & (1 << UDRE0));   unsigned char u = (UCSR0A & (1 << UDRE0));
  
-  // At this point value is either or 32, +  // Neste ponto o valor de é tanto como 32 
-  // which enables using it in a logical operation+  // o que permite usa-lo na operação lógica
   if (u)   if (u)
   {   {
-     // Invert MPCM0 bit+     // Inverte o bit MPCM0
      UCSR0A ^= (1 << MPCM0);      UCSR0A ^= (1 << MPCM0);
   }   }
  
-  // Sometimes it is necessary to acquire a specific or value, +  // Por vezes é necessário adequirir um valor especifico de ou 
-  // so the read bit needs to be shifted right+  // pelo que a leitura do bit deve ser deslocada para a direita
   u >>= UDRE0;   u >>= UDRE0;
  
-  // Now the value of is either or 1+  // Agora o valor de é ou 1
 </code> </code>
  
pt/avr/registers.1417710915.txt.gz · Last modified: 2020/07/20 09:00 (external edit)
CC Attribution-Share Alike 4.0 International
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0