PIC32MX: Digital Inputs

From Mech
Revision as of 13:20, 5 January 2010 by Andrew Long (talk | contribs) (→‎Digital Inputs Example)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

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

/********************************************************************
Digital Input Code
Andrew Long
********************************************************************/

#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_A9 which reads the digital input. 
// PORTx reads on port x the current value of the pin (in this case A9).

#define INPUT_A9       PORTAbits.RA9

int main(void)
{
    // Configure the proper PB frequency and the number of wait states
	SYSTEMConfigPerformance(SYS_FREQ);

	// Set all analog pins to be digital I/O
   AD1PCFG = 0xFFFF;

	//Initialize all of the LED pins
	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 TRISA &= Hex number; 
	// We use &= hex number to only change the pins that we want to set as inputs / outputs.
	//Set A9 as a digital input
	TRISAbits.TRISA9=1;	

    while(1)
    {
		mLED_2_On();

		// What we're going to do is blink an LED on and off
	    // depending on whether or not digital input is high or low.
		if (INPUT_A9 == 0)
		{
		    mLED_3_On();
		}
		else
		{
			mLED_3_Off();
		}
    }
}