Button PLAY Click with Clicker 4 for STM32F4

Published Mar 23, 2025

Click board™

Button PLAY Click
LightRanger 3 Click

Dev. board

Clicker 4 for STM32F4

Compiler

NECTO Studio

MCU

STM32F407VGT6

Button-Triggered Distance Measurement Solution

Measure object distance with precision and ease using button-triggered sensing

What you'll learn and build

Intro

The Button-Triggered Distance Measurement Solution integrates Button Play Click and LightRanger 3 Click to enable on-demand distance measurement with interactive visual feedback. Designed for precision sensing, interactive measurement systems, and smart interfaces, this solution captures multiple distance readings at the press of a button, calculates an average for improved accuracy, and logs the results via UART. With a smoothly fading backlight LED that responds to button presses, it provides a user-friendly and intuitive experience for distance sensing applications.

mikroBUS 1

Button PLAY Click

Button PLAY Click is a very interesting interactive gadget on a Click board™. It is an integrated capacitive touch sensor display in the form of a button. By utilizing an advanced capacitive touch sensing technology, the CTHS15CIC05ARROW sensor can successfully replace the traditional mechanical button, allowing very simplified yet reliable user interfaces to be developed. Besides the touch detection, this sensor also features a green arrow icon with backlight, which makes the Click board™ very useful for building various stylized and visually appealing interfaces.

Button PLAY Click front-background image

mikroBUS 2

LightRanger 3 Click

LightRanger 3 Click is an accurate distance measurement Click board™ based on a ToF (Time of Flight) measurement principle. The Simblee™ enabled RFD77402 rangefinder module from RF Digital is a complete measurement stack on the chip. It is surprisingly easy to work with, as this highly integrated range finder module exposes the only I2C interface and INT pin to the host controller. It features the VCSEL, a Vertical Cavity Surface Emitting Laser, used to emit a narrow band of a harmless modulated light beam in the IR range (850 nm), and a receive sensor, which can detect the reflected light. It can measure distances up to 2000mm, with up to 10% accuracy. The device is rated Class 1 LASER product, operating in the IR (invisible) spectrum range.

LightRanger 3 Click front-background image

Features overview

Development board

Clicker 4 for STM32F4 is a compact development board designed for quickly building custom gadgets. It features an STM32F407VGT6 MCU, four mikroBUS™ sockets for Click board™ connectivity, power management, and more—making it ideal for rapid application development. At its core, the STM32F407VGT6 MCU, powered by an Arm® Cortex®-M4 32-bit processor running up to 168 MHz, ensures ample processing power for demanding tasks. Alongside two 1x20 pin headers, its four mikroBUS™ sockets provide access to a vast and growing range of Click boards™. Clearly marked sections offer an intuitive, user-friendly interface for faster development. Clicker 4 not only accelerates prototyping but can also be integrated directly into projects without additional hardware modifications. Four 4.2mm (0.165”) mounting holes at each corner enable easy installation with screws.

Clicker 4 for STM32F4 front image

Microcontroller Overview

MCU Card / MCU

default

Architecture

ARM Cortex-M4

MCU Memory (KB)

10

Silicon Vendor

STMicroelectronics

Pin count

100

RAM (Bytes)

100

Step by step

Project assembly

Clicker 4 for STM32F4 front image hardware assembly

Start by selecting your development board - Clicker 4 for STM32F4

Clicker 4 for STM32F4 front image hardware assembly
LTE IoT 5 Click front-background image hardware assembly
Calypso Click front-background image hardware assembly
Board mapper by product7 hardware assembly
Necto image step 2 hardware assembly
Necto image step 3 hardware assembly
Necto image step 4 hardware assembly
Necto image step 5 hardware assembly
NECTO Output Selection Step Image hardware assembly
Necto image step 6 hardware assembly
Clicker 4 for STM32F4 HA MCU Step hardware assembly
Necto image step 8 hardware assembly
Necto image step 9 hardware assembly
Necto image step 10 hardware assembly
Necto PreFlash Image hardware assembly

Track your results in real time

Application Output

1. Application Output - In Debug mode, the 'Application Output' window enables real-time data monitoring, offering direct insight into execution results. Ensure proper data display by configuring the environment correctly using the provided tutorial.

2. UART Terminal - Use the UART Terminal to monitor data transmission via a USB to UART converter, allowing direct communication between the Click board™ and your development system. Configure the baud rate and other serial settings according to your project's requirements to ensure proper functionality. For step-by-step setup instructions, refer to the provided tutorial.

3. Plot Output - The Plot feature offers a powerful way to visualize real-time sensor data, enabling trend analysis, debugging, and comparison of multiple data points. To set it up correctly, follow the provided tutorial, which includes a step-by-step example of using the Plot feature to display Click board™ readings. To use the Plot feature in your code, use the function: plot(*insert_graph_name*, variable_name);. This is a general format, and it is up to the user to replace 'insert_graph_name' with the actual graph name and 'variable_name' with the parameter to be displayed.

Software Support

Library Description

Button-Triggered Distance Measurement Solution is developed using the NECTO Studio, ensuring compatibility with mikroSDK's open-source libraries and tools. Designed for plug-and-play implementation and testing, this solution is fully compatible with all development, starter, and mikromedia boards featuring a mikroBUS™ socket.

Example Description
The Button-Triggered Distance Measurement Solution integrates the Button Play Click and LightRanger 3 Click to measure object distance upon a button press, providing visual feedback through a smoothly fading backlight. Distance measurements are averaged across multiple readings for enhanced accuracy, with results logged via UART.

Key functions:

  • initialize_button_play - Initializes the Button Play Click, configures PWM for LED backlight control, and starts the PWM signal. Logs an error and halts execution if initialization fails.

  • initialize_light_ranger - Initializes the LightRanger 3 Click and performs sensor setup. Logs an error and halts execution if sensor initialization fails.

  • update_button_backlight - Smoothly fades the button backlight LED in or out, depending on the button state. Brightens the LED when pressed and dims it on release.

  • measure_and_log_distance - Takes a single distance measurement using the LightRanger 3 Click and logs the result via UART.

Application Init
The initialization sequence sets up UART logging, configures both Click boards, and verifies hardware readiness. If an error occurs during initialization, an error message is logged, and execution halts.

Application Task
The main application loop continuously performs the following tasks:

1. Detects button press and triggers distance measurement.

2. Takes multiple distance readings, calculates the average value, and logs it via UART.

3. Smoothly fades the button backlight in on press and out on release.

4. Logs button press/release events and distance measurements.

Open Source

Code example

The complete application code and a ready-to-use project are available through the NECTO Studio Package Manager for direct installation in the NECTO Studio. The application code can also be found on the MIKROE GitHub account.

/*
 * Solution Name: Button-Triggered Distance Measurement Solution
 *
 * Description:
 * This embedded application uses Button Play Click and LightRanger 3
 * Click to measure the distance to an object when a button is pressed.
 * The button's backlight gradually fades in on press and fades out on release,
 * providing visual feedback. Distance measurements are averaged over multiple
 * readings to mitigate sensor noise and improve accuracy.
 *
 * The system utilizes the following Click boards:
 *   - Button Play Click: Captures button press/release events and controls
 *     LED backlight.
 *   - LightRanger 3 Click: Measures the distance to a nearby object using
 *     a laser sensor.
 *
 * The `application_init` function initializes the logger and both Click boards,
 * ensuring proper startup conditions. Any initialization failure is logged,
 * and the system halts.
 *
 * The `application_task` function monitors the button state and triggers
 * distance measurements when the button is pressed. It takes multiple readings,
 * calculates the average distance, and logs the result via UART.
 *
 * Hardware Setup:
 *   - MIKROBUS_1: Button Play Click
 *   - MIKROBUS_2: LightRanger 3 Click
 *
 * Key Features:
 *   - Button-controlled distance measurement with backlight feedback.
 *   - Multi-sample averaging to reduce sensor reading noise.
 *   - Smooth LED fade-in/out on button press/release.
 *   - UART logging for measurement data and system events.
 *
 * Development Environment:
 *   - [NECTO Studio](https://www.mikroe.com/necto)
 *   - [mikroSDK v2.0](https://www.mikroe.com/mikrosdk) framework
 *   - MIKROE [Click boards](https://www.mikroe.com/click-boards) Add-ons
 *
 * Author: Branko Jaksic
 * Date: 2025
 */

// ------------------------------------------------------------------- INCLUDES
#include "log.h"
#include "board.h"
#include "buttonplay.h"
#include "lightranger3.h"

// ------------------------------------------------------------------ VARIABLES
static buttonplay_t buttonplay;
static lightranger3_t lightranger3;
static log_t logger;

// ----------------------------------------------- PUBLIC FUNCTION DECLARATIONS

/**
 * @brief Initializes the Button Play Click board.
 *
 * Configures the Button Play Click board, sets up the PWM for LED
 * backlight control, and starts the PWM signal. If initialization fails,
 * the function logs an error and halts execution.
 *
 * @note The Button Play Click is connected to MIKROBUS_1.
 */
void initialize_button_play( void );

/**
 * @brief Initializes the LightRanger 3 Click board.
 *
 * Configures the LightRanger 3 Click board and performs device initialization. 
 * If the sensor fails to initialize, the function logs an error and halts
 * execution.
 *
 * @note The LightRanger 3 Click is connected to MIKROBUS_2.
 */
void initialize_light_ranger( void );

/**
 * @brief Updates the button backlight brightness.
 *
 * Smoothly fades the button's backlight LED in or out, depending on the
 * button state. When the button is pressed, the backlight gradually brightens.
 * When released, the backlight gradually dims.
 *
 * @param[in] is_pressed  Boolean indicating the button state:
 *                        - `true`: Fade in the backlight.
 *                        - `false`: Fade out the backlight.
 */
void update_button_backlight( bool is_pressed );

/**
 * @brief Measures and logs the distance using the LightRanger 3 Click.
 *
 * Takes a single distance measurement, retrieves the distance value,
 * and logs it via UART. This function is useful for quick,
 * real-time distance readings.
 */
void measure_and_log_distance( void );

// ------------------------------------------------------ APPLICATION FUNCTIONS
void application_init( void ) 
{
    log_cfg_t log_cfg;

    // Logger initialization
    LOG_MAP_USB_UART( log_cfg );
    log_init( &logger, &log_cfg );
    log_info( &logger, "Application Init" );

    initialize_button_play();
    initialize_light_ranger();

    log_info( &logger, "Initialization Complete, Starting Application Task" );
}

void initialize_button_play( void )
{
    buttonplay_cfg_t buttonplay_cfg;

    buttonplay_cfg_setup( &buttonplay_cfg );
    BUTTONPLAY_MAP_MIKROBUS( buttonplay_cfg, MIKROBUS_1 );

    if ( buttonplay_init( &buttonplay, &buttonplay_cfg ) == PWM_ERROR ) 
    {
        log_error( &logger, "Button Play Click initialization failed!" );
        for ( ; ; );  // Halt execution
    }

    buttonplay_set_duty_cycle( &buttonplay, 0.0 );
    buttonplay_pwm_start( &buttonplay );
    log_info( &logger, "Button Play Click initialized successfully." );
}

void initialize_light_ranger( void )
{
    lightranger3_cfg_t lightranger3_cfg;

    lightranger3_cfg_setup( &lightranger3_cfg );
    LIGHTRANGER3_MAP_MIKROBUS( lightranger3_cfg, MIKROBUS_2 );
    lightranger3_init( &lightranger3, &lightranger3_cfg );

    if ( lightranger3_device_init( &lightranger3 ) != 0 ) 
    {
        log_error( &logger, "LightRanger Click initialization failed!" );
        for ( ; ; );  // Halt execution
    }

    log_info( &logger, "LightRanger Click initialized successfully." );
}

void application_task( void ) 
{
    static uint8_t button_state_old = 0;
    uint8_t button_state = buttonplay_get_button_state( &buttonplay );

    if ( button_state != button_state_old ) 
    {
        if ( button_state ) 
        {
            log_printf( &logger, " <-- Button Pressed --> \r\n" );
            update_button_backlight( true );

            // Measure distance multiple times and calculate the mean value
            uint32_t distance_sum = 0;
            uint8_t num_measurements = 5;

            for ( uint8_t i = 0; i < num_measurements; i++ ) 
            {
                lightranger3_take_single_measurement( &lightranger3 );
                distance_sum += lightranger3_get_distance( &lightranger3 );
                Delay_ms( 100 ); // Small delay between measurements
            }

            uint16_t average_distance = ( uint16_t )( distance_sum / num_measurements );
            log_printf( &logger, "Average Distance: %u mm\r\n", average_distance );
        } 
        else 
        {
            log_printf( &logger, " <-- Button Released --> \r\n" );
            update_button_backlight( false );
        }

        button_state_old = button_state;
    }
}

void update_button_backlight( bool is_pressed )
{
    float duty_cycle;

    if ( is_pressed ) 
    {
        for ( uint8_t n = 1; n <= 100; n++ ) 
        {
            buttonplay_set_duty_cycle( &buttonplay, (float)n / 100 );
            Delay_ms( 10 );
        }
    } 
    else 
    {
        for ( uint8_t n = 100; n > 0; n-- ) 
        {
            buttonplay_set_duty_cycle( &buttonplay, (float)n / 100 );
            Delay_ms( 10 );
        }
    }
}

void measure_and_log_distance( void )
{
    lightranger3_take_single_measurement( &lightranger3 );
    uint16_t distance = lightranger3_get_distance( &lightranger3 );

    log_printf( &logger, "Distance: %u mm\r\n", distance );
}

int main( void ) 
{
    #ifdef PREINIT_SUPPORTED
    preinit();
    #endif

    application_init();

    while ( 1 ) 
    {
        application_task();
    }

    return 0;
}

Additional Support

Resources

Love this project?

'Buy This Kit' button takes you directly to the shopping cart where you can easily add or remove products.