# 14 - Motor DC + Sensor IR Sharp GP2Y0A21

> #### MPLAB X IDE - XC8 Compiler
>
> [**PIC18F4550 / PIC18F45K50**](https://docs.microside.com/practicas/mplab-x-ide/xc8-compiler/pic18f4550-or-pic18f45k50)

<figure><img src="/files/C0BkpeIPVlNFpcOqGl4k" alt=""><figcaption></figcaption></figure>

## **Introducción**

En esta práctica se implementa el control de un motor de corriente directa, usando los módulos PWM y ADC a través de un sensor SHARP para variar la velocidad. La velocidad del motor, depende de la distancia que halla entre un objeto y el sensor infrarrojo.

## **Descripción**

En esta práctica se realiza el control de velocidad de un motor DC, usando los módulos internos ADC y PWM por medio de un sensor Sharp conectado a la tarjeta **X-TRAINER** con el **PIC18F4550/PIC18F45K50**.

**Materiales:**

1 x Tarjeta **X-TRAINER**. [**Manuales**](https://docs.microside.com/tarjetas-de-desarrollo/x-trainer) | [**Comprar**](https://www.microside.com/shop/category/entrenadores-pic-1)

1 x Módulo programador **XCU** o **XCU Lite.** [**Manuales**](https://docs.microside.com/programadores-pics-and-avrs/pic-and-avr) **|** [**Comprar**](https://www.microside.com/shop/category/programadores-pics-avrs-15)

1 x Sensor IR Sharp GP2Y0A21.

1 x Motor DC 5 a 12 volts.

1 x Transistor NPN 2N3904.

1 x Diodo 1N4001.

1 x Juego de cable Dupont.

1 x Protoboard de 830 puntos.

1 x Cable micro USB.

**Software:**

Windows 7 o posterior.

MPLAB X IDE. [**Descarga**](https://www.microchip.com/mplab/mplab-x-ide)

Compilador XC8. [**Descarga**](https://www.microchip.com/en-us/development-tools-tools-and-software/mplab-xc-compilers)

X-TRAINER Suite v1.0 [**Descarga**](https://raw.githubusercontent.com/MICROSIDE-TECHNOLOGY/microside_download_archive/main/Tools/X-TRAINER%20Suite/X-TRAINER%20Suite%20Setup.zip)

MPLAB Code Configurator. (**Solo para PIC18F45K50**)

## **Procedimiento**

1. En el apartado de “[**Diagrama esquemático**](#diagrama-esquematico)” selecciona el modelo de tu tarjeta, realiza las conexiones que se muestran en la imagen y conéctala a la computadora.

{% hint style="info" %}
Las conexiones mostradas en los diagramas esquemáticos son las mismas ya sea que la tarjeta **X-TRAINER** posea el **PIC18F4550** o el **PIC18F45K50**.
{% endhint %}

2. Ejecuta **MPLAB X IDE** y crea un nuevo proyecto con el código fuente que se encuentra en el apartado "[**Código**](#codigo)".
3. Si cuentas con un **PIC18F45K50** ejecuta MCC (MPLAB Code Configurator) y configura los diferentes apartados como lo muestran las siguientes imágenes.

{% hint style="warning" %}
En caso de utilizar un **PIC18F4550** omite este paso.
{% endhint %}

* [**Project Resources**](https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FbyV2zAlQAiqg46a3Lr8z%2Fuploads%2FkwlTbGNpaGD5K7jjjOc5%2F14_Project_Resources.webp?alt=media\&token=c2bbbd1d-079d-4bc2-81a5-4e5d4293ea5b)
* [**System Module**](https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FbyV2zAlQAiqg46a3Lr8z%2Fuploads%2FQTMNxSn6cdueEnhmCoK9%2F00-comun-System_module-2.webp?alt=media\&token=9414df21-65d2-4454-a5a5-8f429219f5f6)
* [**Device Resources**](https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FbyV2zAlQAiqg46a3Lr8z%2Fuploads%2F7gO2hUCwNSkYpIzQoPu2%2FComun%20Device%20Resource.webp?alt=media\&token=0eef8588-1608-4550-8b5a-f7c3c24bdde3)
* [**Pin Manager**](https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FbyV2zAlQAiqg46a3Lr8z%2Fuploads%2F4cuAwuUccmHd5M4usnXN%2F14_PIN_MANAGER.webp?alt=media\&token=68c9ee54-c871-4c08-b3d4-1aa4399f9606)
* [**Pin Module**](https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FbyV2zAlQAiqg46a3Lr8z%2Fuploads%2Fxj7VZNnVkY5gwC49dKCd%2F14_PIN_MODULE.webp?alt=media\&token=0e2c6658-1736-446a-80d8-a1d8423ce0b5)
* [**ADC**](https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FbyV2zAlQAiqg46a3Lr8z%2Fuploads%2FFc2JjJuSdgPn13ctOzV3%2F14_ADC.webp?alt=media\&token=86d62318-3a8d-4463-be01-107fefed0a50)
* [**ECCP**](https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FbyV2zAlQAiqg46a3Lr8z%2Fuploads%2FSP2MFzQfOp67o69EMdNm%2F14_ECCP1.webp?alt=media\&token=d209a541-ae73-4a55-9ccf-b7cdb9b8d68a)
* [**TMR**](https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FbyV2zAlQAiqg46a3Lr8z%2Fuploads%2FJNzrSw7pJCQCnv8xthFp%2F14_TMR2.webp?alt=media\&token=5aad7e56-be66-4e75-a2cb-de92b0a65889)

{% hint style="success" %}
Si tienes dudas de cómo realizar los pasos anteriores puedes encontrar un manual de **MCC (MPLAB Code Configurator)** a través del siguiente [**link**](https://docs.microside.com/practicas/ides/mplab-code-configurator-mcc-mplab-x-ide).
{% endhint %}

4. Realiza los siguientes pasos para configurar el **bootloader** y poder programar la tarjeta **X-TRAINER**:

* Da clic en ***File*** y ***Project Properties***.

<figure><img src="/files/w3YBeDvjt6V6sE8wmGk4" alt=""><figcaption></figcaption></figure>

* Selecciona ***Building***, marca la casilla ***Insert unprotected checksum in user ID memory*** y da clic en ***Apply***.

<figure><img src="/files/tQDojxU2AE1llBIP8s7f" alt=""><figcaption></figcaption></figure>

* Selecciona ***XC8 Linker***, despliega el apartado ***Option categories***: y selecciona ***Memory model**.* \
  En la sección de ***ROM ranges*** escribe **2000-7f00** y da clic en ***Apply***.&#x20;

<figure><img src="/files/Q8RITTGjuTkTM4IiJx43" alt=""><figcaption></figcaption></figure>

* Despliega nuevamente el apartado ***Option categories:*** y selecciona ***Additional options***. En la sección de ***Codeoffset*** escribe **2000**, da clic en ***Apply*** y por último da clic en ***OK***.

<figure><img src="/files/e6TWqujDRyKaCgXz785a" alt=""><figcaption></figcaption></figure>

5. Una vez realizadas las configuraciones del bootloader compila el proyecto.

{% hint style="success" %}
Para compilar el proyecto dirígete a la barra de herramientas superior y da clic en el icono señalado.
{% endhint %}

<figure><img src="/files/s9YbKLFqdHRHtw6uYviM" alt=""><figcaption></figcaption></figure>

6. Abre el **Software X-TRAINER Suite v1.0** en el apartado **PIC18F4550/45K50**, selecciona el archivo .hex generado al compilar el proyecto y programa la tarjeta.

{% hint style="success" %}
Si tienes dudas de cómo realizar los pasos anteriores puedes encontrar un manual del **Software X-TRAINER Suite v1.0**. a través del siguiente [**link**](https://docs.microside.com/manuales-de-usuario/software-x-trainer-suite).
{% endhint %}

7. Al terminar de programar, la tarjeta **X-TRAINER** se reiniciará automáticamente y se ejecutará el programa de esta práctica.

## **Diagrama esquemático**

Selecciona el modelo de tu tarjeta **X-TRAINER.**

{% tabs %}
{% tab title="LITE M R2" %}

<figure><img src="https://raw.githubusercontent.com/MICROSIDE-TECHNOLOGY/14-DC-GP2Y0A21-MPLAB-X-IDE-XC8-COMPILER-PIC18F4550-45K50/main/Diagrama%20de%20conexión/X-TRAINER_Lite-M-r2_Practica-14_Microside_02.png" alt=""><figcaption></figcaption></figure>
{% endtab %}

{% tab title="LITE M R3" %}

<figure><img src="/files/xgXHkbMJkLtHDDEjQGWP" alt=""><figcaption></figcaption></figure>
{% endtab %}

{% tab title="LITE F" %}

<figure><img src="https://raw.githubusercontent.com/MICROSIDE-TECHNOLOGY/14-DC-GP2Y0A21-MPLAB-X-IDE-XC8-COMPILER-PIC18F4550-45K50/main/Diagrama%20de%20conexión/X-TRAINER_LITE-F_Practica-14_Microside_01.png" alt=""><figcaption></figcaption></figure>
{% endtab %}

{% tab title="DIP" %}

<figure><img src="https://raw.githubusercontent.com/MICROSIDE-TECHNOLOGY/14-DC-GP2Y0A21-MPLAB-X-IDE-XC8-COMPILER-PIC18F4550-45K50/main/Diagrama%20de%20conexión/X-TRAINER_DIP_Practica-14_Microside_01.png" alt=""><figcaption></figcaption></figure>
{% endtab %}

{% tab title="DIP R3" %}

<figure><img src="/files/Gv4cLciOeo6BGYmroTwz" alt=""><figcaption></figcaption></figure>

{% endtab %}

{% tab title="PRO R2" %}

<figure><img src="https://raw.githubusercontent.com/MICROSIDE-TECHNOLOGY/14-DC-GP2Y0A21-MPLAB-X-IDE-XC8-COMPILER-PIC18F4550-45K50/main/Diagrama%20de%20conexión/X-TRAINER_PRO-r2_Practica-14_Microside_01-1.png" alt=""><figcaption></figcaption></figure>
{% endtab %}

{% tab title="PRO R3" %}

<figure><img src="/files/flQdGSlqYwD8L8QjXeTG" alt=""><figcaption></figcaption></figure>
{% endtab %}

{% tab title="PRO R4 " %}

<figure><img src="/files/ktT4usmKK8GCnhptUwo8" alt=""><figcaption></figcaption></figure>
{% endtab %}
{% endtabs %}

## **Código**

{% tabs %}
{% tab title="PIC18F4550" %}
{% embed url="<https://gist.github.com/microside-mx/1527f0f6d0d993f810fd6888dadfd8ac>" %}
{% endtab %}

{% tab title="PIC18F45K50" %}
{% embed url="<https://gist.github.com/microside-mx/a824cf4f66e2b82fe0a847c8d779392d>" %}
{% endtab %}
{% endtabs %}

## **Descargas**

<table data-card-size="large" data-view="cards"><thead><tr><th align="center"></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td align="center"><mark style="color:green;"><strong>Software X-TRAINER Suite v1.0</strong></mark></td><td><a href="https://raw.githubusercontent.com/MICROSIDE-TECHNOLOGY/microside_download_archive/main/Tools/X-TRAINER%20Suite/X-TRAINER%20Suite%20Setup.zip">https://raw.githubusercontent.com/MICROSIDE-TECHNOLOGY/microside_download_archive/main/Tools/X-TRAINER%20Suite/X-TRAINER%20Suite%20Setup.zip</a></td></tr><tr><td align="center"><mark style="color:green;"><strong>Proyecto</strong></mark></td><td><a href="https://github.com/MICROSIDE-TECHNOLOGY/14-DC-GP2Y0A21-MPLAB-X-IDE-XC8-COMPILER-PIC18F4550-45K50/archive/refs/heads/main.zip">https://github.com/MICROSIDE-TECHNOLOGY/14-DC-GP2Y0A21-MPLAB-X-IDE-XC8-COMPILER-PIC18F4550-45K50/archive/refs/heads/main.zip</a></td></tr></tbody></table>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.microside.com/practicas/mplab-x-ide/xc8-compiler/pic18f4550-or-pic18f45k50/14-motor-dc-+-sensor-ir-sharp-gp2y0a21.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
