TMR1 Theoretical basis EN/ES

TMR0 is historically the first timer implemented in Microchip PIC microcontrollers, its usefulness is enormous within the range of applications that we can create with microcontrollers but as we sought to reach more demanding processes it was detected that in processes where measuring time very accurately is a fundamental factor the TMR0 ceases to be effective.

Why? in this article I will explain it to you and at the same time we will lay the theoretical foundations that will allow us to know the TMR1 for later use in our applications. 😉


TMR0 es historicamente el primer temporizador implementado en los microcontroladores PIC del fabricante Microchip, su utilidad es enorme dentro del rango de aplicaciones que podemos crear con microcontroladores pero a medida que se buscaba llegar a procesos más exigentes se detectó que en procesos donde medir el tiempo con mucha precisión es un factor fundamental el TMR0 deja de ser eficaz.

¿Por qué? en este artículo te lo explicaré y al mismo tiempo vamos a sentar las báses teóricas que nos permitirán conocer el TMR1 para posteriormente usarlo en nuestras aplicaciones. 😉


Pixabay

Error as a variable

The error is an input variable that every system has and is produced by multiple factors that depend on the nature of the system or process itself. This variable cannot be eliminated (as my studies and personal experience have taught me 😏) however, what an optimal system seeks is to reduce the value of the error variable as much as possible.

Since this variable cannot be eliminated, every process must tolerate a margin of error in which the activities continue to produce the desired results, being able to consider the error negligible.

The greater the capacity of a system to attenuate the error variable, it is said that said system presents a greater precision.

Starting from these two notions (error and precision) we must consider that some processes tolerate a smaller margin of error than others, therefore the precision of a system can be useful for some processes but useless or ineffective in others.


El error es una variable de entrada que tiene todo sistema y es producido por múltiples factores que dependen de la naturaleza del sistema o proceso en sí. Esta variable no se puede eliminar (según me han enseñado mis estudios y experiencia propia 😏) sin embargo un sistema optimo lo que busca es reducir al máximo posible el valor de la variable error.

Ya que esta variable no se puede eliminar todo proceso debe tolerar un margen de error en el que las actividades siguen produciendo los resultados deseados pudiendo considerar el error como despreciable.

Mientras mayor sea la capacidad de un sistema para atenuar la variable error se dice que dicho sistema presenta una mayor precisión.

Partiendo de estas dos nociones (error y precisión) debemos considerar que algunos procesos toleran un margen de error mas pequeño que otros por lo cual la precisión de un sistema puede ser útil para algunos procesos pero inútil o inefectiva en otros.


Pixabay

Errors in the TMR0

The first error comes as a characteristic of the resolution, if we remember the TMR0 is an 8-bit timer which means that it can only represent 256 values ranging from 0 to 255.

We calculated the maximum time that we can do with TMR0 to be 0.0131072 seconds. We must divide this value by 256 to know the value that will add the increase of each bit. This is 0.0131072/256, which gives us a value of 0.512us, that is, the jumps between bits occur at a rate of 0.512us and this value represents the maximum error that can be generated due to the resolution .

But this value is added every time we load the TMR0 which we do every time an interrupt occurs, now suppose we want to do 1 second using 10ms of time for the TMR0 interrupt, to calculate the value of TMR0 that generates 10ms we use the formula :


El primer error viene como una característica de la resolución, si recordamos el TMR0 es un temporizador de 8 Bits lo cual significa que solo puede representar 256 valores que van desde 0 a 255.

El tiempo máximo que podemos hacer con TMR0 calculamos que era de 0.0131072 segundos, ese valor debemos debemos dividirlo entre 256 para conocer el valor que sumará el aumento de cada bit. Esto es 0.0131072/256 lo que nos da un valor de 0.512us, es decir, los saltos entre bit ocurren a razón de 0.512us y este valor representa el error máximo que se puede generar debido a la resolución.

Pero este valor se suma cada vez que cargamos el TMR0 lo cual hacemos cada vez que ocurre una interrupción, ahora supongamos que queremos hacer 1 segundo usando 10ms de tiempo para la interrupción de TMR0, para calcular el valor de TMR0 que genera 10ms usamos la formula:



Loading the known values and the time in 10ms, the result will tell us that we must load the value of 60.6875 in TMR0, but only integer values between 0 and 255 can be loaded, so we must approximate this value to 61 by introducing the first error, this error The value that can be represented in a bit is 31.25%, that is, 31.25% of 0.512us, which would be 0.16us, which I know seems like a negligible number and it is for certain applications.

However, we must consider that this error is introduced every time the TMR0 is loaded and to make a second starting from 10ms we must load it 100 times, so we must multiply 0.16us by 100 obtaining an error of 16us each second only as a characteristic of the resolution.


Cargando los valores conocidos y el tiempo en 10ms nos el resultado nos dirá que debemos cargar en TMR0 el valor de 60.6875, pero solo se pueden cargar valores enteros entre 0 y 255 así que debemos aproximar este valor a 61 introduciendo el primer error, este error es del 31.25% el valor que se puede representar en un bit, osea el 31.25% de 0.512us que serían 0.16us, lo se que parece un número despreciable y lo es para ciertas aplicaciones.

Sin embargo debemos considerar que este error se introduce cada vez que se carga el TMR0 y para hacer un segundo partiendo de 10ms debemos cargarlo 100 veces, así que debemos multiplicar 0.16us por 100 obteniendo un error de 16us cada segundo solo como característica de la resolución.


Now we are going to take into account the time that is consumed to generate an instruction, this is 4/Fosc which for our frequency of 20MHz is 0.2us, it means that each instruction consumes 0.2us but this applies to assembly language since it is likely that one C language instruction is equivalent to many assembly instructions, however we will be generous in purposely and erroneously applying the assumption that it is valid for C instructions.

When the interruption occurs we must increase the variable, check if it has reached the maximum value, load the timer again, these 3 instructions will be executed as a minimum, which will generate an error of 0.6us but since the process is repeated 100 times we must multiply 0.6us For 100 that would give an error of 60us, to these we add the above and we have an error of 76us for each second. We must take into account that this value is higher because we are interpreting that a C instruction consumes 4 machine cycles, which is not true, we are also assuming that in the interruption we use only 3 instructions and this will always be higher.

76us of error for 1000000us seems very negligible and it is in many applications, but what happens if we want to make a clock with this error? In a week the clock would have been delayed 45,964,800us which we can approximate to 46 seconds and in a month we would have an error of 4 minutes, perhaps it does not affect you to be 4 minutes late somewhere but this error will continue to grow and for the year it would already be half an hour late.


Ahora vamos a tomar en cuenta el tiempo que se consume para generar una instrucción, esto es 4/Fosc que para nuestra frecuencia de 20MHz es 0.2us, significa que cada instrucción consume 0.2us pero esto aplica para el lenguanje ensamblador ya que es probable que una instrucción en lenguaje C equivale a muchas instrucciones en ensamblador, sin embargo seremos generosos a aplicar a propósito y de forma erronea la suposición de que es válido para instrucciones en C.

Al producirse la interrupción debemos incrementar la variable, comprobar si ha llegado al valor máximo, cargar de nuevo el temporizador, estas 3 instrucciones se ejecutarán como mínimo lo que generará un error de 0.6us pero como el proceso se repite 100 veces debemos múltiplicar 0.6us por 100 que daría un error de 60us, a estos les sumamos lo anterior y tenemos un error de 76us para cada segundo. Debemos tomar en cuenta que este valor es mayor porque estamos interpretando que una instrucción en C consume 4 ciclos máquina lo cual no es cierto, además estamos asumiendo que en la interrupción usamos solo 3 instrucciones y esto siempre será mayor.

76us de error para 1000000us parece muy despreciable y lo es en muchas aplicaciones, pero ¿qué pasa si queremos hacer un reloj con este error?, en una semana el reloj se habría retrasado 45,964,800us lo que podemos aproximar a 46 segundos y en un més tendríamos un error de 4 minutos, tal vez no te afecta llegar 4 minutos tarde a algún lado pero este error seguirá creciendo y para el año ya tendría un retraso de media hora.


Pixabay

Maybe you might think that I am something dramatic and we are exaggerating the cruelty with the poor TMR0, but the truth is that as a manufacturer I would not like to create a product that customers have to be adjusting every month, also there are applications in which 76us is too long Believe me there are many of that type.

So the TMR0 is very useful as long as the processes do not require extremely fast actions or do not need to use the timer for extremely long times., that is why the need for a second and improved timer arose which we will know as TMR1.


Tal vez podrías pensar que soy algo dramático y estamos exagerando la crueldad con el pobre TMR0, pero la verdad es que como fabricante no me gustaría crear un producto que los clientes deban estar ajustando cada mes, además existen aplicaciones en las que 76us es demasiado tiempo, creeme que hay muchas de ese tipo.

Así que el TMR0 es muy útil siempre y cuando los procesos no requieran acciones altamente veloces o no necesiten usar el temporizador por tiempos extremadamente prolongados., es por eso que surgió la necesidad de un segundo y mejorado temporizador el cual conoceremos como TMR1.


TMR1

The first difference that we are going to notice in the TMR1 is that it is a 16-bit timer compared to the 8 of TMR0, so it can represent 65536 values compared to the 256 of the TMR0, it is a much higher resolution that greatly attenuates the error For example, for the 0.0131072 maximum time that TMR0 can do with a representation of 0.512us per bit, we can represent a value of 0.2ns with TMR1, that is, our resolution error will never be greater than 0.2ns or 0.0002us Compared to the 0.512us or 512ns of the TMR0, by then we can get an idea of how much the error decreases.

On the other hand, it can make an interruption every 104ms, to make a second we can use 10 interruptions compared to the 100 of the TMR0, so the value of the error per instruction within the interruption is reduced 10 times, from 60us to 6us. In this way the total error per second would be 6.0002us compared to the 76us of the TMR0. The formula to calculate the time is:


La primera diferencia que vamos a notar en el TMR1 es que se trata de un temporizador de 16bits frente a los 8 de TMR0, por lo que puede representar 65536 valores frente a los 256 del TMR0, es una resolución mucho mayor que atenúa enormemente el error, por ejemplo para los 0.0131072 de tiempo máximo que puede hacer el TMR0 con una representación de 0.512us por bit, podemos representar con el TMR1 un valor de 0.2ns es decir, que nuestro error por resolución nunca será mayor a 0.2ns o 0.0002us frente a los 0.512us o 512ns del TMR0, ya por ahí podemos hacernos una idea de cuanto disminuye el error.

Por otro lado puede hacer una interrupción cada 104ms, para hacer un segundo podemos usar 10 interrupciones frente a las 100 del TMR0 por lo que el valor del error por instrucciones dentro de la interrupción se reduce 10 veces, de 60us a 6us. De esta forma el error total por segundo sería de 6,0002us frente a los 76us del TMR0. La formula para calcular el tiempo es:


The TMR1 accepts a maximum load of 65535 and the Prescaler accepts a maximum load of 8, if we use the maximum possible values we will obtain a maximum time of 104ms. This will save us from executing many instructions that end up consuming time and adding value to the error in our applications. 😎


El TMR1 acepta una carga máxima de 65535 y el Preescaler acepta una carga máxima de 8, si usamos los valores máximos posibles obtendremos que se puede hacer un tiempo máximo de 104ms. Eso nos ahorrará la ejecución de muchas instrucciones que acaban consumiendo tiempo y añadiendo valor al error en nuestras aplicaciones. 😎







H2
H3
H4
3 columns
2 columns
1 column
2 Comments
Ecency