Tutorial 3: Switch and LED
Objectives Learn how to use GPIO pins for reading a digital input signal and using it to control an LED.
1. Open the MPLAB IDE and create a new project name it “SW_LED”.
2. Set the configuration bits to match the generic settings.
We use an 8 MHz crystal oscillator.
Go to Production → Set Configuration Bits , do configuration, then generate and use it in the code.
To obtain a more organized code, we create a file “config.h” in Header file and then we copy the
generated configuration bits to it.
3. Create a file named main.c in Source Files.
Include the created “config.h” as header in the main.c:
• Configure the used pins
We’ll use a couple of GPIO pins:
The first one will operate as a digital input pin and will be hooked to the push button to read its logical
state (high/low).
The second pin will operate as a digital output pin and will be hooked to the LED to toggle it when the
switch is pressed.
Let’s set the RB0 pin to be an input pin and RC0 to be an output.
First a define names to obtain a more readable code. I define also the external crystal frequency.
Note that we don’t have pin RC0 cannot be defined as analog. Therefore, we don’t need to define this pin
as digital.
Then, I configure the used pins in the void_main().
4. Write code and compile it.
Toggle the LED when the switch is
pressed, then delay for 250 ms. We use a
pull-up resistor, therefore, when the SW is
pressed the state of the pin will be low (0).
Use the __delay_ms() macro requires that
the pre-defined name _XTAL_FREQ to
be holding your actual oscillator’s
frequency value.
5. Simulation: The schematic is shown below. Just create a similar one in your simulator (Proteus software).
6. After connecting everything up in your simulator, you’ll have to double-click the MCU chip and point
to the firmware code .hex file. The path will be as follows
ProjectName.X > dist > default > production > [Link]
Make sure to simulate your project at the same oscillator frequency used in the code. Otherwise, the
timing diagram will be messed up.
7. We can obtain more organized code as follows:
• Create “pin_manager.h” header file and copy pin definition to it.
• Create “pin_manager.c” source file, and create a function named pin_initialize to set used pins
directions and nature.
• Return to pin_manager.h file and write the function prototype.
• Finally, include “pin_manager.h” in main.c and use the pin_initialize function.