In this lesson will use GPIO as input. In lesson-0 we write a program which sent "Hello Embedded World" to the PC once the board get programmed. Here we will send "USER BTN1 Is Pressed" to PC when the pushbutton is pressed.
- A) Creating a new ModusToolbox application
- (B) Add Library
- (C) Device Configurator
- (D) Sending pushbutton status.
(A) Create Empty App and name it "lsn1PushButton. (Lesson-0 Review)
(B) Add retarget-io library (Lesson-0 Review)
(C1) Quick Panel -> Device Configurator -> Pins
(C2) Enter filter text as "BTN"You will see the macro name CYBSP_USER_BTN1 for port 1 and pin 4 which is connected to USER BTN1 on the board.
(D1) Change main.c as the following:
#include "cyhal.h"
#include "cybsp.h"
#include "cy_retarget_io.h"
int main(void)
{
cy_rslt_t result;
result = cybsp_init();
if (result != CY_RSLT_SUCCESS) CY_ASSERT(0);
result = cy_retarget_io_init(P5_1, P5_0, 115200);
if (result != CY_RSLT_SUCCESS) CY_ASSERT(0);
printf("Hello Embedded World \r\n");
result = cyhal_gpio_init(P0_4, CYHAL_GPIO_DIR_INPUT, CYHAL_GPIO_DRIVE_STRONG, 1);
if (result != CY_RSLT_SUCCESS) CY_ASSERT(0);
__enable_irq();
bool btnState = 0;
for (;;)
{
btnState = cyhal_gpio_read(P0_4);
if (!btnState)
{
printf("USER BTN1 Is Pressed \r\n");
}
}(D2) Run RealTerm and select the Port and set Baud as 115200. (Lesson-0 Review)
(D3) Program the board and once you press the USER BTN1 button the "USER BTN1 Is Pressed" will send to the PC and it will keep sending until you release the button.
(D4) Sending the message non-stop isn't OK so change the if condition as follows and the message will send every time you pressed and release the button:
if (btnState != cyhal_gpio_read(P0_4))Some explanation:- cyhal_gpio_init function is used to initialize the GPIO pins. It's defined in cyhal_gpio.h and cyhal_gpio.c other GPIO API such as write and read could be seen in these two files.
- We can alternatively initialize GPIO pins with its macro name:result = cyhal_gpio_init(CYBSP_USER_BTN, CYHAL_GPIO_DIR_INPUT, CYHAL_GPIO_DRIVE_PULLUP, CYBSP_BTN_OFF);
- Pay head that initial value on the pin should be selected in accordance with where the button is active low or active high. For this board the button is active low and if you set init_val = 0, the program won't work. This is why CYBSP_BTN_ON is not defined.





Comments