TMR1 Theoretical basis EN/ES

Words
2299
Reading
11 min
Listen
Play
4y

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:


alt
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:


alt

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. 馃槑







alt altaltaltaltaltaltalt

TMR1 Theoretical basis EN/ES | Ecency