Differences

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

Link to this comparison view

Next revision
Previous revision
pt:examples:timer:delay [2015/12/11 16:46] – Criação deste novo documento. articapt:examples:timer:delay [2020/07/20 09:00] (current) – external edit 127.0.0.1
Line 1: Line 1:
-~~PB~~+<pagebreak>
 ====== Espera ====== ====== Espera ======
  
Line 55: Line 55:
 [{{  :examples:timer:timer_counter.png?300|Os eventos que vêm com as mudanças do temporizador do AVR.}}] [{{  :examples:timer:timer_counter.png?300|Os eventos que vêm com as mudanças do temporizador do AVR.}}]
  
 +Os contadores AVR podem informar sobre o overflow do contador ou quando ocorre um match. O overflow ocorre quando o contador tem o valor máximo possível e o ciclo começa tudo de novo a partir de 0. O alcançar de um valor pré-definido durante o momento de crescimento do valor do contador é comparado com o valor fornecido pelo utilizador. Na ocorrência do evento, os bits nos índices de status da AVR são automaticamente definidos como high.
  
 +Para gerar uma espera utilizando um temporizador, é necessário apenas definir o temporizador e esperar que o bit de status vá para high. Diferentemente do software de espera, o trabalho do timer não está de dependente do compilador, o que o torna mais confiável. Ao mesmo tempo, a diversidade (ou complexidade) da configuração do contador AVR pode ser considerado bastante problemático. Dependendo do sinal de temporização do microcontrolador, pode acontecer que não ser possível dividir exatamente pelo período de espera desejado e a espera não ser precisa.
  
-AVR counters can be made to inform about overflow of the counter or achieving compare mach. Overflow happens when the counter has the maximal possible value and the cycle starts all over again form 0. With reaching a pre set value during the moment of growth of the counter’s value it is compared to the value given by the user. On the occurrence of the event, the bits in the status indexes of the AVR are automatically set as high.   +O código seguinte de um programa é acerca da função de espera de software //sw_delay_ms//, que determina uma determinada espera em milissegundos usando o parâmetro //count//A função usa a função da biblioteca avr-libc //_delay_ms// que é parcialmente escrita em linguagem assembler. A razão pela qual //_delay_ms// não é utilizada neste exercício imediatamente é que ao usar //_delay_ms// problemas podem ocorrer quando as esperas são longasA função //sw_delay_ms// permite a criação de esperas de 65535 ms, sem quaisquer complicações.
-  +
-For generating a delay using a timer, it is only necessary to set the timer and waiting for the status bit to go high. Different from the software delay, the work of the timer is not depending on the compiler, which makes them more reliable. At the same time the diversity (or complexity) of the set-up of the AVR counter can be considered fairly troublesome. Depending on the microcontroller’s timing signal, may happen that it will not divide exactly with the desired delay period and the delay will not be accurate.  +
- +
-The following code of a program is about software delay function //sw_delay_ms//which makes a given delay in milliseconds using the parameter //count//The function uses avr-libc library’s function //_delay_ms// which is partly written in assembler languageThe reason why the //_delay_ms// is not used in this exercise immediately is that when using the //_delay_ms// problems may occur when the delays are longThe //sw_delay_ms// enables creating 65535 ms long delays without any complications+
  
 <code c> <code c>
Line 76: Line 74:
 </code> </code>
  
-The following program is for using the given functionthis creates two delays in the endless loop: 100 ms and 900 ms. During the shorter delay LED is lit and during the longer it is switched off, the result – the LED is blinking periodically+O programa seguinte usa a função dadacriando duas esperas no loop infinito: 100 ms 900 ms. Durante a espera mais curta o LED é iluminado e durante a mais longa este é desligado. Resultado: o LED pisca periodicamente.
  
 <code c> <code c>
Line 108: Line 106:
 </code> </code>
  
-Although it seems that the LED blinks in every 1 second, the time is actually little bit longerbecause the callouts of LED’s and delay functions are taking a couple of clock rates of the microcontroller+Embora pareça que o indicador pisca cada segundoo tempo é na verdade um pouco mais, porque as chamadas das funções de espera  e do LED tomam  um par de ciclos de relógio do microcontrolador.
  
-The program code below is a delay function based on a timer, which is simplified a little bitThe principle of counting is the same as it is at software delay function – a desired amount of 1 ms long delays are producedThe delay is produced with an 8-bit counter 0. It is calculated previously that at clock frequency 14,7456 Mhz the timing signal has to be divided at least 64 timesso that the counter would not reach to overflow in 1 ms. The value which the counter must have so that the overflow occurs after 1 ms is presented in the form of an expression and the variable is //timer_start//. //F_CPU// which is a constant in macro-languagethat shows clock frequency in Hz. The clock frequency should be 25,6 at the moment but since fractions can not be usedthe initial value will be set 26. Unfortunately here arises a mistake in delay timehowever it is fairly small (-1,7 μs). +O código que se segue é uma função de espera com base num temporizador um pouco simplificadoO princípio de contagem é o mesmo da função de espera de software - uma quantidade desejada de esperas de 1 ms são produzidasO atraso é produzido com um contador de 8 bitsÉ calculado anteriormente que à frequência do relógio de 14,7456 MHz, o sinal de sincronismo tem de ser dividido, pelo menos, 64 vezesde modo a que o contador não chegue ao overflow em 1 ms. O valor que o contador deve ter para que o overflow ocorra após 1 ms é apresentado sob a forma de uma expressão sendo a variável //timer_start//. //F_CPU// que é uma constante na macro-linguagemmostra a freqüência de relógio em Hz. A frequência de relógio deve ser 25,6 no momentomas uma vez que fracções não podem ser usadas, o valor inicial será estabelecido em 26. Infelizmente aqui surge um erro no tempo de espera, sendo no entantobastante pequeno (-1,7 μs).
  
-In the cycle takes place initialing of the counter and zeroing the flag of the overflow (by writing into that). Then is waited until the counter counts to 256 from the initial valuei.e. to the overflow. At the moment of the overflow the flag goes high and the delay of 1 ms has taken placeIn the end of the function the timer is stopped      +No ciclo ocorre a inicialização do contador e a da flag de overflow (que será quando ocorre). De seguida, espera-se até que o contador atinja 256 a partir do valor inicialou seja, o overflow. No momento do overflow flag de overflow passa a high e a espera de 1 ms teve já lugarNo final da função do temporizador é parado     
  
  
Line 149: Line 147:
 </code> </code>
  
-Referenced delay function uses a timer library whose source code for ATmega controller looks like the following:+A função de espera referenciada usa uma biblioteca de temporizador cujo código-fonte para o controlador ATmega é parecida com o seguinte:
  
 <code c> <code c>
Line 196: Line 194:
 </code> </code>
  
-The following is a similar program to the example of the software delayIn the shorter 100 ms half-period the LED is lit and on the longer 900 ms half-period it is switched offAs the result the LED is blinking after every secondUnfortunatelyin this example the period isn't precisely 1 second eitherbecause executing other functions of the program takes also time. For exact timing  a 16-bit timer with interruptions must be used+O que se segue é um programa semelhante ao exemplo de espera de software. Nos meios-períodos mais curtos de 100 ms, o LED é iluminado e nos meios-períodos mais longos é desligadoComo resultado o LED pisca a cada segundoInfelizmenteneste exemploo período não é precisamente um segundo também, porque execução de outras funções do programa leva tempo também. Para uma temporização exata, um temporizador de 16 bits com interrupções deve ser utilizado.
  
 <code c> <code c>
pt/examples/timer/delay.1449852372.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