RB4-7 Interruptions // Special Edition 💪💪💪 EN/ES

avatar
(Edited)

After almost 6 days absent (from writing) I have returned to continue here with you. This time I have gone above and beyond the usual to make a special dedication to all those who have shown me their support and have motivated me to deliver the best in each article.

After having seen our first interruption it was time to move on to the next one on the list. This is another external interrupt, but in this case we will call it RB.

It consists of detecting variations on pins RB4, RB5, RB6 and RB7 (any of these) and producing an interrupt if they occur.


Después de casí 6 días ausente (de escribir) he regresado para continuar aquí con ustedes. En esta oportunidad me he esforzado mucho más allá de lo acostumbrado para hacer una dedicación especial a todos aquellos que me han mostrado su apoyo y me han motivado a entregar lo mejor en caa artículo.

Luego de haber visto nuestra primera interrupción llegó el momento de pasar a la siguiente en la lista. Se trata de otra del tipo externo pero en este caso la llamaremos RB.

Consiste en detectar variciones en los pines RB4, RB5, RB6 y RB7 (cualquiera de estos) y producir una interrupción en caso de ocurrir.


Circuit created for simulation by @electronico

Theoretical basis

Although we have already seen some theory concerning interrupts in the article Interruptions [EN/ES], in this section of the article we will focus on details about the RB interrupt.

If we compare it with the RB0 (Ext) interrupt they could be similar because a variation in a pin associated to the interrupt triggers the programmed event in both cases, however RB0 can be configured to be triggered by rising edge or falling edge, RB4-7 will be triggered by any state change in the pins related to the interrupt.

The RB4-7 interrupt can be triggered directly by one of 4 possible external events across its 4 pins, however no matter which pin triggered the trigger it will always go to the same subroutine because it is the same interrupt for all 4 pins.

Within the subroutine of the interrupt, code can be created to check which pin triggered the interrupt and assign an individual task to be executed for each of the 4 possible cases.

A useful case for this interrupt can be the monitoring of a process where 4 critical variables must be monitored, I have seen this in some methane gas plants where a pipeline is monitored with pressure sensors, flame sensors, gas detectors and even smoke detectors, any of these detectors could indicate something abnormal in a critical process and trigger a correction or prevention task.


Aunque ya vimos algo de teoría referente a las interrupciones en el artículo Interruptions [EN/ES], en este apartado del artículo nos centraremos en detalles sobre la interrupción RB.

Si la comparamos con la interrupción RB0 (External) podrían ser similares porque una variación en un pin asociado a la interrupción activa el evento programado en ambos casos, sin embargo RB0 puede ser configurado para activarse por flanco de subida o flanco de bajada, RB4-7 se activará por cualquier cambio de estado en los pines relacionados a la interrupción.

La interrupción RB4-7 puede ser activada directamente por uno de 4 posibles eventos externos a través de sus 4 pines, sin embargo sin importar cual sea el Pin que provocó la activación se irá siempre a la misma subrutina porque se trata de la misma interrupción para los 4 pines.

Dentro de la subrutina de la interupción se pueden crear códigos para verificar cual Pin provocó la interrupción y asignar una taréa individual a ejecutar para cada uno de los 4 casos posibles.

Un caso útil para esta interrupción puede ser el monitoreo de un proceso en el que se deben vigilar 4 varíables críticas, he visto esto en algunas plantas de gas metano en las que se supervisa una tuvería con sensores de presión, sensores de llama, detectores de gas e incluso detectores de humo, cualquiera de estos detectores podría indicar algo anormal en un proceso crítico y activar una taréa de corrección o prevención.


Pixabay

Technical data

The interrupt is enabled using the #INT_RB directive, under this instruction you must write the code that will be executed when the event occurs and if conditions can be created to create a task associated with each pin if required, it is also possible that the same task is common for all 4 events, in which case it won't matter who caused the interrupt, it just executes a common task for all of them.

To activate the interrupt we will use the code enable_interrupts(INT_RB); Additionally, global interrupts must be activated using enable_interrupts(GLOBAL); if any of these codes are omitted the interrupt will not occur.

Once the task scheduled for the interruption ends, it returns to the main program right at the moment where it was when the interruption occurred and continues executing from there.


La interrupción se habilita usando la directiva #INT_RB, debajo de esta instrucción se debe escribir el código que se ejecutará cuando ocurra el evento y se pueden crear condicionales if para crear una tarea asociada a cada pin si se requiere, también es posible que una misma taréa sea común para los 4 eventos en cuyo caso no importará quien produjo la interrupción, simplemente se ejecuta una tarea común para todos.

Para activar la interrupción usaremos el código enable_interrupts(INT_RB); adicionalmente se deben activar las interrupciones globales mediante enable_interrupts(GLOBAL); si se omite alguno de estos códigos la interrupción no ocurrirá.

Una vez que termina la tarea programada a la interrupción se regresa al programa principal justo al momento donde estaba cuando ocurrió la interrupción y se continúa ejecutando a partir de ahí.


Our illustrative application

I think it is a special moment because I feel grateful for all the support I have received from you, at first it was hard to write without feeling that my articles had visitors, soon my good friend @zuerich appeared and now all of you who have been providing support, this has grown my love for HIVE and my motivation to put effort into each article written.

That is why I have dedicated this application to all of you, we are going to create an electronic circuit with a PIC16F877A microcontroller in which we will simultaneously manage a 20x4 LCD screen and an 8x8 Matrix Display.

As long as the interruption does not occur, the main program will be executed in which the LCD will show a welcome message and the Display will show the letters to form the word ELECTRONIC.


Creo que es un momento especial porque me siento agradecido por todo el apoyo que he recibido por parte de ustedes, al principio fue duro escribir sin sentir que mis artículos tuviesen visitas, pronto apareció mi buen amigo @zuerich y ahora todos ustedes los que me han estado brindando apoyo, esto ha hecho crecer mi amor por HIVE y mi motivación por esforzarme en cada artículo escrito.

Es por eso que he dedicado esta aplicación a todos ustedes, vamos a crear un circuito electrónico con microcontrolador PIC16F877A en el cual manejaremos de forma simultánea una pantalla LCD20x4 y un Display Matricial 8x8.

Mientras no ocurra la interrupción se ejecutará el programa principal en el que la LCD mostrará un mensaje de bienvenida y el Display Mostrará las letras para formar la palabra ELECTRONICO.


When the interruption occurs, it will be verified which of the four cases produced the interruption (RB4, RB5, RB6 or RB7) and, depending on the case, a task will be executed.

  • RB4: It will display a message dedicated to Ecency on the LCD and will display the word ECENCY interactively on the matrix while the message is being displayed. Ecency is the app I write my articles on and it gives me a lot of tools to make writing easier, I really enjoy it and for that I'm grateful as I can think of the hard work it takes to have created such a great interface that also gives rewards for its use

  • RB5: It will display a message dedicated to STEMSocial on the LCD and will display the word STEMSOCIAL interactively on the matrix while the message is displayed on the LCD. STEMSocial is the community in which my main topics have found a place and I am very grateful for all the support received.

  • RB6: It will show a message dedicated to HIVE on the LCD and it will show the word HIVE interactively on the matrix. HIVE is the platform that makes it possible to share content and be rewarded for creativity. There is a huge variety of topics written and being written right now, so it represents an important source of information. That's why I'm grateful to everyone who makes it possible for this to happen.

  • RB7: It will show on the LCD a mention to the rest of the people and communities with which I am grateful, since I only have 4 interruptions I have had to include all the others in this one, for this case the matrix will show the message THANKYOU.

To activate the interruptions we will use buttons, each button is connected to an interruption pin and can cause it when the state change occurs.


Cuando ocurra la interrupción se verificará cual de los cuatro casos produjo la interrupción (RB4, RB5, RB6 o RB7) y según sea el caso se ejecutará una tarea.

  • RB4: Mostrará en el LCD un mensaje dedicado a Ecency y mostrará en la matriz la palabra ECENCY de forma interactiva mientras se muestra el mensaje. Ecency es la aplicación en la que escribo mis articulos y me brinda muchas herramientas para que la escritura sea más fácil, lo disfruto mucho y por eso estoy agradecido ya que puedo pensar el arduo trabajo que significa haber creado una interfaz tan genial que además otorga recompenzas por su uso
  • RB5: Mostrará en el LCD un mensaje dedicado a STEMSocial y mostrará en la matriz la palabra STEMSOCIAL de forma interactiva mientras se muestra el mensaje en el LCD. STEMSocial es la comunidad en la cual han encontrado lugar mis temas principales y estoy muy agradecido por todo el apoyo recibido.
  • RB6: Mostrará en el LCD un mensaje dedicado a HIVE y mostrará en la matriz la palabra HIVE de forma interactiva. HIVE es la plataforma que hace posible el poder compartir contenido y ser recompensados por la creatividad. Existe una enorme variedad de temas escritos y escribiendose ahora mismo por lo que representa una importante fuente de información. Por eso estoy agradecido con cada uno de los que hace posible que esto suceda.
  • RB7: Mostrará en el LCD una mención al resto de personas y comunidades con las que estoy agradecido, ya que solo dispongo de 4 interrupciones he tenido que incluir a todos los demás en esta, para este caso la matriz mostrará el mensaje THANKYOU.

Para activar las interrupciones usaremos pulsadores, cada pulsador está conectado a un pin de la interrupción y puede provocarla al producirse el cambio de estado.


Programming

We write the configuration lines as usual, now we include the configurations for the LCD20x4 in port D and the Matrix Display in port C, also we establish port B as input for the operation of the interrupts. We will also create the vector char variables for the words ELECTRONIC, ECENCY, STEMSOCIAL, HIVE and THANKYOU that we will later print in the array.


Escribimos las líneas de configuración como de costumbre, ahora incluímos las configuraciones para el LCD20x4 en el puerto D y el Display Matricial en el puerto C, además establecemos el puerto B como entrada para el funcionamiento de las interrupciones. Crearemos además las variables char en vector para las palabras ELECTRONICO, ECENCY, STEMSOCIAL, HIVE y THANKYOU que posteriormente imprimiremos en la matriz.



#include <16f877a.h>

#device PASS_STRINGS = IN_RAM

#fuses HS,NOWDT,NOPROTECT,NOPUT,NOLVP,BROWNOUT

#use delay(clock=20M)

#use fast_io(B)

#use standard_io(D)

#use standard_io(C)

#define DATA PIN_C0

#define LOAD PIN_C1

#define CLK  PIN_C2

#include <MAX7219.c>

#define LCD_DB4  PIN_D4

#define LCD_DB5  PIN_D5

#define LCD_DB6  PIN_D6

#define LCD_DB7  PIN_D7

#define LCD_RS   PIN_D2

#define LCD_E    PIN_D3

#include <LCD_20X4.c>

unsigned char ELECTRONICO[11] = {'E','L','E','C','T','R','O','N','I','C','O'};

unsigned char HIVE[4]={'H','I','V','E'};

unsigned char STEMSOCIAL[10]={'S','T','E','M','S','O','C','I','A','L'};

unsigned char ECENCY[6]={'E','C','E','N','C','Y'};

unsigned char THANKYOU[8]={'T','H','A','N','K','Y','O','U'};

int time=500;

Then we enable the RB interrupt and immediately write the code that will be executed on it by evaluating the four possible conditions and executing on each of them what I announced a few paragraphs earlier. Note that there are many lines of code so you may prefer to skip them and see the result in the simulation, however I put them here because they are part of this article.


Luego habilitamos la interrupción RB e inmediatamente escribimos el código que se ejecutará en él evaluando las cuatro condiciones posibles y ejecutando en cada una de ellas lo que he anunciado unos párrafos antes. Aviso que son muchas líneas de código así que tal vez prefieras omitirlas y ver el resultado en la simulación, sin embargo las pongo acá porque forman parte de este artículo.



#INT_RB

void interrupcion_RB()

{

   if(input(PIN_B4) == 1)

   {

      lcd_clear();

      lcd_gotoxy(2,1);

      printf(lcd_putc,"This");

      delay_ms(100);

      lcd_gotoxy(7,1);

      printf(lcd_putc,"article was");

      delay_ms(100);

      lcd_gotoxy(15,1);

      printf(lcd_putc,"was");

      delay_ms(100);

      lcd_gotoxy(1,2);

      printf(lcd_putc,"Written");

      delay_ms(100);

      lcd_gotoxy(9,2);

      printf(lcd_putc,"using");

      delay_ms(100);

      lcd_gotoxy(15,2);

      printf(lcd_putc,"Ecency");

      delay_ms(100);

      lcd_gotoxy(1,3);

      printf(lcd_putc,"Set it free,");

      delay_ms(700);

      lcd_gotoxy(14,3);

      printf(lcd_putc,"be free");

      delay_ms(700);

      lcd_gotoxy(1,4);

      printf(lcd_putc," https://ecency.com");
            
      for(int e=0; e<3; e++)

      {

        for(int i=0; i<6; i++)

         {

          display_char(ECENCY[i]);

          delay_ms(time);

         }

      }   

   }

   if(input(PIN_B5) == 1)

   {

      lcd_clear();

      lcd_gotoxy(2,1);

      printf(lcd_putc,"This article was");

      delay_ms(100);

      lcd_gotoxy(5,2);

      printf(lcd_putc,"Written in");

      delay_ms(100);

      lcd_gotoxy(5,3);

      printf(lcd_putc,"STEMSocial");

      delay_ms(100);

      lcd_gotoxy(3,4);

      printf(lcd_putc,"Hive Community");

      delay_ms(100);
      
      for(int e=0; e<3; e++)

      {

        for(int i=0; i<10; i++)

         {

          display_char(STEMSOCIAL[i]);

          delay_ms(time);

         }

      lcd_clear();

      lcd_gotoxy(1,1);

      printf(lcd_putc,"Science");

      delay_ms(100);

      lcd_gotoxy(3,2);

      printf(lcd_putc,"Technology");

      delay_ms(100);

      lcd_gotoxy(6,3);

      printf(lcd_putc,"Engineering");

      delay_ms(100);

      lcd_gotoxy(9,4);

      printf(lcd_putc,"Mathematics");

      delay_ms(100);

      }

   }

   if(input(PIN_B6) == 1)

   {

      lcd_clear();

      lcd_gotoxy(2,1);

      printf(lcd_putc,"This article was");

      delay_ms(100);

      lcd_gotoxy(2,2);

      printf(lcd_putc,"Written for HIVE");

      delay_ms(100);

      lcd_gotoxy(4,3);

      printf(lcd_putc,"WEB3 Social");

      delay_ms(100);

      lcd_gotoxy(3,4);

      printf(lcd_putc,"Making History");

      delay_ms(1000);
      
      for(int e=0; e<3; e++)

      {

        for(int i=0; i<4; i++)

         {

          display_char(HIVE[i]);

          delay_ms(time);

         }

      lcd_clear();

      lcd_gotoxy(1,1);

      printf(lcd_putc,"Rewarding creativity");

      delay_ms(100);

      lcd_gotoxy(4,2);

      printf(lcd_putc,"Proof of Brain");

      delay_ms(100);

      lcd_gotoxy(3,3);

      printf(lcd_putc,"Quality content");

      delay_ms(100);

      lcd_gotoxy(2,4);

      printf(lcd_putc,"Changing the world");

      delay_ms(100);

      }

   }

   if(input(PIN_B7) == 1)

   {

      lcd_clear();

      lcd_gotoxy(1,1);

      printf(lcd_putc,"Special thanks to");

      lcd_gotoxy(1,2);

      printf(lcd_putc,"@zuerich for his");

      lcd_gotoxy(1,3);

      printf(lcd_putc,"continued long-time");

      lcd_gotoxy(1,4);

      printf(lcd_putc,"support... Thanks");

      delay_ms(time*3);
      
      for(int e=0; e<3; e++)

      {

        for(int i=0; i<8; i++)

         {

          display_char(THANKYOU[i]);

          delay_ms(time);

         }

      lcd_clear();

      lcd_gotoxy(3,1);

      printf(lcd_putc,"Chessbrothers");

      delay_ms(200);

      lcd_gotoxy(7,2);

      printf(lcd_putc,"Waivio");

      delay_ms(200);

      lcd_gotoxy(1,3);

      printf(lcd_putc,"Hivebuzz (cyborg) :)");

      delay_ms(200);

      lcd_gotoxy(7,4);

      printf(lcd_putc,"Neoxian");

      delay_ms(1000);

      lcd_clear();

      lcd_gotoxy(1,1);

      printf(lcd_putc,"And all those who");

      delay_ms(100);

      lcd_gotoxy(1,2);

      printf(lcd_putc,"read and support");

      delay_ms(100);

      lcd_gotoxy(1,3);

      printf(lcd_putc,"my articles");

      delay_ms(100);

      lcd_gotoxy(1,4);

      printf(lcd_putc,"THANKS!!!!!!!!!!!");

      delay_ms(1000);

      }

   }

}

Then we write the main program in which we activate the RB interrupt and global interrupts, additionally initialize the LCD and the Matrix, as usual we create a while loop so that it executes the announced main program.


Luego escribimos el programa principal en el que activamos la interrupción RB y las interrupciones globales, además inicializamos la LCD y la Matríz, como de costumbre creamos un bucle while para que ejecute el programa principal anunciado.



void main()

{

   set_tris_b(0xFF);

   enable_interrupts(INT_RB);       

   enable_interrupts(GLOBAL);      
   
   display_init(0);

   seg_putc("1");

   lcd_init();
   
   while(true)

   {

      lcd_clear();

      lcd_gotoxy(1,1);

      printf(lcd_putc,"WELCOME TO MY BLOG");

      lcd_gotoxy(1,2);

      printf(lcd_putc,"RB4-7 INTERRUPTIONS");

      lcd_gotoxy(1,3);

      printf(lcd_putc,"@electronico - HIVE");

      lcd_gotoxy(1,4);

      printf(lcd_putc,"Original Content");

      delay_ms(time);
      
      for(int i=0; i<11; i++)

       {

        display_char(ELECTRONICO[i]);

        delay_ms(time);

       }

  }

}

Simulation

For the simulation we will let the main program run and then we will produce the interrupts, one important thing to note is the fact that when returning from the interrupt the program continues where it was before the event and does not start from the first line.


Para la simulación dejaremos que el programa principal se ejecute y luego iremos produciéndo las interrupciones, una cosa importante a notar será el hecho de que al volver de la interrupción el programa sigue donde estaba antes del evento y no inicia desde la primera línea.





0
0
0.000
6 comments
avatar

Thank you for the positive mention of mine.
I appreciate your posts, though there is some code I don’t understand.
Have a great day!

0
0
0.000
avatar
(Edited)

Regarding the code we can ignore it, generally I focus more on the readers enjoying the animations. And it's a thank you item, if it wasn't for you I might even have quit. But you have been an important motivation to move forward. Thanks!

Edit: But if you are interested in understanding the code, you can always write your doubts and we will solve them.

0
0
0.000