TouchGFX automatically generates GUI C++ code for STM32 based applications that use a display and touch screen. Here is a demonstration on how to attach a C function callback to a TouchGFX entity (a button).
When a button is clicked, a C function in a custom C file has to be called. Here is how.
Create a Default TouchGFX Page and Button
- Create a new project (we call this one MyApplication_1) and select a Discovery or similar STM32 display-capable kit.
- A blank TouchGFX screen is created by default (note that the default name is Screen1, this will be relevant later).
- Drag and drop a button, in this case, a toggle button named ToggleButton1.
Add a Custom Click Event to Toggle Button
- Select the ToggleButton1 object
- On the Interactions tab, add Interaction1 with the following properties
- When ToggleButton1 is clicked, the virtual function called btn1_pressed_vfn is called by the TouchGFX core.
Create Target Callback C Code
When ToggleButton1 is clicked, the goal is to execute a C function placed in a custom C file. The C file is placed in the application code folder (Code/Src).
- Create a source file gfx_callbacks.c in MyApplication_1\Core\Src with the following function. This function will be called when ToggleButton1 is clicked.
// File: gfx_callbacks.c
#include "main.h"
#include "gfx_callbacks.h"
void btn11_pressed_callback (void)
{
static uint8_t btn1_ctr = 0;
btn1_ctr++;
}
- Create a header file gfx_callbacks.h in MyApplication_1\Core\Inc with the following content.
// File: gfx_callbacks.h
#ifndef _GFX_CALLBACKS_H_
#define _GFX_CALLBACKS_H_
void btn11_pressed_callback (void);
#endif
Attach TouchGFX Button Callback with C Code
The generated TouchGFX code that you can modify is placed in Application/User/gui in the CubeIDE project explorer.
- Open Screen1View.cpp
- Add your custom definition of button click event. In this case, we simply call our callback C code in gfx_callbacks.c
- Add a declaration of btn1_pressed_vfn in Screen1View.hpp
C Callback is Triggered when Toggle Button is Clicked
- When you build and run this application, a blank screen with the toggle button appears on the Discovery Kit display.
- Clicking the button calls ScreenView::btn1_pressed_vfn() in Screen1View.cpp.
- This function, in turn, calls btn1_pressed_callback() in our custom C file called gfx_callbacks.c.
Have Something to Say?
Feel free to ask away via the Quick Contact form in the sidebar, or leave a comment below.
Feel free to ask away via the Quick Contact form in the sidebar, or leave a comment below.
Change Log
- Initial Release: 23 December 2021
References
- Reference 1: TouchGFX Tutorial 2
- Reference 2: Calling C functions from C++ code