PIC32MX: Digital Inputs

From Mech
Revision as of 12:14, 5 January 2010 by Andrew Long (Talk | contribs)
Jump to: navigation, search

Working with digital inputs and outputs is fundamental to circuit design, and PIC microcontrollers add versatility to design by allowing programming and re-programming of the logic associated with input and output pins. In this way, one PIC microcontroller can take the place of many pre-programmed digital logic ICs.

Digital Inputs Example

This section uses an example to describe how to set up and read digital inputs using a PIC32MX460F512L.

Sample Code

Program to display push-button input as LED (on board) output

First include header files with definitions for generic type definitions, compiler, and for specific PIC. Also include the plib header file.

  #include "GenericTypeDefs.h"
  #include "Compiler.h"
  #include "HardwareProfile.h"
  #include <plib.h>

NOTE THAT BECAUSE WE USE THE BOOTLOADER, NO CONFIGURATION IS NECESSARY. THE BOOTLOADER PROJECT ACTUALLY CONTROLS ALL OF OUR CONFIG BITS.

Define a constant INPUT_G0 which reads the digital input. PORTx reads on port x the current value of the pin (in this case G0).

  #define INPUT_G0       PORTGbits.RG0

Begin main body of program.

  int main(void){

Configure the proper PB frequency and number of wait states in this case 80MHz.

  SYSTEMConfigPerformance(80000000L);

Initialize the LEDs on the board. This function may be different depending on the hardware profile. This function is for UBW32.

  mInitAllLEDs();

The pin that we want to use as an input must be initialized as an input. TRISx is a register that sets the pin as an input (1) or an output(0). You can set entire ports as inputs / outputs by using TRISG &= Hex number; We use &= hex number to only change the pins that we want to set as inputs / outputs.

  TRISGbits.TRISG0=1;

Use while to set up infinite loop. What we're going to do is blink an LED on the board on and off depending on whether or not the digital input is high or low.

   while(1)
   {
            if (INPUT_G0)
            {
                mLED_3_On();
            }
            else
            {
                mLED_3_Off();
            }
       }
   }


Circuit Diagram

Personal tools