In previous post, we found how to program LPC1768 microcontroller to drive LED. This has been done by configuring GPIO into output mode. Adding button or switch to circuit enables the microcontroller to receive human input. Here in this tutorial, we’ll discuss how to add button switch to LPC1768 Microcontroller project. In this task we will program microcontroller pins to input. Our goal is that, LED should turn OFF when switch is pressed.
Circuit Connection: Add Button Switch to LPC1768 Microcontroller
Let’s go back to our development board which already has LED connected to Pin P1.29. To add switch at P1.28 Pin of microcontroller, we have to prototype small circuit on breadboard. Just hook up LED (If in case not available on your board) and button switch. Here is circuit diagram for your reference,
To use GPIO port pin P1.28 as input to read switch state. It’s required to set the GPIO port into input mode. We’ll discuss more about that later on. Let’s have a look into programming part of application:
Source Code: Add Button Switch to LPC1768 Microcontroller[crayon-5c6abe0755e01109311035/]
Download Files: Add Button Switch to LPC1768 Microcontroller Project.
After careful observation, you can say that program is not much different from previous example. The only addition is of extra function i.e. int getPinState(int pinNumber). Let’s discuss each line of program step-by-step:
[crayon-5c6abe0755e0e575674308/] Here we have set the bit low which set direction of pin P1.28 to input mode. As we have connected button switch to P1.28.
[crayon-5c6abe0755e14060251291/] Set the port pin P1.29 to HIGH. To drive LED at any pin we required to set direction into output mode.
[crayon-5c6abe0755e1a077504270/] Here we set pin P1.29 to logic “HIGH”. As we decided to turn LED ON from beginning of program flow.
[crayon-5c6abe0755e1f157372224/] This never ending loop keep checking status of pin P1.28 i.e. Switch. If Switch Released i.e. logic “HIGH”, turns the LED ON. When Switch Pressed i.e. logic “LOW”, turn the LED OFF. Now let’s get into key part of this program.
[crayon-5c6abe0755e25301268445/] getPinState(int pinNumber) function returns the current state of pin. Here in this case we have used getPinState(28) in while loop which reads the status of GPIO port pin P1.28 and returns status either HIGH(“1”) or LOW(“0”). This pin status used further to turn LED either ON or OFF.
When you build and run this program on your LPC1768 device. You will find LED will stays turned ON all the time. Just press switch to see effect which turn LED OFF until you hold switch to LOW.