PIC32MX: Digital Outputs
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.
Available Pins
Digital Output Example
This section describes how to set up and write digital outputs using a PIC32MX460F512L.
Sample Code
Program to turn on LEDs based on User Switch of UBW32. swUser must be defined for a switch (digital input) if not using UBW32.
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 constants for 4 output pins. LATx is the function used to write to a pin.
#define PIN_D4 LATDbits.LATD4 #define PIN_D5 LATDbits.LATD5 #define PIN_D6 LATDbits.LATD6 #define PIN_D7 LATDbits.LATD7
Begin main body of program.
int main(void){
Configure the proper PB frequency and number of wait states in this case 80MHz.
SYSTEMConfigPerformance(80000000L);
Set all analog pins to be digital I/O
AD1PCFG = 0xFFFF;
Turn off JTAG so we get the pins back
mJTAGPortEnable(0);
The pins that we want to use as outputs must be initialized as an outputs. 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 TRISX &= Hex number; We use &= hex number to only change the pins that we want to set as inputs / outputs.
Set D4, D5, D6, and D7 as a digital outputs
LATD |= 0x00F0; TRISD &= 0xFF0F;
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(swUser) { PIN_D4 = 1; PIN_D5 = 0; PIN_D6 = 1;
PIN_D7 = 0; } else {
PIN_D4 = 0; PIN_D5 = 1; PIN_D6 = 0; PIN_D7 = 1; } } } // end main