Posted on

Interfacing DC Motor with PIC Microcontroller

Interfacing DC Motor with PIC Microcontroller is the second tutorial in a series of tutorials on Design Embedded System with PIC Microcontroller.

In case you are new to PIC Microcontroller and MPLAB X IDE I strongly suggest to visit the tutorial – Getting started with MPLAB X IDE. If this is your first interfacing with PIC microcontroller please go through Interfacing LED with PIC Microcontroller tutorial for a complete overview of the programming and execution process.

For interfacing DC Motor with PIC Microcontroller we will require the following components which can be purchased in OpzLab web store. Links to the individual components are also provided.

  1. PICKIT3 Debugger / Programmer
  2. PIC16F15325
  3. Mini Breadboard
  4. Power Supply
  5. DC Motors
  6. L298N Motor Driver
  7. Jumper Wires

Follow the below tutorial to run the DC Motors in forward, reverse, left and right direction for every 10 seconds from MPLAB X IDE

Start MPLAB X IDE and Create new Project

Open MPLAB Code Configurator and after initial MCLRE and Low Voltage configuration setup the digital output ports.

Save and generate the headers and source files. Update the source file main.c with below code.

#include "mcc_generated_files/mcc.h"

#define MOTOR_L_R RA2   // Left Motor Red Terminal
#define MOTOR_L_B RC0   // Left Motor Black Terminal
#define MOTOR_R_R RC1   // Right Motor Red Terminal
#define MOTOR_R_B RC2   // Right Motor Black Terminal

void forward() {
    MOTOR_L_R = 1;
    MOTOR_L_B = 0;
    MOTOR_R_R = 1;
    MOTOR_R_B = 0;
}

void reverse() {
    MOTOR_L_R = 0;
    MOTOR_L_B = 1;
    MOTOR_R_R = 0;
    MOTOR_R_B = 1;
}

void left() {
    MOTOR_L_R = 0;
    MOTOR_L_B = 0;
    MOTOR_R_R = 1;
    MOTOR_R_B = 0;
}

void right() {
    MOTOR_L_R = 1;
    MOTOR_L_B = 0;
    MOTOR_R_R = 0;
    MOTOR_R_B = 0;
}

void stop() {
    MOTOR_L_R = 0;
    MOTOR_L_B = 0;
    MOTOR_R_R = 0;
    MOTOR_R_B = 0;
}

void main(void) {
    SYSTEM_Initialize();
    while (1) {
        forward();
        __delay_ms(10000);
        reverse();
        __delay_ms(10000);
        left();
        __delay_ms(10000);
        right();
        __delay_ms(10000);
        stop();
        __delay_ms(20000);
    }
}

Connect the circuit as shown below.

Hit the Download button to program and run the device from MPLAB X IDE. The pic microcontroller will be programmed after few seconds, the program will run the dc motors in forward, reverse, left and right directions per 10 seconds each.