USART reception EN/ES

View this thread on: d.buzz | hive.blog | peakd.com | ecency.com
·@electronico·
0.000 HBD
USART reception EN/ES
<div class=text-justify>

Monitoring data in a process is something fundamental for operators because it allows to know the status of variables in real time without the operator having to go to make the measurement on site, in fact that is the main purpose of measuring instruments that can make the local measurement and send the value to a remote location that is usually called "control room".

But if an operator can only fulfill the role of observer then monitoring becomes impractical because there is no point in knowing that something unwanted is going to happen if you cannot take an action in the process to avoid it.

In this article we will complement the information seen in our previous topic [USART transmission EN/ES](https://ecency.com/hive-196387/@electronico/usart-transmission-en-en-es), this time we will learn how to handle in our controller the data coming from a computer or external device via USART communication to take actions in a process.

***
>Monitorear datos en un proceso es algo fundamental para los operadores porque permite conocer el estado de las variables en tiempo real sin que el operador tenga que ir a hacer la medición en el sitio, de hecho ese es el propósito principal de los instrumentos de medición que pueden hacer la medición local y enviar el valor a un lugar remoto que suele llamarse "sala de control".

>Pero si un operador solo puede cumplir el papel de observador entonces el monitoreo se vuelve poco práctico porque no sirve de nada saber que va a ocurrir algo no deseado si no puedes tomar una acción en el proceso para evitarlo.

>En este artículo vamos a complementar la información vista en nuestro tema anterior [USART transmission EN/ES](https://ecency.com/hive-196387/@electronico/usart-transmission-en-es), esta vez aprenderemos a manejar en nuestro controlador los datos que provengan de un ordenador o dispositivo externo mediante comunicacion USART para tomar acciones en un proceso.
***
<center>
![](https://images.ecency.com/DQmeCTv6Ht6hUtssSeJ6iF1w3goqd6APTXQnRKKekjd1uSn/image.png)
 </center>

<center>
<table>
<thead>
<tr><th><center><div class="phishy">Handling of data received on the Microcontroller</div></center></th></tr>
</thead>
<tbody>
</tbody>
</table>
</center>

Once the communications port is opened between the microcontroller and the computer all the data sent from one point to the other will be received. With the Hercules program we will be able to see everything we send from the microcontroller to the computer but it is different in the reverse mode.

That is to say, if we send data from the computer or an external device to the microcontroller the data will be received by the microcontroller but it will not display it or take any action based on it if we have not previously written it in the program.

The data that is sent from the computer is written with the keyboard and therefore will always be of type _char_ to capture it the instruction _getc()_ is used once the data is obtained it can be used in the logic of the program to make decisions based on it. The data can be sent from the Hercules program (for now), at the bottom of this program you can write characters to be sent through the RS232 port in USART mode. 

***
>Una vez que se abre el puerto de comunicaciones entre el microcontrolador y el ordenador todos los datos que se envíen desde un punto a otro serán recibidos. Con el programa hércules podremos ver todo lo que enviemos del microcontrolador al ordenador pero es diferente en el modo inverso.

>Es decir, si enviamos datos desde el ordenador o un dispositivo externo al microcontrolador los datos serán recibidos por el microcontrolador pero no los mostrara ni tomará ninguna acción basado en ellos si no lo hemos escrito previamente en el programa.

>Los datos que se envían desde el ordenador son escritos con el teclado y por lo tanto siempre serán del tipo _char_ para capturarlos se usa la instrucción _getc()_ una vez que el dato es obtenido se puede usar en la lógica del programa para tomar decisiones basadas en este. Los datos los podemos enviar desde el programa Hércules (por ahora), en la parte inferior de este programa se pueden escribir caracteres para ser enviados mediante el puerto RS232 en el modo USART. 
***

<center> 
![](https://images.ecency.com/DQmQVSoKv2H4DSSW1BmEWAvyVqBjMZX5ebuqP6eyMxDt7A9/image.png)
</center>

<center>
<table>
<thead>
<tr><th><center><div class="phishy">Test design</div></center></th></tr>
</thead>
<tbody>
</tbody>
</table>
</center>

To show the handling of received data we are going to create a design in which we will use an LCD for local information and we will control a motor and a led remotely through a computer using the USART mode.

To turn on the motor the letter _a_ must be sent from the computer, the LCD will show a message indicating that the motor is on and the motor will turn on, the letter _b_ must be sent to turn off the motor and show on the LCD the message corresponding to motor off.

The letter c is sent to turn on the LED and d is sent to turn off the LED, both states are displayed locally on the LCD.

***
>Para mostrar el manejo de datos recibidos vamos a crear un diseño en el que usaremos un LCD para información local y controlaremos un motor y un led de forma remota mediante un ordenador usando el modo USART.

>Para encender el motor se debe enviar la letra _a_ desde el ordenador, en LCD mostrará un mensaje indicando que el motor está encendido y el motor se encenderá, la letra _b_ debe ser enviada para apagar el motor y mostar en el LCD el mensaje correspondiente a motor apagado.

>Para encender el LED se se envia la letra c y la d para apagarlo, ambos estados son mostrados de forma local en el LCD.
***

<center> 
![](https://images.ecency.com/DQmczM7a9KmmMyQBkjC3XmtE4rfe2JAjBjiMGaHFQjhHtYT/image.png)
</center>

<center>
<table>
<thead>
<tr><th><center><div class="phishy">Programming</div></center></th></tr>
</thead>
<tbody>
</tbody>
</table>
</center>

We write our configuration lines including the parameters for the USART communication and the LCD. We also add the stdio.h library.
***
>Escribimos nuestras líneas de configuración incluyendo los parámetros para la comunicación USART y el LCD. Añadimos también la librería stdio.h
***

~~~
#include <16f877a.h>

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

#use delay(clock=20M)

#use RS232(BAUD=9600, BITS=8, PARITY=N, XMIT=PIN_C6, RCV=PIN_C7)

#use standard_io(D)

#include <stdio.h

#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 
~~~

To store the data received from the external device we are going to create the variable usart_rx of type char, our motor will be connected to PIN_D0 and our LED to PIN_D1, to avoid that they turn on by mistake when starting the program we force the initial shutdown, later we initialize the LCD and show a welcome massage, this will only be shown once on the LCD when the program starts.
***

>Para almacenar el dato recibido desde el dispositivo externo vamos a crear la variable usart_rx de tipo char, nuestro motor estará conectado al PIN_D0 y nuestro LED al PIN_D1, para evitar que enciendan por error al iniciar el programa obligamos el apagado inicial, posteriormente inicializamos la LCD y mostramos un masaje de bienvenida, este solo se mostrará una vez en el LCD cuando se inicia el programa.
***

~~~
char usart_rx;

void main()

{

   output_low(PIN_D0);                           

   output_low(PIN_D1);

   lcd_init(); 
   
   lcd_clear();

   lcd_gotoxy(1,1);

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

   lcd_gotoxy(1,2);

   printf(lcd_putc,"USART reception");

   lcd_gotoxy(1,3);

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

   lcd_gotoxy(1,4);

   printf(lcd_putc,"Original Content");

   delay_ms(400);
~~~

The first thing we will do in our while loop will be to set a conditional _if(kbhit() > 0)_ we use kbhit to determine when a data has been received, then we store it in the variable we created and set the switch function with 4 cases that will execute the required actions regarding the led and motor.

In each case, in addition to the message on the LCD, a message will be sent to the computer to confirm that the data was received.
***
>Lo primero que haremos en nuestro bucle while será establecer un condicional _if(kbhit() > 0)_ usamos kbhit para determinar cuando se haya recibido un dato, entonces lo almacenamos en la variable que creamos y establecemos la función switch con 4 casos que ejecutarán las acciones requeridas respecto al led y motor.

>En cada caso, a parte del mensaje en el LCD se enviará un mensaje al ordenador para confirmar que se recibió el dato.
***

~~~
 while(true)

   {

      if(kbhit() > 0)                           

      {

         usart_rx = getc();                      
         
         switch(usart_rx)

         {

            case 'a':                          

            output_high(PIN_D0);

            printf("Motor: ON\r\n");

            lcd_clear();

            lcd_gotoxy(1,1);

            printf(lcd_putc,"USART reception");

            lcd_gotoxy(1,2);

            printf(lcd_putc,"Motor: ON");

            lcd_gotoxy(1,3);

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

            lcd_gotoxy(1,4);

            printf(lcd_putc,"Original Content");

            delay_ms(400);

            break;
         
            case 'b':                           

            output_low(PIN_D0);

            printf("Motor: OFF\r\n");

            lcd_clear();

            lcd_gotoxy(1,1);

            printf(lcd_putc,"USART reception");

            lcd_gotoxy(1,2);

            printf(lcd_putc,"Motor: OFF");

            lcd_gotoxy(1,3);

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

            lcd_gotoxy(1,4);

            printf(lcd_putc,"Original Content");

            delay_ms(400);

            break;
         
            case 'c':                           

            output_high(PIN_D1);

            printf("LED: ON\r\n");

            lcd_clear();

            lcd_gotoxy(1,1);

            printf(lcd_putc,"USART reception");

            lcd_gotoxy(1,2);

            printf(lcd_putc,"LED: ON");

            lcd_gotoxy(1,3);

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

            lcd_gotoxy(1,4);

            printf(lcd_putc,"Original Content");

            delay_ms(400);

            break;
         
            case 'd':                           

            output_low(PIN_D1);

            printf("LED: OFF\r\n");

            lcd_clear();

            lcd_gotoxy(1,1);

            printf(lcd_putc,"USART reception");

            lcd_gotoxy(1,2);

            printf(lcd_putc,"LED: OFF");

            lcd_gotoxy(1,3);

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

            lcd_gotoxy(1,4);

            printf(lcd_putc,"Original Content");

            delay_ms(400);

            break;

         }

      }

   }

}
~~~
 
<center>
<table>
<thead>
<tr><th><center><div class="phishy">Simulation</div></center></th></tr>
</thead>
<tbody>
</tbody>
</table>
</center>

For our simulation we will turn on the circuit and after the welcome message using the Hercules program will send an _a_ letter to turn on the motor, then a _b_ to turn it off, then a _c_ to turn on the LED and finally a _d_ to turn it off, we will evaluate the behavior of the system during the process.

***
>Para nuestra simulación encenderemos el circuito y luego del mensaje de bienvenida mediante el programa Hércules se enviará una letra _a_ para encender el motor, posteriormente una _b_ para apagarlo, luego una _c_ para encender el LED y finalmente una _d_ para apagarlo, evaluaremos el comportamiento del sistema durante el proceso.
***

<center>
![](https://images.ecency.com/DQmNkGP5RrUBmK5e354xL3GDTsKrP4EJyZv2DiVqdtUcWjg/usart_rx.gif)
 </center>

***
***
***
***
***
***
***
https://images.ecency.com/p/3W72119s5BjW4PvRk9nXBzqrPWMsMTjNrXDPFFf12CAfRz5MY8jCm5vGDUj7o96hwAT3YCMBJgcTgcWmsqeuBbZL1YbmxtaV4gyfByenDkmAkgv6rkm9ZP.webp?format=webp&mode=fit

<div class=pull-left> 
<div class=pull-left> 
 https://images.ecency.com/DQmaByZ2ZkKHjeSRhs1myrJNzEepPZJwbjLPgp7go8wkBtq/stemsocial.gif 
 </div> 

  <div class=pull-right> 
https://images.ecency.com/DQmfD2byptG1NdjVeJM8EzP8oukEJRPTyKbDEzJg3WpiVZG/ecency.gif 
</div>
</div> 
 
<div class=pull-right>

<div class=pull-left> 

https://images.ecency.com/DQmRF5bXKk4fsa3i2fPK8aHCNYbMZE4WSdzzpcLcoyWxge5/hive.gif 

</div>

<div class=pull-right>

https://images.ecency.com/DQmSBycibSkrnco3Ee5eiJ1cMwPoPrfbrrbirNiiYXPLx7e/thankyou.gif 
</div>
</div>

<center>![](https://images.ecency.com/DQmWaaRYnUU8YbvG53M2CDBq1Z8NTaDMqffgDqQPQdbktRP/image.png) ![](https://images.ecency.com/DQmWMb7UWTpsP83M7fvHB4NQ57whh5xBzvHcKKknCJRBUSU/20221228_185126.gif)![](https://images.ecency.com/DQmWMb7UWTpsP83M7fvHB4NQ57whh5xBzvHcKKknCJRBUSU/20221228_185126.gif)![](https://images.ecency.com/DQmWMb7UWTpsP83M7fvHB4NQ57whh5xBzvHcKKknCJRBUSU/20221228_185126.gif)![](https://images.ecency.com/DQmWMb7UWTpsP83M7fvHB4NQ57whh5xBzvHcKKknCJRBUSU/20221228_185126.gif)![](https://images.ecency.com/DQmWMb7UWTpsP83M7fvHB4NQ57whh5xBzvHcKKknCJRBUSU/20221228_185126.gif)![](https://images.ecency.com/DQmWMb7UWTpsP83M7fvHB4NQ57whh5xBzvHcKKknCJRBUSU/20221228_185126.gif)![](https://images.ecency.com/DQmWMb7UWTpsP83M7fvHB4NQ57whh5xBzvHcKKknCJRBUSU/20221228_185126.gif)</center>
</div>



👍 , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,