Interruptions [EN/ES]

avatar

When we create a program the code is stacked in lines of code. The program is executed line by line and will only make jumps when a line contains an instruction that makes the pointer jump, an example of this would be a conditional if, if the condition is not met the pointer will jump ignoring the execution of the statement inside the if.

This does not present a major problem in short codes or where there are no long delays in which the pointer has to wait for the end of the time count before advancing, but .... what would happen if we had in a line delay_s(30) in a code where we must monitor among several processes a critical one whose event must be attended without delay?

Let's suppose that when you reach the line delay_s(30) the critical event occurs and the counter is only 10 seconds, there would be 20 seconds left plus the execution time of the following lines before reaching the critical process, in many cases that would be too long. But don't worry, there is a better way to deal with critical processes, so today we will learn about interrupts.


Cuando creamos un programa el código se apila en líneas de códigos. El programa se ejecuta línea por línea y solo hará saltos cuando alguna línea contenga una instrucción que haga saltar el puntero, un ejemplo de esto sería un condicional if, si no se cumple la condición el puntero saltará ignorando la ejecución de la sentencia dentro del if.

Esto no presenta mayor problema en códigos cortos o donde no existen retardos largos en los cuales el puntero tiene que esperar que termine el conteo de tiempo antes de avanzar, pero... ¿qué pasaría si tuviesemos en una línea delay_s(30) en un código donde se debe monitorear entre varios procesos uno crítico cuyo evento debe ser atendido sin demora?

Supongamos que cuando se llega a la línea delay_s(30) ocurre el evento crítico y el contador apenas va por 10 segundos, faltarían 20 segundos mas el tiempo de ejecución de las líneas siguientes antes de llegar a la atención del proceso crítico, en muchos casos eso sería demasiado tiempo. Pero no te preocupes, existe una mejor forma de tratar los procesos críticos, por eso hoy conoceremos las interrupciones.


src

Understanding the concept

Let's be observant for a moment, a worker has been hired by an excavation company to dig a trench of a certain number of meters. The worker mentally schedules his work routine to accomplish the task, loosen the soil, remove the soil, move the soil to a place where everything extracted will be piled up.

We could say that this is the main code in the worker's task, but he knows that at some moments his body will present needs that he must attend to without delay, for example he knows that he will get thirsty, he does not know at what time or at what point of his work but he knows that it will happen, so he prepares a second task to meet this need, he tries to have a thermos of water with a glass nearby for when the moment arrives.

In this second case we would say that he has a secondary task or subroutine, although he does not know when it will occur at the time it happens the worker must "pause" his main task, run the subroutine to meet the need and then resume his main task. Since the need causes him to interrupt his work this is known as an interruption but there is the condition that once the need is met the worker will return to where he had been in his main task.


Seamos observadores por un momento, un obrero ha sido contratado por una empresa de excavación para cavar una sanja de cierta cantidad de metros. El trabajador programa mentalmente su rutina de trabajo para cumplir la tarea, aflojar la tierra, sacar la tierra, mover la tierra a un lugar donde se amontonará todo lo extraido.

Podríamos decir que ese es el código principal en la tarea del trabajador, pero él sabe que en algunos momentos su cuerpo presentará necesidades que debe atender sin demora, por ejemplo él sabe que le dara sed, no sabe a que hora ni en que punto de sus labores pero sabe que ocurrirá, por eso prepara una segunda taréa para atender esta necesidad, intenta tener cerca un termo de agua con un vaso para cuando llegue el momento.

En este segundo caso diriamos que tiene una tarea secundaria o subrutina, aunque no sabe cuando ocurrirá en el momento que ocurra el trabajador deberá "pausar" su tarea principal, ejecutar la subrutina para satisfacer la necesidad y luego retomar su tarea principal. Dado que la necesidad hace que él interrumpa su trabajo esto se conoce como interrupción pero existe la condición de que una vez sea atendida la necesidad el trabajador volverá a donde había quedado en su labor principal.


Pixabay

If we can understand the excavator process then we already know what an interrupt is: It is an event that occurs randomly during a process and is able to pause the main task to attend to the task related to the event, once the event is attended to it is able to resume the main program at the exact point it was at when the interrupt occurred.

In the case of the line that counted 30 seconds at the beginning of this article, an interrupt would pause the count at second 10 (where it was when the critical event occurred), attend to the critical event, and then return to the main program to continue counting from 10.

A PIC16F877A microcontroller has two types of interrupts, external when they are triggered on the pins assigned for that purpose or internal when they are generated by internal events in the microcontroller, below is a list of all available interrupts.


Si podemos comprender el proceso del excavador entonces ya sabemos lo que es una interrupción: Se trata de un evento que ocurre aleatoriamente durante un proceso y es capaz de pausar la tarea principal para atender la tarea relacionada con el evento, una vez atendido el evento es capaz de reanudar el programa principal en el punto exacto que estaba cuando ocurrió la interrupción.

En el caso de la línea que contaba 30 segundos al principio de este artículo, una interrupción pausaría la cuenta en el segundo 10 (donde estaba cuando ocurrió el evento crítico), atendería el evento crítico y luego volvería al programa principal para seguir contando a partir de 10.

Un microcontrolador PIC16F877A presenta dos tipos de interrupciones, externas cuando estas son activadas en los pines asignados para tal propósito o internas cuando son generadas por eventos internos en el microcontrolador, a continuación se presenta una lista de todas las disponibles.



PIC C Compiler screem capture for @electronico

In our learning we will cover the external interrupts (RB0 and RB4-RB7) and the internal ones associated to the timers (TIMER0, TIMER1 and TIMER2).

  • RB0 interrupt: When configured, it occurs due to changes in the RB0 pin of the microcontroller as programmed (rising edge or falling edge), when the programmed edge occurs, the main program is interrupted and the program associated to the interrupt is executed.

  • Interruption RB4-RB7: When a variation in any of these 4 pins is activated it will cause the interruption, it is useful when we have a critical process monitored by 4 different sensors, any of the sensors can cause the interruption that must execute the same task for all, then we can use this interruption, although the limit is always the imagination.

  • Interruption by timers: When timers are programmed they start a count and after the programmed time has passed the interruption occurs, it is useful for applications that must be controlled or monitored every certain time, although timers can also be used without activating the interrupt mode for time related applications.


En nuestro aprendizaje cubriremos las interrupciones externas (RB0 y RB4-RB7) y las internas asosciadas a los temporizadores (TIMER0, TIMER1 y TIMER2).

  • Interrupción RB0: Cuando es configurada ocurre por cambios en el pin RB0 del microcontrolador según haya sido programado (flanco de subida o flanco de bajada), al ocurrir el flanco programado el programa principal se interrumpe y se ejecuta el programa asociado a la interrupción.
  • Interrupción RB4-RB7: Cuando es activada una variación en alguno de estos 4 pines provocará la interrupción, es útil cuando tenemos un proceso crítico monitoreado por 4 sensores distintos, cualquiera de los sensores puede provocar la interrupción que debe ejecutar la misma tarea para todos, entonces podemos usar esta interrupción, aunque el limite siempre es la imaginación.
  • Interrupción por temporizadores: Cuando se programa los temporizadores inician un conteo y luego que ha pasado el tiempo programado se produce la interrupción, es útil para aplicaciones que deben ser controladas o supervisadas cada cierto tiempo, aunque los temporizadores también pueden ser usados sin activar el modo interrupción para aplicaciones relacionadas al tiempo.

Having said all the above we have already laid the groundwork to start using interrupts in our applications, in the next articles we will begin to address each type of interruption mentioned in detail giving useful applications. For now I say goodbye thanking you for reading and I remain attentive to your comments.


Dicho todo lo anterior ya sentamos las bases para comenzar a usar interrupciones en nuestras aplicaciones, en los proximos artículos comenzaremos a abordar cada tipo de interrupción mencionado a detalle dandole aplicaciones útiles. Por ahora me despido agradeciendote por haber leído y quedando atento a tus comentarios.





0
0
0.000
8 comments
avatar

Congratulations @electronico! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)

You received more than 8000 upvotes.
Your next target is to reach 9000 upvotes.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Check out our last posts:

HiveBuzz supports meetups of the Hive Austrian Community in Graz
Our Hive Power Delegations to the December PUM Winners
Feedback from the January Hive Power Up Day
The Hive Gamification Proposal Renewal
0
0
0.000
avatar

¡Enhorabuena!


Has recibido el voto de PROYECTO CHESS BROTHERS

✅ Has hecho un buen trabajo, por lo cual tu publicación ha sido valorada y ha recibido el apoyo de parte de CHESS BROTHERS ♔ 💪


♟ Te invitamos a usar nuestra etiqueta #chessbrothers y a que aprendas más sobre nosotros.

♟♟ También puedes contactarnos en nuestro servidor de Discord y promocionar allí tus publicaciones.

♟♟♟ Considera unirte a nuestro trail de curación para que trabajemos en equipo y recibas recompensas automáticamente.

♞♟ Echa un vistazo a nuestra cuenta @chessbrotherspro para que te informes sobre el proceso de curación llevado a diario por nuestro equipo.


🥇 Si quieres obtener ganancias con tu delegacion de HP y apoyar a nuestro proyecto, te invitamos a unirte al plan Master Investor. Aquí puedes aprender cómo hacerlo.


Cordialmente

El equipo de CHESS BROTHERS

0
0
0.000
avatar

Muchas gracias, su apoyo es muy imoprtante para mi!!

0
0
0.000