| Next revision | Previous revision |
| pt:examples:timer:delay [2015/12/11 16:46] – Criação deste novo documento. artica | pt:examples:timer:delay [2020/07/20 09:00] (current) – external edit 127.0.0.1 |
|---|
| ~~PB~~ | <pagebreak> |
| ====== Espera ====== | ====== Espera ====== |
| |
| [{{ :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 longas. A 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 language. The 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 long. The //sw_delay_ms// enables creating 65535 ms long delays without any complications. | |
| |
| <code c> | <code c> |
| </code> | </code> |
| |
| The following program is for using the given function, this 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 dada, criando duas esperas no loop infinito: 100 ms e 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> |
| </code> | </code> |
| |
| Although it seems that the LED blinks in every 1 second, the time is actually a little bit longer, because 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 a cada segundo, o 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 bit. The principle of counting is the same as it is at software delay function – a desired amount of 1 ms long delays are produced. The 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 times, so 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-language, that shows clock frequency in Hz. The clock frequency should be 25,6 at the moment but since fractions can not be used, the initial value will be set 26. Unfortunately here arises a mistake in delay time, however it is fairly small (-1,7 μs). | O código que se segue é uma função de espera com base num temporizador um pouco simplificado. O princípio de contagem é o mesmo da função de espera de software - uma quantidade desejada de esperas de 1 ms são produzidas. O atraso é produzido com um contador 0 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 vezes, de 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-linguagem, mostra a freqüência de relógio em Hz. A frequência de relógio deve ser 25,6 no momento, mas 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 entanto, bastante pequeno (-1,7 μs). |
| |
| In the cycle takes place initialing of the counter and zeroing the flag of the overflow (by writing 1 into that). Then is waited until the counter counts to 256 from the initial value, i.e. to the overflow. At the moment of the overflow the flag goes high and the delay of 1 ms has taken place. In 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á 1 quando ocorre). De seguida, espera-se até que o contador atinja 256 a partir do valor inicial, ou seja, o overflow. No momento do overflow a flag de overflow passa a high e a espera de 1 ms teve já lugar. No final da função do temporizador é parado. |
| |
| |
| </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> |
| </code> | </code> |
| |
| The following is a similar program to the example of the software delay. In the shorter 100 ms half-period the LED is lit and on the longer 900 ms half-period it is switched off. As the result the LED is blinking after every second. Unfortunately, in this example the period isn't precisely 1 second either, because 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 é desligado. Como resultado o LED pisca a cada segundo. Infelizmente, neste exemplo, o período não é precisamente um segundo também, porque a 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> |