Quantcast
Channel: RON ROBOTICS - PIC18F4550
Viewing all 25 articles
Browse latest View live

PIC18F4550 Programming and Tutorial Hardware C

$
0
0

PIC18F4550 Microcontroller Tutorial using  Mplab IDE and C18 Compiler


PIC18F4550 Programming Tutorial in Hardware C
PIC Tutorial , Mplab IDE - C18 compiler toolsuite
PIC18F4550 tutorial, Looking the data sheet | Ports
PIC18F4550 Programming method 1 Project Blink led
PIC18F4550 Programming Method 2 Blink led
PIC18F4550 programming tutorial method 3
PIC18F4550 Programming Method 3 TRISB
PIC18f4550 ADCON Basics.
PIC18F programming | Using header files.
PIC18F4550 programming function prototypes
pic18f4550 Microcontroller Input methods

 

 

PIC18F Microcontroller Programming Tutorial


Tutorial Introduction

Welcome, here in this tutorial series we are going to learn some common methodologies for programming a pic18f. The tutorials here must be perfect to get you started with pic18f microcontroller. We are going to learn about the basics and various details that you need to consider while programming a pic18f microcontroller. For making life easy I have also attached relevant coding examples with explanation with each chapter of the tutorials that I am going to show.   Programming a pic18f Microcontroller with Hardware C

This tutorial is compiled for beginners with pic18f microcontrollers, who wish to learn microcontroller coding in Hardware C. We are also going to see the software tools, understand Microcontroller pin diagram, Ports and its relevance, Programming and relevant data sheet of the microcontroller, and I will also explain where and what to look for in a datasheet, as it can be confusing for beginner. Please do to complain if you find the tutorial a bit lengthy, but shortcuts are never good choice. A navigation menu on the Top must be helpful for you to switch between topic and chapters.

 

There are many ways or styles to code a simple microcontroller program. What is really necessary is to develop a perfect and good coding habit or methodology while you code, to avoid confusion. For doing a same logical operation there can be multiple ways in Hardware C. It will help you to optimize the coding you do.

Here I am going to explain some base line methods and also some common practices that you need to follow while coding a pic18f microcontroller with suitable examples. There can be hundred of ways of writing same code; I will just try to cover some of the basic styles to get you started, from Simple to complex ways. Once you understand the basics then it must be quiet easy for you to navigate your own imagination and make the microcontroller respond according to your wish.  I will try to explain each and every block with simple and easily understandable format. I would also try to avoid Complex terms whenever it is possible.
 

PIC18F inexpensive programming with hardware C

Pic microcontrollers are comparatively inexpensive and easy to find, there are also other microcontrollers Like Arduino Board which are little bit costly. Unless you want to spend too much for you projects, pic programming kit would be perfect to get you started. PIC18F is easily available and very powerful and quiet capable microcontroller which can easily enable you to add some Logic and Intel to your projects. All you need is a Microcontroller, An IDE and a Microcontroller programmer Like pickit2 or JDM.

Programming a PIC18F microcontroller using Hardware C

For our hardware C programming tutorial we are going to use a PIC18F4550 microcontroller. PIC18F4550 is a 40 pin microcontroller by microchip and it has been a favorite microcontroller in between microcontroller hobbyist. You can easily switch over to pic18f2550 microcontroller as well, with little modification in the code. However we are going to focus on pic18f4550 microcontroller for our tutorial with hardware C. After writing and understanding microcontroller Code we are going to upload the code into the microcontroller using hardware programmer.

If you wish to know in general about microcontroller when you can visit my What is a Microcontroller post. That should get you some basics of Microcontroller itself. For writing out first code we will need a microcontroller IDE and a Compiler to compile the microcontroller program.

Hardware C is similar to the general C software programming language that you compile with a BORLAND C compiler. However the compiler and Coding methods for Hardware C are going to be different. It depends upon the microcontroller. For coding a pic18f4550 you will need an IDE that supports the respective microcontroller and also a Compiler that can compile the code written on the IDE.

What is IDE?  Don’t confuse IDE with “Integrated Device Electronics”, Here IDE is just an abbreviation for Integrated Development Environment which is a software environment for writing codes. IDE makes life really easy for coders.

Before we can Start coding we need out weapons.

The IDE that we are going to use is microchips ”MPLAB IDE“and the compiler would be “ C18 compiler “ from Microchip . MPLAB IDE will help you with a Software platform where you can write your Hardware Code, ( Just like Eclipse IDE ).  And the Compiler installed with MPLAB IDE will convert the Human written code into Machine language.

 Please note that the microcontroller can only understand the machine language (0 and 1). The code [instructions] written in the IDE is converted into “Machine code” by the compiler.  After compilation the output will be generated in .hex format (A filename with .hex) [ AN Example .hex ], all we have to do is just to upload that .HEX file into the microcontroller and then the pic18f4550 is ready for action.

 

MPLAB IDE and C18 Compiler output hex

 

There are different types of compiler. Suppose if you working with a PIC30F series microcontroller then the same MPLAB IDE will require a C30 Compiler engine to Compiler your code. C30 and C18 are just the versions of compiler which is capable of Converting your code into machine language (0’s and 1’s) which a microcontroller would understand.

However since we are going to use a “PIC18F“ series of microcontroller so we will use a C18 compiler.

A lite version of C18 compiler and MPLAB ide is completely free to download from Microchips website. Apart form C18 Compiler, a Hi-Tech C compiler can be also used for coding a pic18f4550 series of microcontroller. Hi-Tech C makes it easy to write codes specially when I prefer to write LCD programs, Hi-Tech C compiler is however not free if you wish to optimize the code, So we are going to Stick to C18 Compiler, lite version.

You need to login into microchip account which is free to create before you can download the C18 lite version and MPLAB IDE. The mplab refered in this tutorials is version v8.60. You can download the latest Release from their website directly.

-DOWNLOAD C18 Lite Version Compiler
-DOWNLOAD MPLAB IDE

 

Once you are downloading the MPLAB and C18 Compiler then move on to next tutorial section which would deal with setting up your project for the first time.

Chapter 2 pic18f4550 programming , mplab and C18 compiler | Project SettingsChapter 3 for pic18f4550 programming , Source code and program

 

 

PIC18F4550 Programming tutorial chapter 4 and method 2 for programmingMplab X IDE Tutorial For blinking an LED and Comparison with Mplab IDE - See more at: http://www.rakeshmondal.info/Mplab-X-IDE-XC8-Tutorial-Blinking-LED#sthash.eKp9YGIb.dpuf

 

 

 

 

 

 

 

NEXT Tutorial 2

Tutorial 3 - Blinking an LED Method-1

Tutorial 4- Blink LED Method-2 Header

Tutorial 5- Blink LED -Mplab X IDE - XC8

PIC18F2550 - Blink LED - XC8 Compiler


 


Mplab Ide and C18 Compiler configuration

$
0
0

PIC18F4550 Microcontroller Tutorial Mplab IDE and C18 compiler

 
 
 
 

Configuring MPLAB and C18 Compiler,Setting up your first Project


Mplab Ide Installation
C18 Compiler Toolsuite Inslallation
Toolsuite Settings and creating a new project
Library and Path settings


Introduction

Configuring MPLAB with C18 compiler and setting your first project requires some basic set of things which need to be kept in mind all the time while you carry on to avoid un necessary pain. In my previous pic18f4550 programming post we got a quick preliminary description about Programming a Microcontroller. I am assuming that you have already downloaded the tools from, microchip (MPLAB IDE and C18) Compiler from the links provided from the previous post.

If installation for Mplab and C18 Compiler went well for you then, you can quickly skip this part of tutorial and go on the next part with for coding your pic18f4550 microcontroller. PIC18F4550 Blinking LED Method - 1.

Next stage would be to install the weapons, (tools) that we download in our previous post for the war to be won. Snapshot below describes the steps of installation, Configuration of C18 Compiler, creating project and Setting up compiler, library and directories on windows XP OS. Installation and settings won’t be much of a different taste for other Windows OS as well.

 

First Install the MPLAB IDE from the setup file you downloaded.

All the system files for MPLAB IDE would be installed in
C:\Program Files\Microchip\MPLAB IDE

All the core files are located in
C:\Program Files\Microchip\MPLAB IDE\Core

Incase if in future you loose the shortcut then you can start mplab from
C:\Program Files\Microchip\MPLAB IDE\Core\MPLAB.exe

 

C18 Compiler Toolsuite Installation


 

All right that enough of MPLAB IDE. Let’s gets go on to C18 compiler now. The lite version of c18 Compiler that we are installing here is version v3.41.

 

Next you have to run the C18 Compiler setup for installation. The C18 compiler will detect the MPLAB and will install accordingly.

C18 Compiler installation C18 Compiler installation settings

 

After Installation of C18 Compiler, all the necessary compiler files, Headers, Linker and few Example coding will be installed in following directory.

C:\Program Files\Microchip\mplabc18

You can review short example programs
C:\Program Files\Microchip\mplabc18\v3.41\example

Microchip always documents its releases very nicely. Quick getting started documents can be found in

C:\Program Files\Microchip\mplabc18\v3.41\doc\MPLAB-C18-Getting-Started_51295f.pdf

A personal recommendation. Don’t delete the Setup files after installation. You might need it someday in future just incase if you have to reinstall everything from beginning.

 

 

After installation of Mplab and C18, next step is to create a new project from Project Wizard. All the coding would be handled as individual projects which would contain various the blocks of code interconnected.

For demo purpose we are going to create a Dummy project to understand the project setting.  First create a new folder in your desktop or on your desired location manually. In our tutorial I have created a folder on Desktop “Project1”. All the project files will be stored here; don’t forget the location where you created your project folder. 

 

So First start MPLAB IDE, which would start blank as an “Untitled Workspace”.

Mplab ide blank workspace

 

Project Wizard

Create a new project by proceeding through project wizard from top file menus that would help you to setup the setting for your first new project. Project wizard would give you options to select your microcontroller which you intent to code and also it will load the necessary tool suite that you need for project.

mplab ide project wizard settings

 

 

 

 

 

Project Wizard

 

 

Select the microcontroller from the drop down list menu, which in our case is PIC18F4550.

pic18f4550 settings for mplab ide project

 

 

 

 

 

 

 

ToolSuite Selection

Next step would be to select the Toolsuite.
In our case we are going to use C18 Compiler Toolsuite, so while creating the project from project wizard when it prompts, select C18 Toolsuite from the top drop down menu.

c18 Compiler toolsuite Selection

 

 

 

 

 

 

 

 

 

From Drop down menu select Microchip C18 Toolsuite
Most of the time the default would be Microchip C18 Toolsuite if you haven’t installed any other Toolsuite.

Select the Microchip C18 Toolsuite from Active Toolsuite drop down menu and go on to next settings with defaults.

C18 compiler toolsuite

 

 

 

 

 

 

 

 

 

Next step is to give a name to your project, hit browse and Navigate to the location where you created a folder in the beginning of this session. The folder which was created in the beginning was named as project1 for this tutorial. Navigate to the folder that you created.

Folder location for project

Navigate inside the folder and then name the new Project. And then click next.

In the next screen Mplab would prompt you to add some files to your project. This prompt would help you to add already coded files. Since we don’t have anything yet coded for our pic18f4550 so proceed with next button leaving things untouched.

Project Parameter Summary for pic18f4550

 

 

 

 

 

 

 

 

 

 

When everything is done mplab would display Project Summary with all project parameters such as Device name, Toolsuite and location of the project. Hit finish.

Your project settings are now ready. Created project can be viewed in the same folder where you saved your project few seconds ago. The main project file would be yourprojectname.mcp ( the name which you gave to the project while creating the project inside the folder where you saved ). You can always launch the entire project with your project name. For this tutorial its been named as  project1.mcp inside the main project folder project1.

 

  • Project1 (project Folder)
    • Project1.mcp (Project name)

 

The Project which is created now would be blank without any coding.

 

Blank project with mplab ide

 

Adding a new C File         

Now since we have created a project, now we have to add C files for writing our code.

Create a new file by either clicking on File > New or click on New File icon.

Create a new File

 

 

 

 

That would create a new untitled file. Write some dummy string and then hit save. Name the file while saving it. In our case we would name it as main.c.

 

NOTE:* While saving the file, remember to check the box. “Add this file to project” or the file saved will not be added to the project workspace and the main.c will be missing from project file explorer.

Add files to the project setings

 

 

 

 

 

 

 

 

 

The new added C file would be enlisted in the project explorer Under “Source Files”. Now we have successfully added a C file for writing the codes.

 

Project after the files added in the mplan ide

You can review the build (Compile) setting for your Project under the menu
Project > Built Options> Project

 

Built options in the Mplab IDE

 

 

 

 

 

 

 

 

 

 

Directory settings for mplab Current project

 

 

 

 

 

 

 

 

 

Built options

 

By default when the Microchip C18 Toolsuite was chosen from project wizard, it added the directory paths for the links and library setting for the project, which includes the links to the linker files for linking and other necessary libraries. Just incase if the library settings are not set then you can review the setting under the Directory Search Paths.

 

From drop down menu under the Directories select Library Search Path.

Library Search path setting for mplab project

 

 

 

 

 

 

 

 

 

After selecting the Library Search Path, if you find it empty then you can add the path manually.

C:\Program Files\Microchip\mplabc18\v3.41\lib

 

 

Output Path Setting

By default if you don ’t choose an output folder then all files created during the compilation of the program would be directly dumped into the main project folder (Project1 folder) where you created the project. That would make things looks messy after you compile, and you would find some extra files that compiler generated during compilation.

To avoid that it’s recommended to add a separate output folder. So that compiler would dump all the files into the Output folder including your .hex file which is your final outcome before burning it into the microcontroller.

  • Create a new Folder inside the main Project folder and name it as output.
  • Open the Directory Setting in the project Built Option

 

 

Output Directory settings for Mplab IDE

  • Select the option from drop down as “Output Directory”

 

Output Directory settings select location

 

 

 

 

 

 

 

 

 

  • Hit the browse icon and locate the main project1 folder and then select the folder you just created with name “Output” and then apply settings.

 

Henceforth whenever you would compile any project all the runtime files and output hex files would be dumped in the output folder. That would make life easy in future.

Hence now we are completely set with MPLAB IDE, compiler and Project settings .. So lets carry on with our first setting on real time coding with hardware c.

 

 Blinking a led – Method 1

 

PreviousNext
 

Thanks for Reading
Ron

 



 

PIC18F4550 Microcontroller

$
0
0
PIC18F4550 Microcontroller Datasheet and pinout

PIC18F4550 Microcontroller


Summary
Features
Pin Out
Ports
Datasheet
Miscellaneous

PIC18F4550 belongs to pic18f family of microcontrollers. PIC18F4550 is one among the advanced Microcontrollers from the microchip technology. This microcontroller is very famous in between hobbyist and learners due it functionalities and features such as ADC and USB Integration. A typical PIC18F4550 comes in various packages like DIP, QPF and QPN. These packages can be selected according to the project requirement.

 

PIC18F are inexpensive and Easy to Program

Features


PIC18F4550 is an 8 bit microcontroller. PIC18F4550 has been implemented with Nano WATT technology hence it requires very low power for its operation.

 

PIC18F4550 has 16 bitInstruction Set Architecture, (ISA) which provides a degree of freedom to programmers with various data types , registers ,  instructions, memory architecture, addressing modes, interrupt and IO operations. PIC18F4550 also has an Extended Instruction Set as a special feature; it’s an optional extension to the PIC18 instruction set.

Memory Specifications: A PIC18F4550 has 256 bytes of EEPROM (Electrically Erasable and Programmable Read Only Memory), 2KB of SRAM (Static RAM) and 32KB of flash memory which in return proves another degree of freedom to programmers.

Communication Protocol: PIC18F4550 is remarked as advanced, as it uses well sophisticated protocols for communications. The modern protocols like USB, SPI, EUSART, are well supported in PIC18F4550. These technologies integrate with Nano Watt Technology (as mentioned before) to produce PIC18F4550, a well equipped, low power consuming microcontroller. 

A Dedicated ICD/ICSP Port allows the programmers to code and debug easily.

  • Enhanced flash programme and the 1KB Dual Access RAM for USB are used for buffering.
  • PIC18F4550 consists of up to 13 channels for analog to digital converter. The converter accuracy amounts to 10-bit to convert analog to digital signal relatively.
  • PIC18F4550 is compatible to work with different internal and external clock sources. It comes with four built-in timers or an external oscillator can be interfaced for clocking.
  • The frequency limit for a PIC18F4550 is from 31 KHz to 48 MHz respectively.
  • The microcontroller PIC18F4550 comes with ADC comparators and other such peripherals as an in-built feature.

 

A very good description and in detailed features of PIC18F4550 microcontroller can be found in its respective datasheet. A copy of that PIC18F4550 Datasheet can be downloaded from microchip’s website.

 

PIC18F4550 supports USB functionality that it comes with a USB2.0 hardware inbuilt which can operate in two USB standard speeds.

       USB Speed supported by pic18f4550

  • Full speed 12 MBit per second
  • Low speed 1.2 MBit per second

The entire USB configuration is handled with UCFG register (USB CONFIGURATION REGISTER) which helps in defining the mode, or in which USB-speed the microcontroller should perform.  You can find more details about various USB Operation registers in PIC18F4550 like UCON, UCFG, USTAT, UADDR etc. from PIC18F4550 datasheet.

This PIC18F4550 microcontroller comes in varieties of pinout package, making it more usable for its users. The most commonly used package by hobbyist is 40 pin DIP – Dual Inline package structure (two rows of pins on either ends 20 left- 20 right).

40 PIN Package DIP (Dual Inline package)

PIC18F4550’s 40 pin DIP (Dual inline package) has got its special reputation in between hobbyist, it’s also easily available in any electronic store. DIP or Dual inline package is nothing but a typical microcontroller with two rows of pins on either side. A 40 pin DIP PIC18F4550 has 20 pin on each row.

PIC18F4550 40 Pin microcontroller  PDIP Package

 

 

 

 

 

 

 

 

 

44 Pin packages for PIC18F4550

44 pin packages are mostly focused on for production level devices, for other industries who wish to use them in their devices.

44-Pin QFP (Quad Flat Package) Pinout

44 Pin pic18f4550 TQFP Package

 

 

 

 

 

 

 

 

 

 

 

 

44-Pin QFN (quad-flat no-leads)  Pin out

44 Pin pic18f4550 QFN Package

 

 

 

 

 

 

 

 

 

 

40 pins of PIC18F4550 are divided into 5 ports. Out of which, 35 pins are Input-Output pins which can be configured for general  Input or Output by setting registers associated with them. Please Refer the Pinout diagram above for a clear idea about location of these pins on the microcontroller.

 

Ports           Number of pins   Pin Name

PORTA                  7            RA0-RA6
PORTB                  8            RB0-RB7
PORTC                  7            RC0-RC2, RC4-RC7 (Check the Pinout Diagram)
PORTD                  7            RD0-RD7
PORTE                  4            RE0-RE3

 

Registers Associated with Ports in PIC18F4550

Each port in pic18f4450 is associated with three 8 bit registers for IO operations.

  1. TRISX  (8 bit)
  2. LATx    (8 bit)
  3. PORTx  (8 bit)

TRISx : where X is the name of the ports either of A, B, C, D, E. For example TRISA, TRISB etc.This register assigns the direction of the pins (Input or Output). For example “TRISB = 0xF0”, will set all the pins in port B to Output.

LATX: The latch registers reds and modifies the write operation on the value of I/O pin and stored the output data that is to be passed on to the external hardware.

PORTX: Reads the device level, stores the Input level of the pins and reads and registers the input signal from the external device if the pin is configured as Input.

 

Datasheet


 

Microchip is very well known for its extremely good and detailed documentation. Please download a copy PIC18F4550 Data sheet from their official website for more detailed information.

Download PIC18f4550 Datasheet

PIC18f4550 Section

Programming Microcontroller

A C18 compiler with Mplab ide or Mplab X with XC8 Compiler must be good to getting started with programming a PIC18F4550. A free version of Software ide (Mplab and Mplab x) can be downloaded from microchip's website for getting started with pic18f4550. However other IDE software’s such as MikroC can also used for programming a pic18f4550.
A series of tutorial can help you learn to program a pic18f4550 microcontroller.

Tutorials

PIC18F4550 Programming with hardware C

MPLAB IDE AND C18

PIC18F4550 Blinking led | Method 1

PIC18F4550 Blinking led | Method 2

Mplab X IDE Programming Tutorial

 

Projects

Some projects on pic18f4550 Microcontroller for your reference.

USB Interface board

USB Demo Interface board

PIC18F4550 Stepper Motor Controlller

PIC18F4550 LCD Interface

USB Stepper Motor Driver ( PIC18F4550 )

USB DC motor Control

IR sensor

(IR) Infrared Sensor Interface with PIC18F4550


 

PIC18F4550 Tutorial: Blinking an LED

$
0
0

Blinking an led using pic18f4550 , Chapter 3 , pic18f4550 programming tutorial

 

 

PIC18F4550 Tutorial: Blinking an LED | Chapter 3


Welcome to my third chapter of this programming tutorial for pic18f4550. From here we will start on programming with pic18f4550, my previous tutorials ( Tutorial 1 and Tutorial 2 ) must have given you some outlines regarding the tools that we need and how to setup the project in details to get started.

This is the first method of programming a pic18f4550. For the sake of example, we are going to take a simple case of blinking an LED,  where we are going to blink two led's on pin RB0 and RB1. In coming chapters we are going to see how to blink the same thing in different ways. Our primary target is to learn various methodologies of Programming same thing in different ways to develop a perfect coding habit. 

Choose the coding method at your own discretion which suits perfect for your project requirement. Remember, the way you code, can save a lot of space.

First method is a direct and most common approach, where we are going to do all coding in one project file. MAIN.C. Here we are going to use Mplab ide and c18 compiler. It can be also done with Mplab X IDE , where there is no need of C18 compiler as the X8 compiler already includes all the necessary compiler files. However for this tutorial we will stick to Mplab IDE and C18.

Schematic

pic18f4550 schematic diagram to blink led

As mentioned before we are going to blink two led's on port B , RB0 and RB1.  Here is a sample schematic. The code can be easily modified to blink other led as well.

The input voltage must never exceed 5 V or it might damage the microcontroller, you can also use a IC 7805 Voltage regulator or mcp 1702 to ensure the input is 5V.

 

The circuit can be easily built on a breadboard in no time.

 

Let's Start with Coding

-Start MPLAB IDE and create a New Project as explained in the previous post for pic18f4550.

-Add a new file and save it as MAIN.C and save it in the project folder (Don’t forget to Check mark on “ADD to Project file”). You can use any name you wish..

- Now we have a blank empty project with a C file HOME.C

-Then start typing the source code as below.

Some of the sections in the code below are clickable to jump to the code explanation.

Source Code:

 

#include<p18f4550.h>                                               // Include Header for PIC18f455          
 

      /* ******COMPILER DIRECTIVES FOR CHIP CONFIGURATION BITS ***   */
#pragma config PLLDIV = 5 , CPUDIV = OSC1_PLL2 , USBDIV = 2    // You can write this way
// OR
#pragma config FOSC = INTOSCIO_EC
#pragma config FCMEN = OFF                                 // OR this way
#pragma config BORV = 3
#pragma config WDT = OFF
#pragma config CPB = OFF
#pragma config CPD = OFF

/*  ***************  TIMER *************** */
       void delayzz(void)
        {              int i, j;
                        for(i=0;i<5000;i++)
                {
                          for(j=0;j<2;j++)
                      {           /* Well its Just a Timer */            }    }   }
                           

               /* ****************** MAIN ****************** */

      void main(void)
         {
                        TRISB = 0xF0 ;                  // PORT B Setting: Set all the pins in port B to Output.
     
           while(1)  
                            {
                                LATBbits.LATB0 = 1;   // RB-1 to High  
                                LATBbits.LATB1 = 1;   // RB-1 to High

                                 delayzz();

                                LATBbits.LATB0 = 0;    // RB-0 to LOW
                                LATBbits.LATB1 = 0;    // RB-0 to LOW

                                 delayzz();

                              }
        }

/* THE END */

 

 

Download the code main.c or Download the entire Source code as Mplab Project.

Next step is to compile the code.

After the project is built the output files will be dumped into the same project folder, if a separate output folder is not defined for saving all the compiled files.

Now you can use your Programmer to burn the output .hex into the microcontroller.

Code Flow

-Define the header files for pic18f4550.
-Set the Microcontroller configuration settings with “compiler directives”.
-Define PORT settings:- The pins you want to use for blinking. Set the pin to output.
-Then set the timer:- For the time delay in-between the blinks.
-Define Pins to set as ON or OFF with a delay in-between.
-And finally make a loop where the main code will keep executing.
 

 

#include


Like most of the programming language first stage is to include/Import header files that we need to define. We are going to code a pic18f4550 hence we are going to include <p18f4550> header that contains all the respective settings and definitions of the microcontroller. 

Next stage is the pic18f4550 Configuration Bit settings. We need to set the chip configuration, settings for the pic18f4550, which is going to define the Configuration bits for the pic18f4550. For example: whether to use an internal or external oscillator, whether to keep watchdog timer on or off etc. All such settings are handled in Configuration bits setting in the beginning of the code block. If we don’t define the values then the microcontroller will take the default values which might lead to some trouble.

These configuration bits can be assigned with a Compiler directive “#pragma config

for example
             #pragma config WDT = ON // watchdog timer on.

For each Configuration Bits, you can write a new line or you can write multiple Chip config bit setting on single #pragma config Directive.

             #pragma config FCMEN = OFF  // Each line with individual setting
             #pragma config IESO = OFFF                            

OR
             #pragma configFCMEN = OFF, IESO = OFFF  //Single line with multiple settings.

You can find the all the Configuration bit settings in the Mplab notes.

-On the top menu on MPLAB IDE click on Help  >>  Topics..  >> PIC18F Config Settings 

-From the left pane go to PIC18F4xxx Configuration Settings and then select PIC18F4550 . It would list you all the configuration settings for pic18f4550.

 

PORT settings: TRISB = 0xF0


IF you want to use any pin in the microcontroller for any operation then you have to first set the pin to either for an input or out put. So you have to define the corresponding PORT to either Input or out put.

  TRISB = 0xF0 ;             // Set all the pins under PORT B to output.

 

PORTS

A typical pic18f4550 has 40 pins in it (if it’s a DIP). These 40 pins are divided (classified) into a Logical name PORTS. There are 5 ports in a pic18f4550, PORTB is one of such ports.
Each port is associated with few pins. These ports are accessed by some registers, TRISx register is one of such register to access the corresponding port.

 

TRISB

TRISB Register is used to access port B, which is to define the pins under port B as input or output. Port B has 8 pins, From RB0 to RB7. Check the pin diagram. Port setting , pic18f4550 pin diagram in the tutorial for programming pic18f4550

For example:

TRISB = 0xF0 ;  // Set all the pins in Port B  to output.

Instead of TRISB = 0xF0 ; you can also write

TRISB = 0;  both are same.

For Setting all the pins in PORTB to input

TRISB = 1;   // Set all the pins in port B to input.

TRISB port settings for accessing all the pins in a PIC18F4550, TRISB = 0;

 

 

 

 

 

 

 

Instead of assigning each pin one by one, you can reduce the coding by defining the entire TRISB to output, only if all the pins are for same purpose.

 

Accessing Individual pins

In real time programming there are certain situations where you would want some pins to work as input and some as output in the same PORT.
At such situation you can set individual pins as either input or output.

                TRISBbits.TRISB0 = 0;       //  Set only pin RB0 to output
                TRISBbits.TRISB1 = 1;       //  Set only pin RB1 to Input

 

 TRISBbits.TRISB , accessing individual pins in port in pic18f4550

 

 

 

 

 

 

 

In the figure above the pins from same PORTB , RB0-RB3 is set to output, and RB4-RB7 is defined as input. Incase of individual pin settings you have to specifically mention the individual pin.  The pin not defined will be left unused.

TRISB was just an example, same method can be used to gain access to other ports also (PORT A, B, C, D, E). Review the port settings for various Ports and pins associated with them in the datasheet.

 

void main(void)


The void main is the main section from where the code actually starts to execute. All the function prototypes that are defined outside the main can be called from inside. As like in delayzz() in the code above where we defined it outside the main code block.

The first stage is to Set the port settings, as shown above in PORTS subtopic

The while(1) defined inside is simple endless loop that keep executing the block inside the braces.

For our blinking project we have defined two led's to blink simultaneously together using LATB Register

                              LATBbits.LATB0 = 1;   // RB-0 to High 
                              LATBbits.LATB1 = 1;   // RB-1 to High
                                 delayzz(); // calling the delay function.
                              LATBbits.LATB0 = 0;    // RB-0 to LOW
                              LATBbits.LATB1 = 0;    // RB-1 to LOW

The code can be easily modified to blink alternatively to emit a dipping effect.
               
                             LATBbits.LATB0 = 1;   // RB-0 to High 
                             LATBbits.LATB1 = 0;   // RB-1 to LOW
                                 delayzz(); // calling the delay function.
                             LATBbits.LATB0 = 0;    // RB-0 to LOW
                             LATBbits.LATB1 = 1;    // RB-1 to High
                                 delayzz(); // calling the delay function.

For more information Visit my post on PIC18F4550

 

Download the Source code or entire project file below

MAIN.C

Mplab IDE - Project .zip

The project files above are compiled with traditional Mplab IDE and C18 compiler.

However now microchip have also introduced a free and very advanced version of IDE which is Mplab X IDE. It is available for both windows and Linux machine. Apart from better looks and easy navigation, One of the most shocking thing which I noticed after coding this pic18f4550 with Mplab X IDE is that, the compiled output (.hex files) is way smaller then that of the regular Mplab IDE hex.

The same source code in this tutorial for blinking an led can be created on Mplab X with X C8 compiler for Linux or windows with no difficulty.

Download the Mplab X IDE version of this same blinking project which is coded a Linux Ubuntu machine.

MPLAB X - Project.zip

In my coming tutorials i will shed some more light on Mplab X ide and XC8 compiler.

NEXT CHAPTER4: Tutorial 2 – Method 2- Blinking led with pic18f4550 – header files

 

PreviousNext
 

Thanks for Reading
Ron



PIC18F4550 Programming tutorial chapter 4 and method 2 for programming

PIC18F4550 Tutorial: Blink LED - 2

$
0
0
PIC18F4550 Programming Tutorial , chapter 4 and method 1 for programming

Hi welcome to my 4th chapter of PIC18F4550 programming. Here we are going to learn another methodology or technique for programming a pic18f microcontroller which would be helpful in future while dealing with complex coding. We are going to define our own header file. We are also going to see the Source Code and will understand the importance, benefits of programming a microcontroller this way on Mplab ide. In Chapter3, we saw the basic programming template for pic18f4550 which is a very common style of programming. In this programming tutorial we are going to breakdown the same source code into some header files to make things simple.

In our previous chapter on pic18f4550 programming we did all the coding in just one file main.c for blinking an LED with pic18f4550 which is a very common method adapted by many beginners. However here we are going to break down the same program and define our own header file. For our example we are going to use the same old example of blinking an LED. This strategy of programming helps in long run for beginners.

Why do we need to define an external header file?

For a simple example of blinking or flashing an led it is pretty much okay to code everything in one file main.c. But in future when you are dealing with complex coding functions and logics, things might get messy if all the coding is done in just one file. Rather sometimes it becomes difficult for even the actual programmer to find their own mistakes, or to makes changes if some coding needs to be modified after a couple of months. Hence dividing things makes it easy for keeping the track of code blocks.

For example, the source code in our previous tutorial started with a general programming style where you have the includes in the beginning (#include<p18f4550.h>), and then followed by lengthy Compiler directives (#pragma config) to set the chip configuration bits.

Instead of writing the lengthy chip config bits in the main.c, you can create a separate header file with headername.h and then write all the compiler directives in the header file headername.h. Finally include it the main.c like the regular #includes in the beginning of the code. A typical user created header include syntax would look like..

                                    #include "headername.h"//User defined header

While executing the main.c all the compiler directives will be parsed by the compiler defined inside #include " headername.h”, In future if you want to change some settings in the chip config bits when without touching the main.c you could directly open the respective header file and make changes.

 

Creating a Header file

     -Create a new file.

     -Type the compiler directives in the new file created.

     -Save the file with a name and extention “.h”. Example: headername.h

     -Check mark “Add File to project” >> Hit save.

If everything goes well the then you would see your created header file included in the Project Explorer under “Header Files” , if its not showing then probably while saving the file you forgot to check mark “Add to Project Files”.

     -Open main.c and add the line #include " headername.h ".

By this way you can create your own header files with codes such as compiler directives, timers or port settings and have them included in the main block. The functions defined inside the header files can be also called from main. This strategy would keep the main.c block clean and would also be easy to makes changes with coding in the future. Instead of messing with entire coding you can specifically reach the section you wish to make changes.

 

Let’s review the schematic and the source code for a example below.

 

Schematic

pic18f4550 schematic diagram to blink led method 2

 

 

 

 

 

 

 

In our previous Tutorial we made two LED's to blink. Here we are going to blink four led's on port B , RB0, RB1, RB2 and RB3 .  Here is a sample schematic. The circuit can be easily built on a breadboard in no time.

 

 

Source Code: Blinking led Method 2 with header Files

The source code below will blink the led the same way as in previous tutorial, but here I have defined two header files compdirectives.h and ledsettings.h. compdirectives.h contains all the Chip configuration settings And ledsettings.h has all the necessary port settings and timers for blinking the led.

SOURCE CODE : main.c

        /*      ****************** main.c ******************      */

#include<p18f4550.h>                                    // Include Header for PIC18F4550
#include "compdirectives.h"                               // User defined header: Chip Config | Complier directivs
#include "ledsettings.h"                                      // Port settings

/*  ***************  TIMER *************** */
       void delayzz(void)
        {              int i, j;
                        for(i=0;i<5000;i++)
                {         for(j=0;j<2;j++)
                      {     /* Well its Just a Timer */     }    }   }

            /* ****************** MAIN ****************** */
void main(void)
   {
                        setpin();                 // PORT B Setting: Set all the pins in port B to Output     
           while(1)  
                   {
                                LED1_on();                    // Glow led 1
                                LED2_off();                    // OFF led 2
                                LED3_on();                    // Glow Led 3
                                LED4_off();                    // OFF led 4
                        delayzz();
                                LED1_off();                     // OFF led 1
                                LED2_on();                    // Glow led 2
                                LED3_off();                    // OFF led 3
                                LED4_on();                    // GLow led 4
                       delayzz();
                 }
     }

/* THE END */

DOWNLOAD main.c or the entire project file at the end of this tutotial.

 

 

SOURCE CODE : ledsettings.h

        /*      ****************** ledsettings.h ******************      */

//LED settings

#define setpin() TRISB = 0;           //Setting all PORTB pins to output pin RB0-7

                  #define LD1 LATBbits.LATB0      // RB0
                  #define LD2 LATBbits.LATB1      // RB1
                  #define LD3 LATBbits.LATB2      // RB2
                  #define LD4 LATBbits.LATB3      // RB3

                       #define LED1_on() LD1 = 1;      // High
                       #define LED2_on() LD2 = 1;      // High
                       #define LED3_on() LD3 = 1;      // High
                       #define LED4_on() LD4 = 1;      // High

                       #define LED1_off() LD1 = 0;      // Low
                       #define LED2_off() LD2 = 0;      // Low
                       #define LED3_off() LD3 = 0;      // Low
                       #define LED4_off() LD4 = 0;      // Low

DOWNLOAD ledsettings.h or the entire project file at the end of this tutotial.

 

SOURCE CODE : Compdirectives.h

        /*      ****************** compdirectives.h ******************      */

#pragma config VREGEN = OFF         // Voltage regulator USB , is Suspended
#pragma config WDT = OFF                // Watchdog timer is suspended
#pragma config PLLDIV = 5                // Internal Oscillator engaged
#pragma config MCLRE = OFF

#pragma config WDTPS = 32768

#pragma config CCP2MX = ON

#pragma config PBADEN = OFF

#pragma config CPUDIV = OSC1_PLL2

#pragma config USBDIV = 2
#pragma config FOSC = INTOSCIO_EC
#pragma config FCMEN = OFF
#pragma config IESO = OFF
#pragma config PWRT = OFF
#pragma config BOR = OFF
#pragma config BORV = 3

#pragma config LPT1OSC = OFF
#pragma config STVREN = ON
#pragma config LVP = OFF
#pragma config ICPRT = OFF
#pragma config XINST = OFF

#pragma config DEBUG = OFF
#pragma config CP0 = OFF, CP1 = OFF, CP2 = OFF, CP3 = OFF
#pragma config CPB = OFF                                                                              // CPB off
#pragma config CPD = OFF
#pragma config WRT0 = OFF, WRT1 = OFF, WRT2 = OFF, WRT3 = OFF
#pragma config WRTC = OFF
#pragma config WRTB = OFF
#pragma config WRTD = OFF
#pragma config EBTR0 = OFF, EBTR1 = OFF, EBTR2 = OFF, EBTR3 = OFF
#pragma config EBTRB = OFF

DOWNLOAD compdirectives.h or the entire project file at the end of this tutotial.

Here for instance if you wish to make changes with the Port settings, and led configuration then instead of searching for specific line of code in main.c , you could directly open the ledsettings.h and make changes without touching main.c much. Rather by this approach your main.c looks neat and clean much more understandable.

As shown in the code above you can also define your own names according to your understanding for some blocks of code. For example: For blinking an led on RB0 the usual way is LATBbits.LATB0=1; For your understanding you can pretty well define it with some name you want, something like #define LED1_on() LATBbits.LATB0=1; , so now from main block you can call the function LED1_on(); which would execute LATBbits.LATB0=1; which is to set the pin RB0 to high and resulting in glowing the led.

 

NOTE: I would strongly suggest to place a comment line with your liberty of understanding next to important sections of code while you are learning programming. It not only helps others who read your code to understand its content but helps you a lot when you see the code after a few weeks yourself.

 

Download the Full Project

main.c

Compdirectives.h

ledsettings.h

Full Mplab Ide project file.zip

 

PreviousNext

Top

Thanks for Reading
Ron



PIC18F4550 programming tutorial chapter 3 , header

Mplab X IDE Tutorial For blinking an LED and Comparison with Mplab IDE

$
0
0
Mplab X IDE Tutorial with XC8 Compiler

 

 

 

 

 

 

Mplab X IDE and XC8 C Compiler


Mplab X IDE is the latest avatar of Mplab IDE which is provided by microchip. It is launched with better features, interfaces and is quiet advanced IDE then the old version of Mplab which were introduced in the past.

In this tutorial we will see some basic and advanced features and benefits while coding with Mplab X over the traditional Mplab IDE. With a Sample source code at the end of this post I will also show a comparison of the output hex files generated with Mplab IDE and Mplab X IDE.

Now a days developer IDE for any programming language are Hi-end, like visual studio or Eclipse which provides better interface and features, but Microchips older versions of IDE never had these features of autocomplete and suggestions while writing the codes. Hence this new avatar as MPLAB X settles these problems and the way it looks.

The Mplab X IDE uses its platform as Netbeans from oracle, Hence while coding with it might make you feel as if you are working on Netbeans IDE, because lots of Mplab X features are taken from Netbeans.

Features of Mplab X IDE Over Mplab IDE


MPLAB X IDE and XC8 Compiler tutorial

Before installing you might want to update java for the installation to run smooth.  Since its java based IDE now, so Mplab X is not limited to windows.

As a long awaited feature, Mplab X IDE is now available on Linux and Mac OS versions also, which can be easily downloaded from microchip’s website for free. So the programmer does not have to be confined to a windows computer only, as it was the case with old versions of Mplab IDE. Apart from better looks and interface, one of the most amazing thing which can be noticed is the size of output after compilation (the hex file).

After coding and compiling the sample codes from my previoustutorials, I found that the compiled output hex files by XC8 were way smaller in size than that of the output from old Mplab IDE and C18 compiler. Hence compiling with Mplab X can save a lot of space.

In traditional Mplab IDE you had to be selective about the type of the compiler, for the family of microcontroller you are coding. For Example: To code a PIC18F family microcontroller you needed C18 Compiler and for PIC16F microcontroller it was required to install a different Compiler Toolsuite. Hence now microchip integrated most of its different compiler toolsuite into one XC8 compiler for Mplab x which support all 8, 16 and 32 bit microcontroller family. Hence all you need is just to download the Mplab X and XC8 Compiler.

The older version of Mplab projects can still be imported into the latest Mplab X without any difficulty with project wizard.

Note: I will try to attach an Mplab X version of project file for download with each of my old tutorials which were done on Mplab IDE. Lot of programmer who have the habit of programming with old versions of IDE sometimes find it little difficult to work with latest Mplab X versions, But it is really not so hard, once you get to know it more.  In this tutorial we are going to use Mplab X IDE and XC8 Compiler to code our microcontroller.

 


PIC18F4550 Programming with MPLAB X IDE


Programming a PIC18f4550 with Mplab X IDE and XC8 Compiler , project

Before we start coding on PIC18F4550 with mplab X , we need to create a new project just like Mplab IDE.

Creating a project is easy in Mplab X, just open the IDE and proceed to project wizard from file menu. Select the microcontroller family or directly type the name of the microcontroller in the device name.

Then select the hardware tool from the list, if you have any programmer like pickit2 connected then select pickit2 or go with the defaults and click next.

Select XC8 C compiler from the list of compiler which I assume you must have installed after installing Mplab X IDE and finally type a project name – and you are ready for coding.

It will open a blank project, Now you can create a new source file from the project explorer by right clicking on Source File> New> C main File.

Select your desired Name, the extension must be C and then finally click finish. It will open a default source code template; you are ready for coding with Mplab X.

Start mplab X IDE from LinuxMplab x IDE C8 - Create new Project for PIC18F4550

Select the PIC18F4550 Microcontroller

Mplab X xc8 Simulator select Tool

XC8 Compiler select from the list of available Compilers for mplab x IDE

Project name for PIC18F4550 Blink led with mplabX ide and XC8 Compiler

Blinking LED with PIC18F4550 on Mplab X IDE and XC8 Compiler for beginners

 

Blinking an LED with Mplab X IDE and PIC18F4550


For testing the Mplab X IDE we are going to use the same source code from one of my previous tutorial where we coded a pic18f4550 with Mplab ide for blinking an led. We are just going to replicate our previous tutorial with a different IDE.

  -Create a New project and select device as "PIC18F4550" from drop down menu, and proceed withcreating a new project with XC8 Compiler.

  -Create a New Source C file. And clean it up.

  -Copy the source code from previous post– Blinking an LED using pic18f4550.

  -Run > Build project.

If everything goes right then the output windows below will display a Build Successful message. The output window at the bottom will also show the location of .hex files which were just created. If you have a pickit2 attached then you directly burn the firmware into the microcontroller or  Navigate to the .hex file location which is usually,

            MplabProjectFoler/Projectname.X/Dist/Default/Production Folder

Search for the file with .hex in the production folder. If you have a pickit already attached then you can program directly or you can use other programmers to burn the output .hex file in to pic18f4550 microcontroller. The source code above should blink RB-0 and RB-1 alternatively with a dealy inbetween the two LED. The schematics are same as shown in my previous post.

 


Comparison of HEX files compiled with

MPLAB X IDE and MPLAB IDE v8


Now as I have mentioned before that you will notice that the size of the .hex file be much more shorter when you compile with Mplab X then that of Mplab IDE. Hence here we are going to do a small practical Observation.

Project for blinking led with same source code, I first compiled it with traditional MPLAB IDE and the .hex file came out something like this for just blinking two led.

.HEX file compiled With Mplab IDE

:020000040000FA
:06000000A8EF00F0120061
:020006000000F8
:08000800060EF66E000EF76E05
:10001000000EF86E00010900F550656F0900F550FB
:10002000666F03E1656701D03DD00900F550606F50
:100030000900F550616F0900F550626F0900090071
:10004000F550E96E0900F550EA6E09000900090053
:10005000F550636F0900F550646F09000900F6CF91
:1000600067F0F7CF68F0F8CF69F060C0F6FF61C0C5
:10007000F7FF62C0F8FF0001635302E1645307E039
:100080000900F550EE6E6307F8E26407F9D767C020
:10009000F6FF68C0F7FF69C0F8FF00016507000EB2
:0600A000665BBFD71200F1
:0A00A600D9CFE6FFE1CFD9FF040E29
:1000B000E126DE6ADD6ADECF02F0DDCF03F0D89004
:1000C000035004E6880E025C130E03581DE2020E74
:1000D000DB6A030EDB6A020EDBCF02F0030EDBCF1E
:1000E00003F0D890035004E6020E025C000E0358A1
:1000F00006E2020EDB2A030E01E3DB2AECD7DF2A3D
:10010000010E01E3DB2AD7D7040EE15C02E2E16ACB
:10011000E552E16EE552E7CFD9FF1200F00E936E83
:100120008A808A82C0DF8A908A92BDDFF9D7120066
:10013000000EF36E00EE00F0080E01D81200EA6027
:1001400002D0EE6AFCD7F350E9601200EE6AFCD7E9
:1001500013EE00F023EE00F0F86A019C04EC00F0CE
:0C016000B6EC00F08EEC00F0FBD71200B3
:02016C0012007F
:020000040030CA
:0100000024DB

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Now here is the .Hex file compiled with Mplab X ide with same source code for blinking two LED.

HEX file compiled With Mplab X IDE

:04000000AFEF3FF02F
:107F5E000001B2EF3FF0F00E936E00D08A808A825D
:107F6E008A848A86C5EC3FF08A908A928A948A9691
:107F7E00C5EC3FF0F3D7F2D700EF00F0000E026E23
:107F8E00000E016E0250800A6D0F880ED8B4015C8F
:107F9E00D8A001D001D002D02BD02AD0000E046E72
:107FAE00000E036E0450800A800F020ED8B4035CDC
:107FBE00D8A001D001D002D00ED00DD0034A042A91
:107FCE000450800A800F020ED8B4035CD8A001D0F2
:107FDE0001D0F4D700D0014A022A0250800A6D0F58
:107FEE00880ED8B4015CD8A001D001D0D7D700D06C
:027FFE0012006F
:020000040020DA
:08000000FFFFFFFFFFFFFFFF00
:020000040030CA
:0E0000002408191EFF8385FF0FC00FE00F407C
:00000001FF

 

 

 

 

 

 

 

 

 

 

I hope you noticed the difference between the both .hex files. Hence Mplab X can really save a lot of space when you are dealing with really lengthy and complex codes where programmers have to take the size of the program into serious consideration.

 

Thanks for reading
Rakesh Mondal


Related Topics

PIC18F4550 Programming using hardware C
Mplab IDE and C18 Compiler
PIC18F4550 Programming- Blink 1 (Mplab IDE)
PIC18F4550 Programming Blinking LED - 2 (Mplab IDE and X IDE)
IR Sensor Circuit Interface with PIC18F4550
 


 

Infrared IR Sensor Interface with PIC18F4550 Microcontroller

$
0
0
IR sensor circuit Interface with PIC18F4550 microcontroller project - Digital input

IR Sensor Interface with PIC18F4550


In my previous project we have made a simple IR sensor Circuit. In this project, as promised before – we are going to demonstrate a PIC18F4550 microcontroller interface to IR sensor circuit. We are just going to glow few on the pic18f4550 as an example, however you can do some more intelligent operations by adding some more logics to the microcontroller coding. Interfacing infrared Proximity sensors with Microcontroller is quiet easy.

This project is not only about interfacing an infrared IR sensor module but also we are going to learn - How to take digital input from a PIC18F4550 Microcontroller (Reading the Input with a Microcontroller). It means that the source code here will work same for taking input from a simple switch. You can replace the IR sensor with some simple PUSH Switch or some other types of proximity sensors . In case of push button you would need to pull down the pin to ground with 1 k resistance, however for IR sensor you won’t need to pull down the input pin with resistor.

Infrared IR Sensor Module

Let’s take a look at the IR Infrared Sensor Circuit Project module that we made in our previous project which is an inexpensive ( Low Cost ) sensor circuit module. You can find the schematic and PCB design in my previous post. There are three pins in the Schematic - Two pins for providing the input voltage and GND to the IR Sensor Module, and the third pin from the IR module is the IR control pin. This Control Pin from the IR sensor Module will be interfaced to the PIC18F4550 microcontroller for sensor input.

IR Sensor Module

Infrared IR sensor Object detection circuit Module design and pin settings

Concept

The output from the IR sensor circuit will be connected to pins of a PIC18f4550 microcontroller and the microcontroller will regard it as digital input to read either 1 or 0.  According to the output from the IR sensor module, the PIC18F4550 will respond by glowing led. Since we just want to read some voltage in the microcontroller as input (either High or low) hence we are going to configure input pins as digital to read just 1 or 0 from the sensor.

IR infrared Sensor circuit connected a with PIC18F4550 microcontroller project on breadboardProject: PIC18F4550 Microcontroller programming with IR sensor Module

 

PIC18F4550 Interface with IR sensor Circuit

The output from the IR sensor circuit is connected to RA0 of the pic18f4550 which is configured as input with TRISB registers, and the output will be displayed on LED connected across RD7, RD6,RD5 (PORTD) and RB0 and RB1 (PORTB) which are configured as output pins. Follow the schematic below.

Schematic (IR sensor and PIC18F4550 microcontroller)

Schematic for Infrared IR sensor circuit interfacing with a PIC18F4550 Microcontroller circuit

In this project we don’t need to perform any Analog to Digital Conversion(ADC), hence we are going to turn the ADC off (ADCON0bits.ADON = 0) and configure all the PINS to Digital.  At the default 1 MHZ oscillator frequency the output sometimes gives unstable result, hence tuning the microcontroller to 8MHZ solved the problem, Please note that pic18f4550 works by default on 1 MHZ and you can change the OSCCON bits settings to tune the oscillator frequency according to your requirement.

Search in pic18f4550 datasheet for OSCCON register bits and you will find a nice description and bits settings table for available oscillator frequency and settings to configure the microcontroller oscillator frequency. Here I have configured the internal oscillator to 8MHZ to avoid switch debouncing. However it works well with 1MHZ settings as well. As a better plan the comparator is also turned off to avoid any conflict.

                          All the resistors in the above Schematic is 1k resistance. If possible, it is also recommended to add a IC 7805 liner Voltage regulator IC as a source of +5V to avoid any voltage fluctuation which could possibly damage the microcontroller. Make sure the input voltage to pic18f4550 must never exceed +5v. Please do read the excellent pic18f4550 datasheet provided by microchip.

IR sensor circuit programmed with PIC18F4550 microcontroller as Digital Input pin

Source Code:

MPLAB IDE and C18 Compiler is used for compiling the source code, however MPLAB X IDE and XC8 Compiler can be also used with no difficulty. Download the entire project at the end of the source code below with compiled firmware. 

SOURCE CODE :infraredinput.c

/*
 * File:   infraredinput.c
* Author: ron
 * December 10, 2012, 1:21 PM
 */
#include <p18f4550.h>          // Include Header for PIC18F4550

#define switch1  PORTAbits.RA0  // Switch on RA0

#define led1    LATDbits.LATD7     // led1
#define led2    LATDbits.LATD6    // led2

#define led3    LATBbits.LATB0   // led3
#define led4    LATBbits.LATB1    // led4
#define led5    LATBbits.LATB2    // led5

void main (void)

{

            /* If you want your microcontroller to work at  1MHZ then comment the three lines below */

OSCCONbits.IRCF0 = 1 ;               // set internal clock to 8 MHz
OSCCONbits.IRCF1 = 1;                //  For Avoiding switch debouncing problem      
OSCCONbits.IRCF2= 1;                 //

/* Input output settings*/

       TRISAbits.TRISA0 = 1;                  //   RA0 Input for taking input from IR sensor

       TRISDbits.TRISD7 = 0;                  // Port D pins output
       TRISDbits.TRISD6 = 0;

       TRISBbits.TRISB0 = 0;                  // Port B pins Output
       TRISBbits.TRISB1 = 0;
       TRISBbits.TRISB2 = 0;

       CMCON = 0x07;           // Disable Comparator

       ADCON1bits.PCFG0 = 1;          // These 4 settings below determines the analog or digital input
       ADCON1bits.PCFG1 = 1;          // In our case we are making all the pins digital
       ADCON1bits.PCFG2 = 1;         // by setting them as 1111
       ADCON1bits.PCFG3 = 1;         // Check with the datasheet for a nice desc of these bits and config.

       ADCON0bits.ADON = 0;  //  Disabled ADC

while(1)
     {   //Forever Loop
            if(switch1 == 1)    //   On reading IR sensor value ON
                    {    //Turn led ON
                                led1 = 1;
                                 led2 = 1;
                              led3 = 1;
                              led4 = 1;
                                 led5 = 1;              }
       else if ( switch1 == 0) // On reading IR Sensor Value OFF
                      {   //Turn led off
                              led1 = 0;
                            led2 = 0;
                            led3 = 0;
                            led4 = 0;
                            led5 = 0;              }
                                     else {    }

    }   //End While loop --forever
}

/* THE END */

The coding above is pretty much self-explanatory, and comment lines must be also helpful for better understanding.

Now you can use this project to develop your own application the way you want. It's easy to interface this project with a L293D Motor Driver to drive DC motors as an "IR sensor Motor Driver" or a simple IR infrared robot, or you could add one more IR module on some other AN pin as switch2, with which you can make it as "IR Line follower robot" very easily.In my next tutorial I have also shown how to interface multiple IR sensors with Arduino Uno board and have the status of the sensor displayed on LCD.

Use the way your creativity drives you.

Download the Full Project

infraredinput.c

Firmware

Full Mplab IDE project file.zip (IR Digital input)

Mplab X IDE project (Digital Input)

 

Thanks for Reading
Rakesh Mondal
RON

PreviousNext

Top

IR sensor circuit Programmed with PIC18F4550 Microcontroller, programming pic184550 for digital input



 

USB Stepper Motor Driver

$
0
0
USB Stepper Motor Driver, PIC18F4550 USB Stepper Motor Controller

 

 

 

 

USB Stepper Motor Driver


In this project we are going to drive a unipolar Steppermotor(5 wire) using USB interface from a PC Computer. This project is an application of the USB Interface Board PIC18F4550 which was published here in the past. You can run other stepper motors too. It is simple and easy to make, we are going to use PIC18F4550 microcontroller which has an in built USB (USB 2.0) functionality which allows it to connect with any computer with a USB port and Windows OS. We will try to provide as much as details we can for achieving this project.

USB Stepper Motor driverUSB Stepper Motor driver

 

 

 

 

 

 

 

OLD METHOD: The legacy (OLD) method was to use a parallel port (DB 9), which were far more easy with simple port control commands, which were good enough to glow few led directly connected to COMM pins of a parallel port, and with a simple loop written in VB it was easy to generate a pulse of blinking led for a stepper motor.

USB: However laptops and portable computers don’t come with those big D9 (parallel or printer) port anymore, as the USB ports - due to its excellent characteristics and small size has taken its replacement for almost for any external device. USB interface for this project is going to be little complex then the old parallel port method.

The microcontroller which will serve as the communication channel between the Computer and Stepper motor, the PIC18F4550 microcontroller, can work in two USB speed 12Mbps(full speed) and 1.2Mbps(low speed).

For our project we will run this microcontroller board in Full speed (12Mpbs). The project can be also achieved with a PIC18F2550 with little modification in the firmware, but since 18F4550 has more number of pins on a standard Dual Inline package (40 pins, 20 pins on each side), so we will go with that. PIC18F4550 is far more cheap and inexpensive then an Arduino board. In fact the stepper motor here costs more than the entire board and components used.

usb stepper motor

 

 

 

 

 

 

 

Stepper Motor

The stepper motor used here is a 5 wire Stepper motor (M35SP-8) which is going to be operated by an application written in C#, (visual studio) which will communicate with the microcontroller board via USB, and microcontroller will drive the Motor connected with it according to the output directed by the software written in C#. The entire project and its necessary project files with schematics can be found at the end of this page.

Unipolar Stepper motor - 5 wire

The M35SP-8 Stepper Motor has a step angle of 7.5 degree, with one Common wire and 4 control wires connected to each coils. Hence we need only 4 control links for generating the pulse which will drive this stepper motor. For information on the specification of MS35SP-8 refer the respective datasheet.

 

Stepper Motor Wiring

The Figure below shows the labeling of the Stepper motor used for this project. If you wish to use any other stepper motor then you have to follow wiring labels of that respective stepper motor.

stepper motor wiring5 wire Stepper Motor Driver Color code wiring

Running other Stepper motors

The USB interface board we are using here has 6 control pins, it means you can control 6 LEDs (example) with this board. Out of which, only 4 pins are required to control our M35SP-8 Stepper motor, remaining 2 will be unused.

However you can run more kinds of stepper motor too. Since we have 6 control lines available hence the project can be easily modified to run other stepper motors too. Any stepper motor has one common ground wire and remaining are control wires, So technically with this USB interface board you can run a 5 wire, 6 wire and 7 wire stepper motor easily (6 control and one Common power).  

 

USB Interface Board Schematic


First start with the USB interface board, which will require a firmware to be loaded in the microcontroller and later, a windows driver, after the board is ready. I strongly recommend making this board on PCB.

You can find a detailed tutorial and specifications for making this board alone in my previousUSB Interface post. The firmware used here is the same firmware as in PIC18F4550 board with no modification. The components required are pretty much clear in the schematic or you are free to explore USB Interface Board post for detailed component list.

-Firmware Download

After making this board, connect it with computer USB port and it would ask you for driver.

-WIN XP driver
-WIN 7 Driver

The only thing here different is the C# application, which is written for running the stepper motor.

 

Schematic:

USB Stepper Motor Driver schematic

Connect two led across RD4 and RD5, which will display the status of the USB Board. IF the Communication between the computer and USB Board is successful then both the LED’s would blink alternatively.

The pins RD0-RD3 of the microcontroller is interfaced with 4 coils of the stepper motor, and the “Common wire” is interfaced the external 9V motor supply.  

USB Interface Board PIC18F4550 Microcontroller

 

PIC18F4550 USB Stepper Motor Circuit

USB stepper Motor Driver Circuitry

The output voltage across the RD pins of the microcontroller would be enough to glow few LED, but it is not enough to run our MS35SP-8 stepper motor, hence we are going to use a Darlington pair of transistors for high voltage switching.

 

uln2003-Interface

For such purpose we will use ULN2003 IC, UlN2003 is a monolithic high voltage Darlington array IC, which contains an array of transistors (bipolar transistors) which will do the switching for us, with excitation of low voltage input.  

On the USB interface board we cannot increase the voltage more than 5v, or it will kill the microcontroller instantly (Refer the PIC18F4550 datasheet) and the output pulses generated will be low voltage hence ULN2003 is used, which would drive our load (stepper motor). We will feed the ULN2003 with 9V power supply which will run the stepper motor. Refer the ULN2003 datasheet for its technical specifications. A typical L293D motor Driver can be also used for such purpose, but that will make circuitry little bit more complex, hence uln2003 is good enough.

After making the USB interface board to work, it’s a good idea to test with 4 leds, after that interface it with uln2003 as showed in the schematic above, make sure you check all the connections before testing it out. Be careful because we are introducing 9V to the ULN2003, the microcontroller directly cannot bear 9v as mentioned before.

Note: Do not forget to connect the Ground pin (GND) of the Microcontroller board to the ULN2003 GND pin (pin8)

 

Application C#


After the USB board is successfully installed on the PC with the drivers provided, the led on RD4 and RD5 would start to blink alternatively. Now start the application. The Application here is written on C# forms. Open the project file and everything will be quiet easy to code and modify, or to add more steps for stepper motor.

 

Application for controlling and driving USB Stepper Motor

CS application

You can also alter the time delay in between each step by entering the ms value on the software application for this driver.

Stepper Motor Stepping Sequence

As of now only three modes has been added for this stepper motor.

Stepper Motor Modes Steppings

 

 

 

The truth table below shows how pins are set and phases are energized according to the modes.

 

Single Step Wave mode: C1, C2, C3, C4 are coils connected to RD0, RD1, RD2 and RD3 pins of USB pic18f4550. In this mode only single phase is energized (Single phase excitation) for the running the motor. Single stepping (wave) mode gets completed in 4 cycles, A, B, C and D which then repeats over again from the beginning (loop) at the end. At the end of 4 cycles the Stepper motor shaft completes one revolution.

 

Stepper-Motor-Steppings-Wave-single step

 

Full Step Sequence mode: This mode drives with Dual phase excitation, which means that two phases are energized at a time and hence results in more torque. This mode also has 4 cycles, A, B, C, and D. However the motor in this mode runs with little more toques then that of wave mode.  At the end of last cycle the motor loops over the same.

 

Half wave stepper motor stepping

 

Half Step sequence mode: This mode is the combination of both Single phase excitation and dual phase excitation, in this both single and dual phases are energized alternatively for running the Stepper Motor. This mode of operation has 8 cycles or steps for completing one rotation of the motor shaft. This mode provides pretty good resolution but the speed is going to be slow.

 

Half wave Stepper motor steppings

You can toggle the modes the way you want in the application running on the desktop for the speed and step mode you want.

If you want to run a 6 wire stepper motor then you can easily modify the code on the C# application, by adding some more port control commands and sequence of loop. The source code is pretty much self-explanatory and can be very easily modified.

USB Stepper Motor project

Testing Stepping Pulse with LED

Before connecting and ULN2003 to the circuit board, you can test if the Stepper motor Stepping pulses are generating on the pins the way it is supposed to be, by connecting 4  led across the RD0 to RD3. Watch this video below for a small demonstration.

Don’t connect the LED across the output pins of ULN2003 or the Led’s will get damaged, Connect them directly to the RD pins with 1 k resistance each. Start the software and hit Start motor button.

LED connected to stepper motor for testing usb LED connected to stepper motor for final test

The label on the C# application will update according to the Stepping pulse sent to the PIC18F4550, If everything is working fine and the led’s are blinking in the way shown in the stepping truth table above, then  connect the uln2003 and stepper motor to the board.

Stepper Motor Interfaced to ULN2003

 

 

PROJECT FILES

-C# Stepper motor Driver Software application
-Firmware for microcontroller

-Driver download – XP
-Vista and Win 7

-Schematics

 

Thanks for reading
Rakesh Mondal.

USB Stepper Motor Controller Driver Project


Related Topics

PIC18F4550 USB Interface Board
Stepper Motor Drivers
Stepper Motor Driver using PIC18F4550
Stepper Motor Schematics
Stepper Motor Controller using PIC18F2550
USB DC MOTOR Controller
L293D Motor Driver
PIC18F4550 Microcontroller


 


Stepper Motor Driver using PIC18F4550 Microcontroller

$
0
0
Stepper Motor Driver tutorial using PIC18F4550 Microcontroller

 

 

 

 

Stepper Motor Tutorial


In this tutorial we are going to drive a Single unipolar stepper motor using PIC18F4550 Microcontroller in various different stepping modes. The source code and Project files are free to download at the end of this page.

Stepper motor due its excellent features is very famous in between hobbyist for various robotic applications. Running DC, Stepper motor and servo is the most basic requirement in any robotic application which moves. Stepper motor’s ability to run in various modes with various speed and torque gives it a more degree of advantage over the simple DC motor for various projects, especially in robotics based projects.

USB Stepper Motor driverSo in this basic stepper motor tutorial we will learn to drive a simple 5 wire unipolar stepper motor using a 40 pin PIC18F4550 microcontroller.

For a little more sophisticated Stepper motor Driver you can also follow my USB Stepper Motor Driver project which is quiet similar to current project , however this driver tutorial does not involve any interaction to any computer system directly except for writing the codes.

 

 

-5 wire Unipolar Stepper Motor
-Bread board
-PIC18F4550 Microcontroller
-IC 7805
-ULN2003 (For better Results)

Unipolar Stepper motor - 5 wirePIC18F4550 Microcontroller Interface with Stepper Motor

Stepper Motor Schematic for PIC18F

 

 

 

 

 

 

The stepper Motor can be also connected directly without ULN2003, but during the testing the results were not satisfactory hence a ULN2003 was added.

Caution!: 9V power supply is given to Stepper Motor which is not same as the voltage for the PIC18F4550 power supply (5V). Do not connect both the power supply together as the PIC18F4550 cannot bear more than 5V, both the supply must not be shot together or the microcontroller will be damaged.

If you have a single source of power supply for both the Stepper motor supply and Microcontroller, then add a MCP102 or an IC 7805 Voltage regulator (5v) before the VSS terminal of the Microcontroller, which would keep the input voltage to microcontroller at 5V.

is

 

 

Stepper Motor Driver with IC 7805 voltage regulator

 

 

 

 

 

 

 

 

 

Stepper Motor Wire Color Code


It is important to understand the color code of the stepper motor for identifying the Coils and Common wire before it can be connected across the Microcontroller pins. The diagram below shows which color cables are connected across which pin of the microcontroller.

Motor wiring color codeStepper Motor Color codes

 

 

 

 

 

 

 

Compiler IDE and Source code


The source code is compiled with MPLAB X IDE and X C8 Compiler which can be loaded into the microcontroller using pickit2 or JDM Programmer. It can be also compiled with Mplab and C18 compiler without much effort. For convenience I have added both versions of the source code at the end of this post with the compiled HEX file. For our Stepper Motor Driver we are not going to use any external Oscillator with the microcontroller.

There are two source code posted here, the source code 1 demonstrate the basic and simple Single Stepping mode of a stepper motor. The second source code is little more complex and has three other stepping modes (Single, FULL and HALF) cycling with delay of 5 seconds each.

-Source Code - 1

-Source Code - 2


 

stepper motor wiringThe first code demonstrates Single stepping mode for driving our 5 wire unipolar stepper Motor. Where the Stepper Motor coils are connected to PIC18F4550 pins, RD4, RD5, RD6 and RD7.

You would also require a header file which contains the various compiler directives, which is common for both the source codes 1 and source code 2.The delay has been set to 50000 microsecond or 50 milliseconds.

If in case if you want to use __delay_us( ); instead of __delay_ms( ); for adding delays then you can use some time converters or my favorite online scientific calculator ( eeweb calculator ) for ms to us conversion.

        /*      ****************** Steppermotor.c ******************      */

#include <p18f4550.h>
#include "headerzz.h";
#define _XTAL_FREQ 2000000

     void main(void)
{
                  TRISDbits.TRISD0=0;          // Configuring Port D to output
                  TRISDbits.TRISD1=0;          // From pins RD4 to RD7
                  TRISDbits.TRISD2=0;
                  TRISDbits.TRISD3=0;

           while(1)
              {
                      LATDbits.LATD0=1;        // ON
                      LATDbits.LATD1=0;
                      LATDbits.LATD2=0;
                      LATDbits.LATD3=0;
                      __delay_ms(50);

                      LATDbits.LATD0=0;
                      LATDbits.LATD1=1;        // ON
                      LATDbits.LATD2=0;
                      LATDbits.LATD3=0;

                       __delay_ms(50);
                      LATDbits.LATD0=0;
                      LATDbits.LATD1=0;
                      LATDbits.LATD2=1;       //On
                      LATDbits.LATD3=0;

                      __delay_ms(50);
                      LATDbits.LATD0=0;
                      LATDbits.LATD1=0;
                      LATDbits.LATD2=0;
                      LATDbits.LATD3=1;       // On
                      __delay_ms(50);

                     }
      }

/* THE END */

Donwnload Steppemotor.c, Header.c and output1.hex

You can download the entire Mplab X –XC8 project at the end of this post.

Stepper-Motor-Steppings-Wave-single step

In the above sample source code excites each coil with delay of few milliseconds and loops over again from the beginning endlessly for the next cycle.

In this mode only single phase is energized at a time, and for completing one complete revolution of the motor shaft it take 4 cycles, and only one coil is energized at a time and during next cycle previous coil goes low 0 and next one goes high 1.

 

 

Stepper Motor Scource code tutorial1

Stepper Motor Using PIC18F4550This source code demonstrates three modes of stepper motor which are Single stepping mode, half wave stepping mode and Full Wave stepping mode. Each mode executes for 5 to 6 seconds and then executes next mode. The schematic for this Source code is little different.

The Stepper Motor coils are connected across PIC18F4550 pins RD4, RD5, RD6 and RD7. Also 4 LEDS are connected across RB0, RB1, and RB2 acting as indicator for the mode in which the stepper motor is running.  Follow Schematic 2 for Source code 2.

Stepper motor stepping modes

RB0 - Single Wave Stepping
RB1- Half Stepping mode
RB2- Full Stepping mode

        /*      ****************** Steppermotor2.c ******************      */
#include <p18f4550.h>
#include "headerzz.h";
#define _XTAL_FREQ 2000000 //20 for the Delays
#define port_d_op TRISD = 0;
#define port_b_op TRISB = 0;

         void singlestepping (void)
      {
          int a;
          PORTB = 0b00000111;      __delay_ms(60);
          PORTB = 0b00000001;

            for(a=0;a<10;a++)
             {
               PORTD = 0b10000000;      __delay_ms(60);
               PORTD = 0b01000000;      __delay_ms(60);
               PORTD = 0b00100000;      __delay_ms(60);
               PORTD = 0b00010000;      __delay_ms(60);
             }
          }

          void halfstepping (void)
          {
               int b;
               PORTB = 0b00000111;      __delay_ms(60);
               PORTB = 0b00000010;

               for(b=0;b<10;b++)
               {
               PORTD = 0b10000000;      __delay_ms(60);
               PORTD = 0b11000000;      __delay_ms(60);
               PORTD = 0b01000000;      __delay_ms(60);
               PORTD = 0b01100000;      __delay_ms(60);
               PORTD = 0b00100000;      __delay_ms(60);
               PORTD = 0b00110000;      __delay_ms(60);
               PORTD = 0b00010000;      __delay_ms(60);
               PORTD = 0b10010000;      __delay_ms(60);
               }
          }

              void fullstepping (void)
          {
                 int c;
                 PORTB = 0b00000111;           __delay_ms(60);
                 PORTB = 0b00000100;

                    for(c=0;c<10;c++)
                    {
                         PORTD = 0b11000000;      __delay_ms(60);
                         PORTD = 0b01100000;      __delay_ms(60);
                         PORTD = 0b00110000;      __delay_ms(60);
                         PORTD = 0b10010000;      __delay_ms(60);
                    }
               }

                         void main (void)
                    {
                              port_d_op;           // Make Pord D output
                              port_b_op;           // Make Port B output

                    while(1)      // Steppings
                {

                         singlestepping();
                         halfstepping();
                         fullstepping();
                }
          }

/* THE END */

Donwnload Steppemotor.c, Header.h and output1.hex

You can download the entire Mplab X –XC8 project at the end of this post.

 

Full stepping mode and Half stepping Logic diagram

Truth table representation of the stepper motor stepping sequence.

FULL wave stepper motor steppingHalf wave Stepper motor steppings

 

Testing Stepper Motor Stepping Pulse with LED

After Coding and burning the firmware, you can test the stepper Motor stepping pulse generated by the microcontroller, by connecting few LED across the PIC18F4550 pins directly. In the video below, we are first going connect few LED's instead of Stepper Motor, and test whether the microcontroller is generating the stepping pulse the way it is supposed to generate. Be sure not to connect the LED's to the uln2003 pin, connect it across the Microcontroller Pins directly or the high voltage (9v) across the ULN2003 would damage the LED for sure. The LED's should blink and pulse the according to the source code and truth table above.

If the output stepping pulses are generating on the LED's the way is it coded, then you can proceed forward and connect the ULN2003 and Stepper motor according to the schematic.

Stepper Motor Step sequence detailsStepper Motor Step sequence PIC18F4550

 

 

 

 

 

 

Project Files

Stepper Motor 1

Stepper Motor 2

Thanks for Reading
Ron


Related Topics

Stepper Motor Drivers
USB Stepper Motor Driver
USB DC Motor Driver
Stepper Motor Schematics
Stepper Motor Driver Using PIC18F2550
PIC18F4550 Microcontroller


 

USB Interface Board Tutorial Using PIC18F4550

$
0
0
USB Interface Board using pic18f4550 microcontroller tutorial
 
 

USB Interface Development Board Tutorial -1

STAGE/PART-1
 MAKING OF THE MAIN CIRCUIT BOARD


 CONTROL YOUR DEVICES FROM COMPUTER USING USB PORT – pic18f4550 + MPLAB IDE

INTRODUCTION ( USB PROJECT) : STEP 1

This project demonstrates a computer control interface using a USB Board. (USB INTERFACE PROJECT). This tutorial will show you a simple way to control some device like led, motors and other devices with computer through a USB Board. The traditional way to control devices from a computer was to use a parallel printer port which is much more easy to implement than that of a USB PROJECT, but the only limitation with parallel printer port is that the latest computer does not comes with parallel printer port. So you can use this project as an alternative to a parallel port interface. pic18f4550 usb interface project is Human Interface Device (HID).

If you are thinking that Buying a USB to Parallel port converter would work then you are wrong ! , hence this one is an very good alternative .

For this USB Interface Board we are going to use a Microcontroller “PIC18F4550

This tutorial is not so difficult for a experienced person however I am also posting a step by step procedure for beginners . If you are an experienced person with microcontroller then all you need to do is to make the USB board Circuit and then burn the firmware into the microcontroller , with a microcontroller programmer and then install the drivers on your system , and finally launch the application after connecting the main board to the computer with a USB PORT.

-Experienced personal can go to end of Interface Board link and can download everything at the end of that page. Beginners can follow this page and continue on for full description.

- This project allows you to control some device with your computer on clicks of few buttons on a small application written in C# which communicates through the pic18f4550 microcontroller. But creating this board can be difficult for beginners and easy for experienced persons.

SO beginners please follow this entire tutorial step by step.

 

Please watch the video below so see the PIC18F4550 Microcontroller in action.

 

 

APPLICATION OF USB DEMO BOARD (USB ROBOT)

 

In traditional parallel printer port interface project all you have to do is to connect few led’s across you parallel port (printer port) and code an application in Visual Basic or C# and you are done. But when it comes to USB port control, its quiet complex way than parallel printer port control.

This Tutorial will show you in details for constructing this USB pic18f4550 circuit and running it from a C# application. Please read and follow all the posts.

 

PIC18F4550 USB Interface Development Board

pic18f4550 schematic , usb interface demo board

PIC18F4550 Interface Board

I found a kind of tutorial on microchip.com to control one led with PIC18F4550, and from there I started to do experiments on source codes and then I came up with controlling 8 led’s. For now I am showing only 6 LED controls

This USB Interface board pic18f4550 is programmed to control 6 led’s and it can be manipulated easily to control 8 led’s. In spite of led’s you can interface it to some other electronics components to control, like DC motor or stepper motor or can make your own robotics application as I did. A small software coded in C# can control the glowing of led’s with clicks of mouse or by pressing some keys.

Let's First Take care care of circuit board then we will come back to MPLAB IDE to program it.

Let’s start with making the circuit board first, then we will discuss about other coming steps for making this demo interface development board like firmware, Driver, bootloading, writing our own code using MPLAB IDE, etc. Please read all my steps carefully and follow them properly, in first reading it may not be so much clear, so I suggest giving a second reading. As you go further, it will start to get clear slowly. I am trying to make it as easy as possible for better understanding.

-For my project I bought this PIC18f4550 microcontroller for Rs. 375 (Indian currency) that is around 6.5 $. It is available in any electronics shop.

The schematic provided in this tutorial is a snapshot picture from EAGLE Layout designer.

PIC18f4550 Microcontroller on a 40 pin base pic18f4550 interface board overviewpic18f4550 microcontroller chip with a 40 pin base ,  www.rakeshmondal.info
 

 

 

So get all the components in the list i have provided below and heat up your soldering iron and lets begin. Be careful while working with soldering iron.

 

pic18f4550 USB Board SCHEMATIC

pic18f4550 schematic , circuit diagram for usb interface board Schematic with all the components required

 

 

 

 

 

 

 

SCHEMATIC

TIP: Save the schematic and pin diagram for this USB demo interface Board. Refer the pin diagram time to time while soldering to avoid confusion. It is better to do labeling in the PCB to avoid confusion while you are soldering.

Components Required for USB Interface Board

LabelValueQuantity
C122p1
C222p1
C30.47u1
C40.01u1
C510u1
C60.01u1
Q120MHZ1
MPPIC18F45501
R1,2,3,41K1 Each
R5,610K1
Push switch2 Pins2
USB Socket-1
LEDS--

And a soldering iron of course

 

 

PIN DIAGRAM - PIC18F4550

pic18f4550 pin diagram , USB interface Board , data sheet diagram

 

 

 

 

 

 

 

 

 

 

 

Guidelines While Making the Circuit Board for USB Interface

It is recommended to use a PCB for making this USB Interface Board . Over breadboard there are always chances of loose connections. On a Breadboard Sometime all the connections are perfect but still the PIC18F4550 is not detected by the system, (it will freak you out) , so better way is to use a PCB, I myself faced this problem, even though all the circuitry and connections were perfect and all checked up several times, but still no sign of life. So better to use a PCB on the first shot. You can alter the connection anytime on PCB if any mistake is detected on the USB interface board you are making.

-There are some basic things that you must always be cautious about while experimenting with any microcontroller. One thing that you must always be cautious about is, “the voltage”.

-In PIC18F4550 datasheet you can find the Vmax value, i.e. 5v. The voltage input to the microcontroller must never exceed this value under any condition or it will burn the microcontroller for sure.

The input voltage to a pic18f4550 Microcontroller under any condition should never exceed 5 V.

Always refer the data sheet of the respective microcontroller before doing anything with it.

-The standard voltage in any standard USB port is 5V, so you don’t have to worry about Vmax voltage while connecting this PIC18F4550 microcontroller Board to your computer USB port. For our USB Interface Board you don't need any External Power supply. If just in case you have to use an external power supply in spite of USB power supply then you can use a IC 7805 voltage regulator to keep the input voltage at constant 5 v.

The maximum length of any USB cable is 5 meters to the max. But I suggest for initial steps keep the connecting USB wire less than a meter for our board to work perfectly. There are only 4 or 5 pins in a USB PORT. D+ , D– , -Ve voltage (GND), +5v voltage and shield wire. You can check out for USB COLOR code pinout diagram in Google. Save a copy of USB PORT pinout config Picture from Google for further reference while you go on.

 

USB INTERFACE BOARD PIC18F4550

USB Computer control Board using pic18f4550 , USB Interface Development Board  PIC18F4550 USB demo interface Board

 

 

 

 

 

 

 

 -The crystal oscillator used in this pic18f4550 USB Interface Interface Board is 20MHZ crystal oscillator which is used for internal oscillation of the microcontroller and it is connected on 13 and 14 pin. I suggest to add a 1M resistor (1M=1000k) before the crystal oscillator on 13 and 14 pin.

- Don’t forget to short 11th and 32nd pin together and to 5 v of the USB +5v (+ve voltage) , similarly 12th and 31st pin to GND.(-ve voltage).

-The led’s on SPP 0 to SPP 7, add a 1 k resistance to each LED's. In case if you want to know how to identify the LED pins you can refer my LED IDENTIFY post.

-There are two switches in our board, one for bootloading and another one is the reset button, I will explain about the bootloading routine later in my other posts in details.

-By this USB Interface board we are going to control six pins, from SPP 0 to SPP7. For now we will use these pins to glow led’s , but these are control pins, we can use these to control other things too. It can easily interfaced with L293D Motor Driver, or you can interface it to run other dvice over USB like DC Motor, Stepper Motor, relay switches , servo etc. etc.

breadboard design for pic18f4550 USB Interface Board

 

 

 

 

 

 

 
USB HUB, pic18f4550 USB Interface Board

 

 

 

 

After you are done making with the USB Circuit Board

Simply connecting the USB cable from your computer to the USB Interface Board immediately after you complete the soldering won’t make it start working right away. Before the system (your computer) can detect this new hardware , you need to load a microcontroller program (code , usually a small hex file) into the pic18f4550 microcontroller, then your computer will detect it like any new external plug and play hardware and then you can install the driver‘s in your computer for this Board. A Step by Step tutorial to install the driver and links to download the drivers are given in my coming posts.

-The source Code for this pic18f4550 microcontroller is written in an IDE named as MPLAB IDE with a Compiler.
-The compiled code for this microcontroller will generate the output in the form of a small hex file. That hex file (firmware) will be loaded into the pic18f4550 microcontroller.
-For loading this Hex code into the pic18f4550 microcontroller you will need a special hardware [Microcontroller Programmer] I will also provide a tutorial to make your own Microcontroller Programmer to load the code into the Pic18f4550 Microcontroller. I will get into more details in my coming posts.

Usually the program loaded into the EPROM of the microcontroller is the firmware. The Firmware is loaded into the EPROM of the microcontroller, then we have to connect it to the USB port of the computer and then it will detected and then we have to provide the driver.

-After the circuit design is complete its time to test it out, as said before if you directly connect the USB Interface Board to your computer then the board will show no activity, we have to load it with a firmware first !!

So lets carry on with the next step - "1st time programming of the microcontroller" .

 

STEP 2 >>>1st time programming of the microcontroller

 

pic18f4550 microcontroller

 

 

 

PIC18F4550 CHIP

Thanks for reading
Rakesh Mondal

ron

Blink LED with XC8 compiler using external Oscillator

$
0
0

Blinking led using xc8 compiler, 20MHz oscillator with PIC18F4550

 

Blink led with external 20 MHz Oscillator and XC8 compiler using delays


In this tutorial we are going to blink few simple led's with PIC18F microcontroller, using an external 20MHz crystal oscillator and the '__Delay' function of XC8 Compiler. Most of my previous tutorials here dealt with internal oscillator of PIC18F4550, where mostly the delays were generated with simple “for” loops. However those who wish to directly use the default __delay_us or __delay_ms function, it becomes an instant pain as the __delay function no longer accepts the variable value, like the C18 Compiler.

This tutorial is made on few requests and queries I recently received through mails, regarding the delay problems in xc8 compiler, which is: The value of the delay for the function __delay_ms() must be a constant !For example: __delay_ms(20), (20 milliseconds delay),You cannot define a variable inside the __delay_us(), “example __delay_ms(X), where X is a int variable”, this was possible with C18. There is a solution to the delay problem with XC8 Compiler.

Hence I decided to put it together as tutorial to blink a simple led using external 20 MHZ Crystal oscillator on pic18f4550 with XC8 compiler and Mplab x ide.

It is all about setting the compiler directives correct to get the external oscillator working fine. The 20 MHz crystal oscillator is interfaced with two 22p capacitor as explained in the oscillator section in the pic18f4550 datasheet. Please download the latest version of datasheet for PIC18F4550 from the microchip website. A 0.1u cap is also added close to microcontroller.

The basic logic with any microcontroller is to turn the led on and then turn off by setting the registers, with some good delay in between the on and off, enough to catch the effect by human eye. There are many ways to generate such delays, such as using delays.h, making your own delay “for” loops,timer etc.

The theory goes as, if you wish to use xc8 delay function then you have to include delays.h as a header (preprocessor) and then include __delay_us(); or __delay_ms(); (with double underscore) anywhere you wish to have a delay. The desired delay must be a constant, such as ” __delay_ms(500);” which theoretically sounds simple.

But the problem is with the limits to the constant which is defined inside the __delay_ms() function. For example if you wish to generate a 200ms delay, then according to the theory all you have to do is :- __delay_ms(200) and you are done, but compiler wont accept the value and would result in an error. This is due to the limitation with the value of the constant.

The limit of the constant defined inside the delay function depends on the XTAL value defined in the Compiler directives.
"#define _XTAL_FREQ 20000000UL"

blink led with 20MHz Crystal Osc,pic18f4550

This limitation of the constant and the issue with passing a variable value to the Delay function can be solved by creating a function prototype, or by calling the delay function with a "for loop" whose parameters can be a variable. Now with the limited range of constant you can create delays of any length.

For example, if were to generate a delay of 200ms without any error, then i would enclose the __delay_ms(20); inside a "for" loop and call it 10 times, which should result a 200 millisecond delay.

The code I wrote below generates a delay of approximately 200ms, where for 20 MHz I have defined _XTAL_FREQ 20000000UL. Please note that XTAL_FREQ doesn’t really sets the frequency of the hardware, but it’s still required for __delay_ms to work. If you directly write the milliseconds values as __delay_ms(200); then immediately the compiler would throw an error on compiling the code. For the configuration I defined in my code,the compiler doesn’t want to accept the ms value greater than 39 milliseconds. Hence creating “for” loop again can be helpful when the ms value can’t be more then 39 for _XTAL_FREQ 20000000UL.

 For example:
 for ( int x=0; x<=20; x++ )    
    {
    __delay_ms(10);
    }

Approximately creates a delay of 200ms.

Schematic

blink led with xc8 with 20mhz on pic18f4550

Let's Start with Coding

-Start MPLABX IDE and create a New Project as explained in the previous post for pic18f4550.

-Add a new file and save it as MAIN.C

-Then start typing the source code as below.

Source Code:

#include <p18f4550.h>
#include <delays.h>

#define LD1 LATBbits.LATB7
#define LD2 LATBbits.LATB6

#define _XTAL_FREQ   20000000UL // This one is just for __delay_ms

#pragma config PLLDIV = 5       // PLL Prescaler Selection bits (Divide by 5 (20 MHz oscillator input))
#pragma config CPUDIV = OSC2_PLL3 // System Clock Postscaler Selection bits ([Primary Oscillator Src: /2][96 MHz PLL Src: /3])
#pragma config USBDIV = 2
#pragma config FOSC = HSPLL_HS  // Oscillator Selection bits (HS oscillator, PLL enabled (HSPLL))

// Everything is Off After this to make sure things do not go wrong

#pragma config FCMEN = OFF      // Fail-Safe Clock Monitor Enable bit (Fail-Safe Clock Monitor disabled)
#pragma config IESO = OFF       // Internal/External Oscillator Switchover bit (Oscillator Switchover mode disabled)
#pragma config PWRT = OFF       // Power-up Timer Enable bit (PWRT disabled)
#pragma config BOR = OFF        // Brown-out Reset Enable bits (Brown-out Reset disabled in hardware and software)
#pragma config BORV = 3         // Brown-out Reset Voltage bits (Minimum setting)
#pragma config VREGEN = OFF     // USB Voltage Regulator Enable bit (USB voltage regulator disabled)
#pragma config WDT = OFF        // Watchdog Timer Enable bit (WDT disabled (control is placed on the SWDTEN bit))
#pragma config WDTPS = 32768    // Watchdog Timer Postscale Select bits (1:32768)
#pragma config CCP2MX = OFF     // CCP2 MUX bit (CCP2 input/output is multiplexed with RB3)
#pragma config PBADEN = OFF     // PORTB A/D Enable bit (PORTB<4:0> pins are configured as digital I/O on Reset)
#pragma config LPT1OSC = OFF    // Low-Power Timer 1 Oscillator Enable bit (Timer1 configured for higher power operation)
#pragma config MCLRE = OFF      // MCLR Pin Enable bit (RE3 input pin enabled; MCLR pin disabled)
#pragma config STVREN = OFF     // Stack Full/Underflow Reset Enable bit (Stack full/underflow will not cause Reset)
#pragma config LVP = OFF        // Single-Supply ICSP Enable bit (Single-Supply ICSP disabled)
#pragma config ICPRT = OFF      // Dedicated In-Circuit Debug/Programming Port (ICPORT) Enable bit (ICPORT disabled)
#pragma config XINST = OFF      // Extended Instruction Set Enable bit (Instruction set extension and Indexed Addressing mode disabled
#pragma config CP0 = OFF        // Code Protection bit (Block 0 (000800-001FFFh) is not code-protected)
#pragma config CP1 = OFF        // Code Protection bit (Block 1 (002000-003FFFh) is not code-protected)
#pragma config CP2 = OFF        // Code Protection bit (Block 2 (004000-005FFFh) is not code-protected)
#pragma config CP3 = OFF        // Code Protection bit (Block 3 (006000-007FFFh) is not code-protected)
#pragma config CPB = OFF        // Boot Block Code Protection bit (Boot block (000000-0007FFh) is not code-protected)
#pragma config CPD = OFF        // Data EEPROM Code Protection bit (Data EEPROM is not code-protected)
#pragma config WRT0 = OFF       // Write Protection bit (Block 0 (000800-001FFFh) is not write-protected)
#pragma config WRT1 = OFF       // Write Protection bit (Block 1 (002000-003FFFh) is not write-protected)
#pragma config WRT2 = OFF       // Write Protection bit (Block 2 (004000-005FFFh) is not write-protected)
      // Write Protection bit (Block 3 (006000-007FFFh) is not write-protected)
#pragma config WRTC = OFF       // Configuration Register Write Protection bit
#pragma config WRTB = OFF       // Boot Block Write Protection bit (Boot block (000000-0007FFh) is not write-protected)
      // Data EEPROM Write Protection bit (Data EEPROM is not write-protected)
#pragma config EBTR0 = OFF      // Table Read Protection bit
#pragma config EBTR1 = OFF      // Table Read Protection bit
#pragma config EBTR2 = OFF      // Table Read Protection bit
#pragma config EBTR3 = OFF      // Table Read Protection bit
#pragma config EBTRB = OFF      // Boot Block Table Read Protection bit

void main(void)
{
   
    TRISBbits.TRISB6 = 0;  // Setting output
    TRISBbits.TRISB7 = 0;  // Output

 while(1)
 {
             LD1=1;
             LD2=0;

          for ( int x=0; x<=10; x++ )
            {
              __delay_ms(20);   // 20x10 200ms

            }
             LD1=0;
             LD2=1;

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

            {
              __delay_ms(20);

            }
       }
}

/* THE END */

Download the code main.c

 

NEXT CHAPTER4: Tutorial 2 – Method 2- Blinking led with pic18f4550 – header files

PreviousNext
 

Thanks for Reading
Ron



PIC18F4550 Programming tutorial chapter 4 and method 2 for programming

PIC18F4550 ADC Stepper Motor Speed Controller

$
0
0
PIC18F4550 ADC tutorial for Stepper Motor Speed Controller

 

 

 

 

PIC18F4550 Stepper Motor Speed Controller


This tutorial deals with controlling the speed of stepper Motor using a pic18f4550 Microcontroller with a potentiometer. In my previous project we have tried the same with Arduino but the stepper motor couldn’t endure the delay below 35 milliseconds in-between each Steps. This project is one of the many applications of Analog to Digital Converter (ADC).

The inbuilt ADC module of pic18f4550 is 10 bit, and will be used for sampling the analog input into digital output. The Configuration of ADC used in this project is best suited for room temperature, or else time taken to charge (Chold) the capacitor inside the ADC module of PIC18F4550 would go high, else known as acquisition time. The reference voltage Vref for the analog input channel would be 0v-5v. Due to the inaccuracy of the internal clocks of the PIC18F4550, we will use external oscillator (20MHZ) to clock the ADC module of this microcontroller.

Stepper Motor used in in this project is an M35SP unipolar stepper Motor with step angle of 7.8. A ULN2003 (NPN Darlington transistor) chip would be used for amplifying the microcontroller output pules to match up with the operational voltage of the Stepper Motor. To feed the analog input to the microcontroller we will use a 10K Potentiometer which would be rigged to AN0/RA0 Pin of the pic18F4550.

This Project takes a max of 45 minutes to complete and stepper Motor itself is probably the most expensive component in this complete setup. If you wish to know in details about ADC or other stepper motor tutorials then you can refer my previous posts.

 

IDE: MPLABX IDE
Compiler: XC8 Compiler (v1.34)
Microcontroller: PIC18F4550 – 40 PIN DIP
Programmer: PICKIT2
Stepper Motor: 5 Wire Unipolar M35SP -8 Stepper Motor ( Step angle 7.5)
Motor Voltage: 9V
POT: 10k Breadboard Type

 

ADC Configuration for PIC18F4550:


Reference voltage: 0- 5 V
ADRES Register: Right justified. 10 Bit ADC of PIC18F4550
TAD: 2TAD
Clock source: External
OSC: 20 MHZ crystal
Prescaler : 1/32 (1/16 will be too close , hence 32 is good)
Channel: AN01

Stepper Motor Wiring

If M35SP stepper Motor is used for your project then follow the wiring references and wire color codes given in the images below. If you wish to use any other stepper motor then you have to follow wiring labels and color codes of that respective stepper motor.

m35sp 8 stepper motor5 wire Stepper Motor Driver Color code wiring

 

Schematic:

Schematics for Stepper Motor ADC Speed Controller with PIC18F4550

 

Source Code


IDE: MPLABX IDE

Compiler: XC8 Compiler (v1.34)

A compiled version of HEX file, project files along and separate source code is given below. The Stepper Motor is configured on to work on port B (RB7 to RB 4), and it is coded to work on Single Step wave mode. However the source code can be easily modified to work on Half step and Full Step sequence by changing the output pins order pins with LATB register.

Source Code for ADC onfiguration of PIC18F4550

HEX File Download

Source code

Project Files

 

Thanks for reading
Rakesh Mondal


Related Topics

PIC18F4550 USB Interface Board
Arduino Steppe Motor Speed Controller

Stepper Motor Driver using PIC18F4550
Stepper Motor Schematics
Stepper Motor Controller using PIC18F2550
USB DC MOTOR Controller
L293D Motor Driver


 

PIC18F4550 TQFP Experiment | Breakout board

$
0
0
PIC18F4550 TQFP Experiment | Rakesh Mondal

PIC18F4550 has been an interesting Microcontroller so far for all kinds of experiments and learning for me. Interestingly Thin Quad Flat package is very small in size then that of a regular 40 pin Dual inline package and thereby reducing the size of the circuit board and project significantly. Sure the cost of TQFP is comparatively higher than the regular DIP PIC18F4550, but I found it worth to give it a try. Specifications are almost same to that of a regular dual inline package, only with four additional pins. There are lot of breakout board already available to get things started, but I preferred to make one for me rather than buying one.

DIP’s are easily available, but for TQFP variant of PIC18F4550 I had to wait for 25 days after placing order before it could be delivered as the local suppliers didn’t had these. It is more of an industrial grade package.

PIC18F4550 TQFP Custom breakout board

Unlike the regular DIP, the PIC18F4550 TQFP package has 44 Pins. This was my first ever attempt to work with TQFP. Since I was fairly new to micro soldering and dealing with small spaces, I had to practice a few times on old broken circuitry off some old malfunctioning router circuit board.

Note: Please be cautious while etching PCB, as it deals with potentially harmful chemical and equipment, the process is prone to accident. Micro soldering involves working with various equipment in a close proximity hence use necessary protective gears.

Like all the boards, the first step to begin with was to lay out a PCB design on my PCB designer. Probably this was the easiest part so far.

TQFP PIC18F4550 Custom breakout board design ready

But the real fun begins while carefully etching the board and later soldering the contacts.

The Plan is to make a custom breakout board with Jumper pins, and later adjusting the breakout schematics to all my future PCB boards. It would allow me to switch the microcontroller boards back and forth across my other projects. DIP’s are larger in size and there is always possibility of breaking few pins while switching across the 40 pin base on a frequent basis. But on my custom TQFP breakout board jumper pins are strong enough to deal with constant switching between my boards; on the event of damage, the pins can be replaced easily. Also TQFP occupies less space thereby making the projects smaller.

PIC18F4550 TQFP Custom breakout board design 1

TQFP PIC18F4550 breakout board design 2

PIC18F4550 TQFP breakout board – PCB layout Design

Etching a circuit board with such small space between the pins is challenging. I would highly recommend to stick with glossy paper (heat transfer paper) for printing the board instead of regular paper. The distance between the pins are so little that incase of errors, it is hard to make any corrections with marker.

PIC18F4550 TQFP breakout board – Etching the circuit 2

PIC18F4550 TQFP breakout board – Printing on Copper Board

PIC18F4550 TQFP Custom breakout board – Soldering connectors.

After few hours of careful soldering, the result was below. Fortunately I was able to make it work in the first attempt. I usually cover up the exposed copper with solder lead to mitigate the effects of corrosion after few months, also it makes the board less ugly.

TQFP PIC18F4550 breakout board – Micro soldering

PIC18F4550 TQFP Custom breakout board – Soldering connectors

I agree, not one of the best job in etching and soldering, but I tried by best.

TQFP PIC18F4550 breakout board

PIC18F4550 TQFP breakout board final design

Board 2 – The test board

Now since the board 1 which bears the Microcontroller is ready, it is time to test if it is working the way it’s supposed to be and all the contacts on the microcontroller is precise, without any loose ends. To do so I would need another board which would let me run experiments. The new board’s would bear female ports in the exact alignment to that of the male pins of the previous designed PIC18f4550 TQFN board 1, this new board if design carefully in perfect alignment should enable me to burn by codes with Pickit2 programmer.

Which bring to my next TQFP ICSP + Experiment Board

 

Thanks for Reading
Ron

TQFP PIC18F4550 Custom ICSP Board

$
0
0
PIC18F4550 TQFP Custom ICSP board

The Sole purpose of this circuit is to code and test the formerly build PIC18F4550 TQFP board.

I could have included an ICSP port on the formerly built Microcontroller board itself rather than making a separate ICSP board, but somehow it didn’t seem to me a very good idea to mess things up on the first very attempt to close the TQFP deal. Believe me, separate board made things less painful to debug when space between the pins were so less.

Hence I decided to isolate things to a different ICSP adapter board, which shall make things little less complicated, easy to debug and good probability of experimenting and testing without hurting the QFP microcontroller Board.

The microcontroller board bears Male Pins. So all the upcoming related board should have female Ports in the right alignment to that of the UC board, so it should fit right in.  There may be more than one way to make sure the alignment is correct, but for me the easiest way was to edit the previous Eagle project and build the next board around it without disturbing the pin alignment.

TQFP PIC18F4550 ICSP Custom board

First step was to open the Layout designer and print on heat transfer paper.

PIC18F4550 TQFP Custom ICSP Circuit PCB layout design

PIC18F4550 TQFP Custom ICSP Circuit Printing on paper

TQFP PIC18F4550 ICSP Custom board printing on Circuit

TQFP PIC18F4550 ICSP Custom Circuit Etching process

TQFP PIC18F4550 ICSP Custom Circuit Etching chemical dip

PIC18F4550 TQFP Custom ICSP Copper board Print

TQFP PIC18F4550 ICSP Custom board Ready and working

PIC18F4550 TQFP Custom ICSP Circuit design and logic

After all the soldering and connections, the formerly build Microcontroller board sat right into the ICSP board as expected. After a month of wait (Order and delivery) and few hours of etching followed by careful soldering, the effort paid off my when Pickit2 detected the PIC18F4550 on the very first attempt.

The ICSP board worked the way it’s supposed to be and the pins were tested on the Microcontroller board to perform some basic ADC, Input and Output operations which turned out to be successful. Now finally it’s time make some good use of the TQFP board.

It was time to place order for some SMD components for my upcoming boards, regular sized components were just using up unwanted space. So this led me to work on my next project.

PIC18F4550 TQFP BOT

TQFP PIC18F4550 ICSP Custom board

Thanks for Reading
Ron

TQFP PIC18F45550 Robot Platform (Bot Board)

$
0
0

After a series of successful test with PIC18F4550 TQFP microcontroller board, it was time to build some projects. The plan is to make sort of robot development board of my own which can allow me to test various codes and observe response of sensors in real time.

The Bot Development Board

Why to build a Development board of my own? The other robot kits which I have are bigger in size and I always end up reusing components or building on bread board, to test out certain code ideas to save time. With microcontroller development boards, I still have to build the robot from scratch after coding the microcontroller, I always end up disassembling the complete robot and breadboard over a course of time.

I wanted something which, uses pic18f4550, is smaller in size and the components are very easy to assemble without wiring up cables every time. So I decided to make robot board of my own, which fits my specific requirements, on which I can run my test anytime I want rather than investing time recreating complete robot again.

So my wishes and idea manifested into something which looks like below – version 1.0. I call it the BOT Board. It has a battery unit, Power Regulator, own set of wheels, DC motor controller, provision to add two Infrared sensors and an Ultrasonic Sensor. The onboard ICSP shall allow me to burn the codes directly. The battery unit is basically just a portable power bank, which I also use for changing my phone.

 

TQFP PIC18F4550 Microcontroller Robot Development Board
PIC18F4550 Microcontroller Robot Board PCB Circuit
PCB layout design PIC18F4550 Microcontroller Robot Board
PIC18F4550 Microcontroller Robot Board with motor driver
PIC18F4550 Microcontroller Robot Development Board ultrasonic sensor

Mplab X IDE Tutorial For blinking an LED and Comparison with Mplab IDE

$
0
0
Mplab X IDE Tutorial with XC8 Compiler

 

 

 

 

 

 

Mplab X IDE and XC8 C Compiler


Mplab X IDE is the latest avatar of Mplab IDE which is provided by microchip. It is launched with better features, interfaces and is quiet advanced IDE then the old version of Mplab which were introduced in the past.

In this tutorial we will see some basic and advanced features and benefits while coding with Mplab X over the traditional Mplab IDE. With a Sample source code at the end of this post I will also show a comparison of the output hex files generated with Mplab IDE and Mplab X IDE.

Now a days developer IDE for any programming language are Hi-end, like visual studio or Eclipse which provides better interface and features, but Microchips older versions of IDE never had these features of autocomplete and suggestions while writing the codes. Hence this new avatar as MPLAB X settles these problems and the way it looks.

The Mplab X IDE uses its platform as Netbeans from oracle, Hence while coding with it might make you feel as if you are working on Netbeans IDE, because lots of Mplab X features are taken from Netbeans.

Features of Mplab X IDE Over Mplab IDE


MPLAB X IDE and XC8 Compiler tutorial

Before installing you might want to update java for the installation to run smooth.  Since its java based IDE now, so Mplab X is not limited to windows.

As a long awaited feature, Mplab X IDE is now available on Linux and Mac OS versions also, which can be easily downloaded from microchip’s website for free. So the programmer does not have to be confined to a windows computer only, as it was the case with old versions of Mplab IDE. Apart from better looks and interface, one of the most amazing thing which can be noticed is the size of output after compilation (the hex file).

After coding and compiling the sample codes from my previoustutorials, I found that the compiled output hex files by XC8 were way smaller in size than that of the output from old Mplab IDE and C18 compiler. Hence compiling with Mplab X can save a lot of space.

In traditional Mplab IDE you had to be selective about the type of the compiler, for the family of microcontroller you are coding. For Example: To code a PIC18F family microcontroller you needed C18 Compiler and for PIC16F microcontroller it was required to install a different Compiler Toolsuite. Hence now microchip integrated most of its different compiler toolsuite into one XC8 compiler for Mplab x which support all 8, 16 and 32 bit microcontroller family. Hence all you need is just to download the Mplab X and XC8 Compiler.

The older version of Mplab projects can still be imported into the latest Mplab X without any difficulty with project wizard.

Note: I will try to attach an Mplab X version of project file for download with each of my old tutorials which were done on Mplab IDE. Lot of programmer who have the habit of programming with old versions of IDE sometimes find it little difficult to work with latest Mplab X versions, But it is really not so hard, once you get to know it more.  In this tutorial we are going to use Mplab X IDE and XC8 Compiler to code our microcontroller.

 


PIC18F4550 Programming with MPLAB X IDE


Programming a PIC18f4550 with Mplab X IDE and XC8 Compiler , project

Before we start coding on PIC18F4550 with mplab X , we need to create a new project just like Mplab IDE.

Creating a project is easy in Mplab X, just open the IDE and proceed to project wizard from file menu. Select the microcontroller family or directly type the name of the microcontroller in the device name.

Then select the hardware tool from the list, if you have any programmer like pickit2 connected then select pickit2 or go with the defaults and click next.

Select XC8 C compiler from the list of compiler which I assume you must have installed after installing Mplab X IDE and finally type a project name – and you are ready for coding.

It will open a blank project, Now you can create a new source file from the project explorer by right clicking on Source File> New> C main File.

Select your desired Name, the extension must be C and then finally click finish. It will open a default source code template; you are ready for coding with Mplab X.

Start mplab X IDE from LinuxMplab x IDE C8 - Create new Project for PIC18F4550

Select the PIC18F4550 Microcontroller

Mplab X xc8 Simulator select Tool

XC8 Compiler select from the list of available Compilers for mplab x IDE

Project name for PIC18F4550 Blink led with mplabX ide and XC8 Compiler

Blinking LED with PIC18F4550 on Mplab X IDE and XC8 Compiler for beginners

 

Blinking an LED with Mplab X IDE and PIC18F4550


For testing the Mplab X IDE we are going to use the same source code from one of my previous tutorial where we coded a pic18f4550 with Mplab ide for blinking an led. We are just going to replicate our previous tutorial with a different IDE.

  -Create a New project and select device as "PIC18F4550" from drop down menu, and proceed withcreating a new project with XC8 Compiler.

  -Create a New Source C file. And clean it up.

  -Copy the source code from previous post– Blinking an LED using pic18f4550.

  -Run > Build project.

If everything goes right then the output windows below will display a Build Successful message. The output window at the bottom will also show the location of .hex files which were just created. If you have a pickit2 attached then you directly burn the firmware into the microcontroller or  Navigate to the .hex file location which is usually,

            MplabProjectFoler/Projectname.X/Dist/Default/Production Folder

Search for the file with .hex in the production folder. If you have a pickit already attached then you can program directly or you can use other programmers to burn the output .hex file in to pic18f4550 microcontroller. The source code above should blink RB-0 and RB-1 alternatively with a dealy inbetween the two LED. The schematics are same as shown in my previous post.

Comparison of HEX files compiled with
MPLAB X IDE and MPLAB IDE v8


 

Now as I have mentioned before that you will notice that the size of the .hex file be much more shorter when you compile with Mplab X then that of Mplab IDE. Hence here we are going to do a small practical Observation.

Project for blinking led with same source code, I first compiled it with traditional MPLAB IDE and the .hex file came out something like this for just blinking two led.

.HEX file compiled With Mplab IDE ( C18 )

:020000040000FA
:06000000A8EF00F0120061
:020006000000F8
:08000800060EF66E000EF76E05
:10001000000EF86E00010900F550656F0900F550FB
:10002000666F03E1656701D03DD00900F550606F50
:100030000900F550616F0900F550626F0900090071
:10004000F550E96E0900F550EA6E09000900090053
:10005000F550636F0900F550646F09000900F6CF91
:1000600067F0F7CF68F0F8CF69F060C0F6FF61C0C5
:10007000F7FF62C0F8FF0001635302E1645307E039
:100080000900F550EE6E6307F8E26407F9D767C020
:10009000F6FF68C0F7FF69C0F8FF00016507000EB2
:0600A000665BBFD71200F1
:0A00A600D9CFE6FFE1CFD9FF040E29
:1000B000E126DE6ADD6ADECF02F0DDCF03F0D89004
:1000C000035004E6880E025C130E03581DE2020E74
:1000D000DB6A030EDB6A020EDBCF02F0030EDBCF1E
:1000E00003F0D890035004E6020E025C000E0358A1
:1000F00006E2020EDB2A030E01E3DB2AECD7DF2A3D
:10010000010E01E3DB2AD7D7040EE15C02E2E16ACB
:10011000E552E16EE552E7CFD9FF1200F00E936E83
:100120008A808A82C0DF8A908A92BDDFF9D7120066
:10013000000EF36E00EE00F0080E01D81200EA6027
:1001400002D0EE6AFCD7F350E9601200EE6AFCD7E9
:1001500013EE00F023EE00F0F86A019C04EC00F0CE
:0C016000B6EC00F08EEC00F0FBD71200B3
:02016C0012007F
:020000040030CA
:0100000024DB

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Now here is the .Hex file compiled with Mplab X ide with same source code for blinking two LED.

HEX file compiled With Mplab X IDE -XC8 Compiler

:04000000AFEF3FF02F
:107F5E000001B2EF3FF0F00E936E00D08A808A825D
:107F6E008A848A86C5EC3FF08A908A928A948A9691
:107F7E00C5EC3FF0F3D7F2D700EF00F0000E026E23
:107F8E00000E016E0250800A6D0F880ED8B4015C8F
:107F9E00D8A001D001D002D02BD02AD0000E046E72
:107FAE00000E036E0450800A800F020ED8B4035CDC
:107FBE00D8A001D001D002D00ED00DD0034A042A91
:107FCE000450800A800F020ED8B4035CD8A001D0F2
:107FDE0001D0F4D700D0014A022A0250800A6D0F58
:107FEE00880ED8B4015CD8A001D001D0D7D700D06C
:027FFE0012006F
:020000040020DA
:08000000FFFFFFFFFFFFFFFF00
:020000040030CA
:0E0000002408191EFF8385FF0FC00FE00F407C
:00000001FF

 

 

 

 

 

 

 

 

 

I hope you noticed the difference between the both .hex files. Hence Mplab X can really save a lot of space when you are dealing with really lengthy and complex codes where programmers have to take the size of the program into serious consideration.

 

Thanks for reading
Rakesh Mondal

Infrared IR Sensor Interface with PIC18F4550 Microcontroller

$
0
0
IR Sensor Interface with PIC18F4550 Microcontroller project - Digital Input

IR Sensor Interface with PIC18F4550


In my previous project we have made a simple IR sensor Circuit. In this project, as promised before – we are going to demonstrate a PIC18F4550 microcontroller interface to IR sensor circuit. We are just going to glow few on the pic18f4550 as an example, however you can do some more intelligent operations by adding some more logics to the microcontroller coding. Interfacing infrared Proximity sensors with Microcontroller is quiet easy.

This project is not only about interfacing an infrared IR sensor module but also we are going to learn - How to take digital input from a PIC18F4550 Microcontroller (Reading the Input with a Microcontroller). It means that the source code here will work same for taking input from a simple switch. You can replace the IR sensor with some simple PUSH Switch or some other types of proximity sensors . In case of push button you would need to pull down the pin to ground with 1 k resistance, however for IR sensor you won’t need to pull down the input pin with resistor.

Infrared IR Sensor Module

Let’s take a look at the IR Infrared Sensor Circuit Project module that we made in our previous project which is an inexpensive ( Low Cost ) sensor circuit module. You can find the schematic and PCB design in my previous post. There are three pins in the Schematic - Two pins for providing the input voltage and GND to the IR Sensor Module, and the third pin from the IR module is the IR control pin. This Control Pin from the IR sensor Module will be interfaced to the PIC18F4550 microcontroller for sensor input.

IR Sensor Module

Infrared IR sensor Object detection circuit Module design and pin settings

Concept

The output from the IR sensor circuit will be connected to pins of a PIC18f4550 microcontroller and the microcontroller will regard it as digital input to read either 1 or 0.  According to the output from the IR sensor module, the PIC18F4550 will respond by glowing led. Since we just want to read some voltage in the microcontroller as input (either High or low) hence we are going to configure input pins as digital to read just 1 or 0 from the sensor.

IR infrared Sensor circuit connected a with PIC18F4550 microcontroller project on breadboardProject: PIC18F4550 Microcontroller programming with IR sensor Module

 

PIC18F4550 Interface with IR sensor Circuit

The output from the IR sensor circuit is connected to RA0 of the pic18f4550 which is configured as input with TRISB registers, and the output will be displayed on LED connected across RD7, RD6,RD5 (PORTD) and RB0 and RB1 (PORTB) which are configured as output pins. Follow the schematic below.

Schematic (IR sensor and PIC18F4550 microcontroller)

Schematic for Infrared IR sensor circuit interfacing with a PIC18F4550 Microcontroller circuit


In this project we don’t need to perform any Analog to Digital Conversion(ADC), hence we are going to turn the ADC off (ADCON0bits.ADON = 0) and configure all the PINS to Digital.  At the default 1 MHZ oscillator frequency the output sometimes gives unstable result, hence tuning the microcontroller to 8MHZ solved the problem, Please note that pic18f4550 works by default on 1 MHZ and you can change the OSCCON bits settings to tune the oscillator frequency according to your requirement.

Search in pic18f4550 datasheet for OSCCON register bits and you will find a nice description and bits settings table for available oscillator frequency and settings to configure the microcontroller oscillator frequency. Here I have configured the internal oscillator to 8MHZ to avoid switch debouncing. However it works well with 1MHZ settings as well. As a better plan the comparator is also turned off to avoid any conflict.

                          All the resistors in the above Schematic is 1k resistance. If possible, it is also recommended to add a IC 7805 liner Voltage regulator IC as a source of +5V to avoid any voltage fluctuation which could possibly damage the microcontroller. Make sure the input voltage to pic18f4550 must never exceed +5v. Please do read the excellent pic18f4550 datasheet provided by microchip.

IR sensor circuit programmed with PIC18F4550 microcontroller as Digital Input pin

Source Code:

MPLAB IDE and C18 Compiler is used for compiling the source code, however MPLAB X IDE and XC8 Compiler can be also used with no difficulty. Download the entire project at the end of the source code below with compiled firmware. 

SOURCE CODE :infraredinput.c

/*
 * File:   infraredinput.c
* Author: ron
 * December 10, 2012, 1:21 PM
 */
#include <p18f4550.h>          // Include Header for PIC18F4550

#define switch1  PORTAbits.RA0  // Switch on RA0

#define led1    LATDbits.LATD7     // led1
#define led2    LATDbits.LATD6    // led2

#define led3    LATBbits.LATB0   // led3
#define led4    LATBbits.LATB1    // led4
#define led5    LATBbits.LATB2    // led5

void main (void)

{

            /* If you want your microcontroller to work at  1MHZ then comment the three lines below */

OSCCONbits.IRCF0 = 1 ;               // set internal clock to 8 MHz
OSCCONbits.IRCF1 = 1;                //  For Avoiding switch debouncing problem      
OSCCONbits.IRCF2= 1;                 //

/* Input output settings*/

       TRISAbits.TRISA0 = 1;                  //   RA0 Input for taking input from IR sensor

       TRISDbits.TRISD7 = 0;                  // Port D pins output
       TRISDbits.TRISD6 = 0;

       TRISBbits.TRISB0 = 0;                  // Port B pins Output
       TRISBbits.TRISB1 = 0;
       TRISBbits.TRISB2 = 0;

       CMCON = 0x07;           // Disable Comparator

       ADCON1bits.PCFG0 = 1;          // These 4 settings below determines the analog or digital input
       ADCON1bits.PCFG1 = 1;          // In our case we are making all the pins digital
       ADCON1bits.PCFG2 = 1;         // by setting them as 1111
       ADCON1bits.PCFG3 = 1;         // Check with the datasheet for a nice desc of these bits and config.

       ADCON0bits.ADON = 0;  //  Disabled ADC

while(1)
     {   //Forever Loop
            if(switch1 == 1)    //   On reading IR sensor value ON
                    {    //Turn led ON
                                led1 = 1;
                                 led2 = 1;
                              led3 = 1;
                              led4 = 1;
                                 led5 = 1;              }
       else if ( switch1 == 0) // On reading IR Sensor Value OFF
                      {   //Turn led off
                              led1 = 0;
                            led2 = 0;
                            led3 = 0;
                            led4 = 0;
                            led5 = 0;              }
                                     else {    }

    }   //End While loop --forever
}

/* THE END */

The coding above is pretty much self-explanatory, and comment lines must be also helpful for better understanding.


Now you can use this project to develop your own application the way you want. It's easy to interface this project with a L293D Motor Driver to drive DC motors as an "IR sensor Motor Driver" or a simple IR infrared robot, or you could add one more IR module on some other AN pin as switch2, with which you can make it as "IR Line follower robot" very easily.In my next tutorial I have also shown how to interface multiple IR sensors with Arduino Uno board and have the status of the sensor displayed on LCD.

Use the way your creativity drives you.

Download the Full Project

infraredinput.c

Firmware

Full Mplab IDE project file.zip (IR Digital input)

Mplab X IDE project (Digital Input)

 

Thanks for Reading
Rakesh Mondal
RON

PreviousNext

Top

IR sensor circuit Programmed with PIC18F4550 Microcontroller, programming pic184550 for digital input


USB Stepper Motor Driver

$
0
0
USB Stepper Motor Driver, PIC18F4550 USB Stepper Motor Controller

 

 

 

 

USB Stepper Motor Driver


In this project we are going to drive a unipolar Steppermotor(5 wire) using USB interface from a PC Computer. This project is an application of the USB Interface Board PIC18F4550 which was published here in the past. You can run other stepper motors too. It is simple and easy to make, we are going to use PIC18F4550 microcontroller which has an in built USB (USB 2.0) functionality which allows it to connect with any computer with a USB port and Windows OS. We will try to provide as much as details we can for achieving this project.

USB Stepper Motor driverUSB Stepper Motor driver

 

 

 

 

 

 

 

OLD METHOD: The legacy (OLD) method was to use a parallel port (DB 9), which were far more easy with simple port control commands, which were good enough to glow few led directly connected to COMM pins of a parallel port, and with a simple loop written in VB it was easy to generate a pulse of blinking led for a stepper motor.

USB: However laptops and portable computers don’t come with those big D9 (parallel or printer) port anymore, as the USB ports - due to its excellent characteristics and small size has taken its replacement for almost for any external device. USB interface for this project is going to be little complex then the old parallel port method.

The microcontroller which will serve as the communication channel between the Computer and Stepper motor, the PIC18F4550 microcontroller, can work in two USB speed 12Mbps(full speed) and 1.2Mbps(low speed).

For our project we will run this microcontroller board in Full speed (12Mpbs). The project can be also achieved with a PIC18F2550 with little modification in the firmware, but since 18F4550 has more number of pins on a standard Dual Inline package (40 pins, 20 pins on each side), so we will go with that. PIC18F4550 is far more cheap and inexpensive then an Arduino board. In fact the stepper motor here costs more than the entire board and components used.

usb stepper motor

 

 

 

 

 

 

 

Stepper Motor

The stepper motor used here is a 5 wire Stepper motor (M35SP-8) which is going to be operated by an application written in C#, (visual studio) which will communicate with the microcontroller board via USB, and microcontroller will drive the Motor connected with it according to the output directed by the software written in C#. The entire project and its necessary project files with schematics can be found at the end of this page.

Unipolar Stepper motor - 5 wire

The M35SP-8 Stepper Motor has a step angle of 7.5 degree, with one Common wire and 4 control wires connected to each coils. Hence we need only 4 control links for generating the pulse which will drive this stepper motor. For information on the specification of MS35SP-8 refer the respective datasheet.

 

Stepper Motor Wiring

The Figure below shows the labeling of the Stepper motor used for this project. If you wish to use any other stepper motor then you have to follow wiring labels of that respective stepper motor.

stepper motor wiring5 wire Stepper Motor Driver Color code wiring

Running other Stepper motors

The USB interface board we are using here has 6 control pins, it means you can control 6 LEDs (example) with this board. Out of which, only 4 pins are required to control our M35SP-8 Stepper motor, remaining 2 will be unused.

However you can run more kinds of stepper motor too. Since we have 6 control lines available hence the project can be easily modified to run other stepper motors too. Any stepper motor has one common ground wire and remaining are control wires, So technically with this USB interface board you can run a 5 wire, 6 wire and 7 wire stepper motor easily (6 control and one Common power).  

 

USB Interface Board Schematic


First start with the USB interface board, which will require a firmware to be loaded in the microcontroller and later, a windows driver, after the board is ready. I strongly recommend making this board on PCB.

You can find a detailed tutorial and specifications for making this board alone in my previousUSB Interface post. The firmware used here is the same firmware as in PIC18F4550 board with no modification. The components required are pretty much clear in the schematic or you are free to explore USB Interface Board post for detailed component list.

-Firmware Download

After making this board, connect it with computer USB port and it would ask you for driver.

-WIN XP driver
-WIN 7 Driver

The only thing here different is the C# application, which is written for running the stepper motor.

 

Schematic:

USB Stepper Motor Driver schematic

Connect two led across RD4 and RD5, which will display the status of the USB Board. IF the Communication between the computer and USB Board is successful then both the LED’s would blink alternatively.

The pins RD0-RD3 of the microcontroller is interfaced with 4 coils of the stepper motor, and the “Common wire” is interfaced the external 9V motor supply.  

USB Interface Board PIC18F4550 Microcontroller

 

PIC18F4550 USB Stepper Motor Circuit

USB stepper Motor Driver Circuitry

The output voltage across the RD pins of the microcontroller would be enough to glow few LED, but it is not enough to run our MS35SP-8 stepper motor, hence we are going to use a Darlington pair of transistors for high voltage switching.

 

uln2003-Interface

For such purpose we will use ULN2003 IC, UlN2003 is a monolithic high voltage Darlington array IC, which contains an array of transistors (bipolar transistors) which will do the switching for us, with excitation of low voltage input.  

On the USB interface board we cannot increase the voltage more than 5v, or it will kill the microcontroller instantly (Refer the PIC18F4550 datasheet) and the output pulses generated will be low voltage hence ULN2003 is used, which would drive our load (stepper motor). We will feed the ULN2003 with 9V power supply which will run the stepper motor. Refer the ULN2003 datasheet for its technical specifications. A typical L293D motor Driver can be also used for such purpose, but that will make circuitry little bit more complex, hence uln2003 is good enough.

After making the USB interface board to work, it’s a good idea to test with 4 leds, after that interface it with uln2003 as showed in the schematic above, make sure you check all the connections before testing it out. Be careful because we are introducing 9V to the ULN2003, the microcontroller directly cannot bear 9v as mentioned before.

Note: Do not forget to connect the Ground pin (GND) of the Microcontroller board to the ULN2003 GND pin (pin8)

 

Application C#


After the USB board is successfully installed on the PC with the drivers provided, the led on RD4 and RD5 would start to blink alternatively. Now start the application. The Application here is written on C# forms. Open the project file and everything will be quiet easy to code and modify, or to add more steps for stepper motor.

 

Application for controlling and driving USB Stepper Motor

CS application

You can also alter the time delay in between each step by entering the ms value on the software application for this driver.

Stepper Motor Stepping Sequence

As of now only three modes has been added for this stepper motor.

Stepper Motor Modes Steppings

 

 

 

The truth table below shows how pins are set and phases are energized according to the modes.

 

Single Step Wave mode: C1, C2, C3, C4 are coils connected to RD0, RD1, RD2 and RD3 pins of USB pic18f4550. In this mode only single phase is energized (Single phase excitation) for the running the motor. Single stepping (wave) mode gets completed in 4 cycles, A, B, C and D which then repeats over again from the beginning (loop) at the end. At the end of 4 cycles the Stepper motor shaft completes one revolution.

 

Stepper-Motor-Steppings-Wave-single step

 

Full Step Sequence mode: This mode drives with Dual phase excitation, which means that two phases are energized at a time and hence results in more torque. This mode also has 4 cycles, A, B, C, and D. However the motor in this mode runs with little more toques then that of wave mode.  At the end of last cycle the motor loops over the same.

 

Half wave stepper motor stepping

 

Half Step sequence mode: This mode is the combination of both Single phase excitation and dual phase excitation, in this both single and dual phases are energized alternatively for running the Stepper Motor. This mode of operation has 8 cycles or steps for completing one rotation of the motor shaft. This mode provides pretty good resolution but the speed is going to be slow.

 

Half wave Stepper motor steppings

You can toggle the modes the way you want in the application running on the desktop for the speed and step mode you want.

If you want to run a 6 wire stepper motor then you can easily modify the code on the C# application, by adding some more port control commands and sequence of loop. The source code is pretty much self-explanatory and can be very easily modified.

USB Stepper Motor project

Testing Stepping Pulse with LED

Before connecting and ULN2003 to the circuit board, you can test if the Stepper motor Stepping pulses are generating on the pins the way it is supposed to be, by connecting 4  led across the RD0 to RD3. Watch this video below for a small demonstration.

Don’t connect the LED across the output pins of ULN2003 or the Led’s will get damaged, Connect them directly to the RD pins with 1 k resistance each. Start the software and hit Start motor button.

LED connected to stepper motor for testing usb LED connected to stepper motor for final test

The label on the C# application will update according to the Stepping pulse sent to the PIC18F4550, If everything is working fine and the led’s are blinking in the way shown in the stepping truth table above, then  connect the uln2003 and stepper motor to the board.

Stepper Motor Interfaced to ULN2003

 

 

PROJECT FILES

-C# Stepper motor Driver Software application
-Firmware for microcontroller

-Driver download – XP
-Vista and Win 7

-Schematics

 

Thanks for reading
Rakesh Mondal.

USB Stepper Motor Controller Driver Project

Stepper Motor Driver using PIC18F4550 Microcontroller

$
0
0
Stepper Motor Driver tutorial using PIC18F4550 Microcontroller , PIC18F4550 stepper Motor interface

 

 

 

 

Stepper Motor Tutorial


In this tutorial we are going to drive a Single unipolar stepper motor using PIC18F4550 Microcontroller in various different stepping modes. The source code and Project files are free to download at the end of this page.

Stepper motor due its excellent features is very famous in between hobbyist for various robotic applications. Running DC, Stepper motor and servo is the most basic requirement in any robotic application which moves. Stepper motor’s ability to run in various modes with various speed and torque gives it a more degree of advantage over the simple DC motor for various projects, especially in robotics based projects.

USB Stepper Motor driverSo in this basic stepper motor tutorial we will learn to drive a simple 5 wire uni-polar stepper motor using a 40 pin PIC18F4550 microcontroller.

For a little more sophisticated Stepper motor Driver you can also follow my USB Stepper Motor Driver project which is quiet similar to current project , however this driver tutorial does not involve any interaction to any computer system directly except for writing the codes.

 

 

-5 wire Unipolar Stepper Motor
-Bread board
-PIC18F4550 Microcontroller
-IC 7805
-ULN2003 (For better Results)

Unipolar Stepper motor - 5 wirePIC18F4550 Microcontroller Interface with Stepper Motor

Stepper Motor Schematic for PIC18F

 

 

 

 

 

 

The stepper Motor can be also connected directly without ULN2003, but during the testing the results were not satisfactory hence a ULN2003 was added.

Caution!: 9V power supply is given to Stepper Motor which is not same as the voltage for the PIC18F4550 power supply (5V). Do not connect both the power supply together as the PIC18F4550 cannot bear more than 5V, both the supply must not be shot together or the microcontroller will be damaged.

If you have a single source of power supply for both the Stepper motor supply and Microcontroller, then add a MCP102 or an IC 7805 Voltage regulator (5v) before the VSS terminal of the Microcontroller, which would keep the input voltage to microcontroller at 5V.

is

 

 

Stepper Motor Driver with IC 7805 voltage regulator

 

 

 

 

 

 

 

 

 

Stepper Motor Wire Color Code


It is important to understand the color code of the stepper motor for identifying the Coils and Common wire before it can be connected across the Microcontroller pins. The diagram below shows which color cables are connected across which pin of the microcontroller.

Motor wiring color codeStepper Motor Color codes

 

 

 

 

 

 

 

Compiler IDE and Source code


The source code is compiled with MPLAB X IDE and X C8 Compiler which can be loaded into the microcontroller using pickit2 or JDM Programmer. It can be also compiled with Mplab and C18 compiler without much effort. For convenience I have added both versions of the source code at the end of this post with the compiled HEX file. For our Stepper Motor Driver we are not going to use any external Oscillator with the microcontroller.

There are two source code posted here, the source code 1 demonstrate the basic and simple Single Stepping mode of a stepper motor. The second source code is little more complex and has three other stepping modes (Single, FULL and HALF) cycling with delay of 5 seconds each.

-Source Code - 1

-Source Code - 2


 

stepper motor wiringThe first code demonstrates Single stepping mode for driving our 5 wire uni-polar stepper Motor. Where the Stepper Motor coils are connected to PIC18F4550 pins, RD4, RD5, RD6 and RD7.

You would also require a header file which contains the various compiler directives, which is common for both the source codes 1 and source code 2.The delay has been set to 50000 microsecond or 50 milliseconds.

If in case if you want to use __delay_us( ); instead of __delay_ms( ); for adding delays then you can use some time converters or my favorite online scientific calculator ( eeweb calculator ) for ms to us conversion.

Download Steppemotor.c, Header.c and output1.hex

You can download the entire Mplab X –XC8 project at the end of this post.

Stepper-Motor-Steppings-Wave-single step

In the above sample source code excites each coil with delay of few milliseconds and loops over again from the beginning endlessly for the next cycle.

In this mode only single phase is energized at a time, and for completing one complete revolution of the motor shaft it take 4 cycles, and only one coil is energized at a time and during next cycle previous coil goes low 0 and next one goes high 1.

 

 

Stepper Motor Scource code tutorial1

Stepper Motor Using PIC18F4550This source code demonstrates three modes of stepper motor which are Single stepping mode, half wave stepping mode and Full Wave stepping mode. Each mode executes for 5 to 6 seconds and then executes next mode. The schematic for this Source code is little different.

The Stepper Motor coils are connected across PIC18F4550 pins RD4, RD5, RD6 and RD7. Also 4 LEDS are connected across RB0, RB1, and RB2 acting as indicator for the mode in which the stepper motor is running.  Follow Schematic 2 for Source code 2.

Stepper motor stepping modes

RB0 - Single Wave Stepping
RB1- Half Stepping mode
RB2- Full Stepping mode

Download Steppemotor.c, Header.h and output1.hex

You can download the entire Mplab X –XC8 project at the end of this post.

 

Full stepping mode and Half stepping Logic diagram

Truth table representation of the stepper motor stepping sequence.

FULL wave stepper motor steppingHalf wave Stepper motor steppings

 

Testing Stepper Motor Stepping Pulse with LED

After Coding and burning the firmware, you can test the stepper Motor stepping pulse generated by the microcontroller, by connecting few LED across the PIC18F4550 pins directly. In the video below, we are first going connect few LED's instead of Stepper Motor, and test whether the microcontroller is generating the stepping pulse the way it is supposed to generate. Be sure not to connect the LED's to the uln2003 pin, connect it across the Microcontroller Pins directly or the high voltage (9v) across the ULN2003 would damage the LED for sure. The LED's should blink and pulse the according to the source code and truth table above.

If the output stepping pulses are generating on the LED's the way is it coded, then you can proceed forward and connect the ULN2003 and Stepper motor according to the schematic.

Stepper Motor Step sequence detailsStepper Motor Step sequence PIC18F4550

 

 

 

 

 

 

Project Files

Stepper Motor 1

Stepper Motor 2

Thanks for Reading
Ron


Related Topics

Stepper Motor Drivers
USB Stepper Motor Driver
Stepper Motor Schematics
PIC18F4550 Microcontroller


PIC18F4550: Blink led with 20MHZ oscillator - XC8

$
0
0
PIC18F4550 for Blinking led using 20MHZ external Oscillator with XC8 Compiler

 

PIC18F4550 Tutorial: Blink led with 20MHZ Oscillator (XC8 Compiler)


In this tutorial we are going to blink few simple led's with PIC18F microcontroller, using an external 20MHz crystal oscillator and the '__Delay' function of XC8 Compiler. Most of my previous tutorials here dealt with internal oscillator of PIC18F4550, where mostly the delays were generated with simple “for” loops. However those who wish to directly use the default __delay_us or __delay_ms function, it becomes an instant pain as the __delay function no longer accepts the variable value, like the C18 Compiler.

This tutorial is made on few requests and queries I recently received through mails, regarding the delay problems in xc8 compiler, which is: The value of the delay for the function __delay_ms() must be a constant !For example: __delay_ms(20), (20 milliseconds delay),You cannot define a variable inside the __delay_us(), “example __delay_ms(X), where X is a int variable”, this was possible with C18. There is a solution to the delay problem with XC8 Compiler.

Hence I decided to put it together as tutorial to blink a simple led using external 20 MHZ Crystal oscillator on pic18f4550 with XC8 compiler and Mplab x ide.

It is all about setting the compiler directives correct to get the external oscillator working fine. The 20 MHz crystal oscillator is interfaced with two 22p capacitor as explained in the oscillator section in the pic18f4550 datasheet. Please download the latest version of datasheet for PIC18F4550 from the microchip website. A 0.1u cap is also added close to microcontroller.

The basic logic with any microcontroller is to turn the led on and then turn off by setting the registers, with some good delay in between the on and off, enough to catch the effect by human eye. There are many ways to generate such delays, such as using delays.h, making your own delay “for” loops,timer etc.

The theory goes as, if you wish to use xc8 delay function then you have to include delays.h as a header (preprocessor) and then include __delay_us(); or __delay_ms(); (with double underscore) anywhere you wish to have a delay. The desired delay must be a constant, such as ” __delay_ms(500);” which theoretically sounds simple.

But the problem is with the limits to the constant which is defined inside the __delay_ms() function. For example if you wish to generate a 200ms delay, then according to the theory all you have to do is :- __delay_ms(200) and you are done, but compiler wont accept the value and would result in an error. This is due to the limitation with the value of the constant.

The limit of the constant defined inside the delay function depends on the XTAL value defined in the Compiler directives.
"#define _XTAL_FREQ 20000000UL"

blink led with 20MHz Crystal Osc,pic18f4550

This limitation of the constant and the issue with passing a variable value to the Delay function can be solved by creating a function prototype, or by calling the delay function with a "for loop" whose parameters can be a variable. Now with the limited range of constant you can create delays of any length.

For example, if were to generate a delay of 200ms without any error, then i would enclose the __delay_ms(20); inside a "for" loop and call it 10 times, which should result a 200 millisecond delay.

The code I wrote below generates a delay of approximately 200ms, where for 20 MHz I have defined _XTAL_FREQ 20000000UL. Please note that XTAL_FREQ doesn’t really sets the frequency of the hardware, but it’s still required for __delay_ms to work. If you directly write the milliseconds values as __delay_ms(200); then immediately the compiler would throw an error on compiling the code. For the configuration I defined in my code,the compiler doesn’t want to accept the ms value greater than 39 milliseconds. Hence creating “for” loop again can be helpful when the ms value can’t be more then 39 for _XTAL_FREQ 20000000UL.

 For example:
 for ( int x=0; x<=20; x++ )    
    {
    __delay_ms(10);
    }

Approximately creates a delay of 200ms.

Schematic

blink led with xc8 with 20mhz on pic18f4550

Let's Start with Coding

-Start MPLABX IDE and create a New Project as explained in the previous post for pic18f4550.

-Add a new file and save it as MAIN.C

-Then start typing the source code as below.

Source Code:

#include <p18f4550.h>
#include <delays.h>

#define LD1 LATBbits.LATB7
#define LD2 LATBbits.LATB6

#define _XTAL_FREQ   20000000UL // This one is just for __delay_ms

#pragma config PLLDIV = 5       // PLL Prescaler Selection bits (Divide by 5 (20 MHz oscillator input))
#pragma config CPUDIV = OSC2_PLL3 // System Clock Postscaler Selection bits ([Primary Oscillator Src: /2][96 MHz PLL Src: /3])
#pragma config USBDIV = 2
#pragma config FOSC = HSPLL_HS  // Oscillator Selection bits (HS oscillator, PLL enabled (HSPLL))

// Everything is Off After this to make sure things do not go wrong

#pragma config FCMEN = OFF      // Fail-Safe Clock Monitor Enable bit (Fail-Safe Clock Monitor disabled)
#pragma config IESO = OFF       // Internal/External Oscillator Switchover bit (Oscillator Switchover mode disabled)
#pragma config PWRT = OFF       // Power-up Timer Enable bit (PWRT disabled)
#pragma config BOR = OFF        // Brown-out Reset Enable bits (Brown-out Reset disabled in hardware and software)
#pragma config BORV = 3         // Brown-out Reset Voltage bits (Minimum setting)
#pragma config VREGEN = OFF     // USB Voltage Regulator Enable bit (USB voltage regulator disabled)
#pragma config WDT = OFF        // Watchdog Timer Enable bit (WDT disabled (control is placed on the SWDTEN bit))
#pragma config WDTPS = 32768    // Watchdog Timer Postscale Select bits (1:32768)
#pragma config CCP2MX = OFF     // CCP2 MUX bit (CCP2 input/output is multiplexed with RB3)
#pragma config PBADEN = OFF     // PORTB A/D Enable bit (PORTB<4:0> pins are configured as digital I/O on Reset)
#pragma config LPT1OSC = OFF    // Low-Power Timer 1 Oscillator Enable bit (Timer1 configured for higher power operation)
#pragma config MCLRE = OFF      // MCLR Pin Enable bit (RE3 input pin enabled; MCLR pin disabled)
#pragma config STVREN = OFF     // Stack Full/Underflow Reset Enable bit (Stack full/underflow will not cause Reset)
#pragma config LVP = OFF        // Single-Supply ICSP Enable bit (Single-Supply ICSP disabled)
#pragma config ICPRT = OFF      // Dedicated In-Circuit Debug/Programming Port (ICPORT) Enable bit (ICPORT disabled)
#pragma config XINST = OFF      // Extended Instruction Set Enable bit (Instruction set extension and Indexed Addressing mode disabled
#pragma config CP0 = OFF        // Code Protection bit (Block 0 (000800-001FFFh) is not code-protected)
#pragma config CP1 = OFF        // Code Protection bit (Block 1 (002000-003FFFh) is not code-protected)
#pragma config CP2 = OFF        // Code Protection bit (Block 2 (004000-005FFFh) is not code-protected)
#pragma config CP3 = OFF        // Code Protection bit (Block 3 (006000-007FFFh) is not code-protected)
#pragma config CPB = OFF        // Boot Block Code Protection bit (Boot block (000000-0007FFh) is not code-protected)
#pragma config CPD = OFF        // Data EEPROM Code Protection bit (Data EEPROM is not code-protected)
#pragma config WRT0 = OFF       // Write Protection bit (Block 0 (000800-001FFFh) is not write-protected)
#pragma config WRT1 = OFF       // Write Protection bit (Block 1 (002000-003FFFh) is not write-protected)
#pragma config WRT2 = OFF       // Write Protection bit (Block 2 (004000-005FFFh) is not write-protected)
      // Write Protection bit (Block 3 (006000-007FFFh) is not write-protected)
#pragma config WRTC = OFF       // Configuration Register Write Protection bit
#pragma config WRTB = OFF       // Boot Block Write Protection bit (Boot block (000000-0007FFh) is not write-protected)
      // Data EEPROM Write Protection bit (Data EEPROM is not write-protected)
#pragma config EBTR0 = OFF      // Table Read Protection bit
#pragma config EBTR1 = OFF      // Table Read Protection bit
#pragma config EBTR2 = OFF      // Table Read Protection bit
#pragma config EBTR3 = OFF      // Table Read Protection bit
#pragma config EBTRB = OFF      // Boot Block Table Read Protection bit

void main(void)
{
   
    TRISBbits.TRISB6 = 0;  // Setting output
    TRISBbits.TRISB7 = 0;  // Output

 while(1)
 {
             LD1=1;
             LD2=0;

          for ( int x=0; x<=10; x++ )
            {
              __delay_ms(20);   // 20x10 200ms

            }
             LD1=0;
             LD2=1;

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

            {
              __delay_ms(20);

            }
       }
}

/* THE END */

Download the code main.c

 

NEXT CHAPTER4: Tutorial 2 – Method 2- Blinking led with pic18f4550 – header files

PreviousNext
 

Thanks for Reading
Ron


PIC18F4550 Programming tutorial chapter 4 and method 2 for programming

Viewing all 25 articles
Browse latest View live