Rotary Switch Click with Clicker 4 for STM32F4

Published Apr 16, 2025

Click board™

Rotary Switch Click
Speaker 2 Click

Dev. board

Clicker 4 for STM32F4

Compiler

NECTO Studio

MCU

STM32F407VGT6

Switch-Triggered Voice Playback Solution

Enable audible feedback and intuitive navigation with a rotary-driven voice playback system

What you'll learn and build

Intro

The Switch-Triggered Voice Playback solution integrates Rotary Switch Click and Speaker 2 Click to deliver an intuitive, zone-based audio feedback system. Designed for menu navigation, industrial control panels, user interfaces, and accessibility applications, this solution maps rotary encoder positions to predefined voice prompts, enabling users to receive audible cues as they rotate the switch. By continuously monitoring switch position and playing corresponding audio files in real time, it offers a highly responsive and user-friendly interface for systems requiring hands-on, audible interaction.

mikroBUS 1

Rotary Switch Click

Rotary Switch Click is a compact add-on board for applications requiring precise rotary input. This board is based on the RDS6-16S-1065-1-SMT, a 16-position notched cap surface-mount rotary DIP switch from Same Sky. This switch features continuous 360-degree actuator rotation, a 2.54mm pin pitch, and robust construction with a contact resistance of 80mΩ and a maximum operating torque of 700gf*cm, ensuring reliable operation for up to 10,000 steps. The board supports the innovative Click Snap feature, allowing the rotary switch to operate autonomously when detached, providing flexibility in various implementations. It connects to the host MCU via the TCA9536, a 4-bit I2C I/O expander from Texas Instruments, simplifying switch state monitoring. Ideal for industrial equipment, consumer electronics, and automotive systems, Rotary Switch Click offers a versatile and durable solution for mode selection and user-configurable settings in demanding environments.

Rotary Switch Click front-background image

mikroBUS 2

Speaker 2 Click

Speaker 2 Click is a compact add-on board for high-quality audio playback and voice prompt applications. This board features the ISD2360, a 3-channel digital ChipCorder® from Nuvoton, which integrates flash memory for non-volatile audio storage and playback. The ISD2360 supports up to 64 seconds of audio storage with digital decompression, independent multi-channel playback, and a Class D speaker driver for driving the onboard AS01508AO-SC-R speaker. It features a standard SPI interface, configurable I/O pins, and built-in program verification, ensuring reliable operation with minimal external components. The board also includes selectable logic voltage levels (3.3V or 5V) and a jumper for independent digital power selection. Speaker 2 Click is ideal for embedded applications requiring clear voice prompts, sound effects, or pre-recorded messages, making it suitable for automation systems, consumer electronics, and industrial devices.

Speaker 2 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

Switch-Triggered Voice Playback 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 Switch-Triggered Voice Playback solution integrates Rotary Switch Click and Speaker 2 Click to create a system that dynamically plays pre-recorded voice prompts depending on the user's switch position. The Rotary Switch Click reads rotary encoder values and maps the current position to a logical voice zone. Each zone corresponds to a distinct voice file stored on the Speaker 2 Click, which plays the associated audio when the user enters a new zone. This solution is ideal for menu navigation systems, industrial panels, user interfaces, and accessibility aids where audible feedback is required for switch-based input.

Key functions:

  • rotaryswitch_init - Initializes the Rotary Switch Click for reading the encoder position.

  • rotaryswitch_default_cfg - Applies default configuration for stable switch readings.

  • rotaryswitch_get_position - Reads the current rotary position (0–255) from the switch.

  • speaker2_init - Initializes the Speaker 2 Click for audio playback.

  • speaker2_default_cfg - Configures default settings for voice file playback.

  • speaker2_play_voice - Plays a predefined voice prompt associated with the current switch zone.

  • log_printf - Logs rotary switch zone and voice playback status via UART for debugging and tracking.

Application Init
The UART logger is initialized for real-time feedback. The Rotary Switch Click is initialized and configured to provide position readings from 0–255. The Speaker 2 Click is initialized to support voice playback of multiple pre-recorded prompts. If any peripheral fails to initialize, the system logs the error and enters a safe halt state.

Application Task
The main application task operates in a continuous loop, periodically reading the current position of the rotary switch. Based on the rotary input value (ranging from 0 to 255), it calculates the corresponding voice zone by dividing the range into seven equal segments. It then checks whether the detected zone differs from the previously stored zone value. If the user has rotated into a new zone, the system logs both the current rotary position and the active zone over UART, then initiates playback of the appropriate voice prompt using the Speaker 2 Click board. Following the playback attempt, it logs whether the command was successfully executed. This cycle repeats every 20 milliseconds, maintaining a highly responsive and real-time application behavior.

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: Switch-Triggered Voice Playback Solution
 *
 * Description:
 * This embedded application maps rotary switch positions to pre-defined 
 * voice prompts using the Rotary Switch Click and Speaker 2 Click boards. 
 * As the user rotates the switch, the system dynamically triggers playback 
 * of corresponding voice files via the onboard speaker.
 *
 * The system utilizes the following Click boards:
 *   - Rotary Switch Click: A 256-position rotary encoder used to determine 
 *     the current user-selected value or range.
 *   - Speaker 2 Click: Plays pre-recorded voice prompts based on the selected 
 *     rotary switch position.
 *
 * The `application_init` function initializes both Click boards and sets up 
 * the UART logger for status tracking and debugging.
 *
 * The `application_task` function continuously reads the rotary switch 
 * position and maps it to one of seven logical zones using configurable 
 * macro definitions. Each zone is assigned to a specific voice file, played 
 * back via Speaker 2 Click. The mapping ensures flexibility and clean logic 
 * through macros like `ROTARY_SWITCH_MAX_RANGE`, `SPEAKER_2_NUM_SOUNDS`, 
 * and `SPEAKER_2_ZONE_WIDTH`.
 *
 * Hardware Setup:
 *   - MIKROBUS_1: Rotary Switch Click (Rotary input)
 *   - MIKROBUS_2: Speaker 2 Click (Voice playback)
 *
 * Key Features:
 *   - Rotary position-to-voice mapping via modular macros
 *   - Configurable number of voice zones and resolution
 *   - Dynamic playback of pre-recorded voice prompts
 *   - UART-based logging for rotary position and playback status
 *
 * 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: April, 2025
 */

// ------------------------------------------------------------------- INCLUDES
#include "log.h"
#include "board.h"
#include "speaker2.h"
#include "rotaryswitch.h"

// ------------------------------------------------------------- PRIVATE MACROS
#define ROTARY_SWITCH_MAX_RANGE 256
#define SPEAKER_2_NUM_SOUNDS    7
#define SPEAKER_2_ZONE_WIDTH ( ROTARY_SWITCH_MAX_RANGE / SPEAKER_2_NUM_SOUNDS )

// ------------------------------------------------------------------ VARIABLES
static log_t logger;
static speaker2_t speaker2;
static rotaryswitch_t rotaryswitch;

// ----------------------------------------------------- USER-DEFINED CONSTANTS
static const uint16_t speaker2_voice_map[SPEAKER_2_NUM_SOUNDS] = {
    SPEAKER2_VP9_ONE,
    SPEAKER2_VP10_TWO,
    SPEAKER2_VP11_THREE,
    SPEAKER2_VP12_FOUR,
    SPEAKER2_VP13_FIVE,
    SPEAKER2_VP14_SIX,
    SPEAKER2_VP15_FAST_BEEP
};

// ------------------------------------------------------ APPLICATION FUNCTIONS
void application_init ( void )
{
    log_cfg_t log_cfg;  /**< Logger config object. */
    speaker2_cfg_t speaker2_cfg;  /**< Click config object. */
    rotaryswitch_cfg_t rotaryswitch_cfg;  /**< Click config object. */

    /** 
     * Logger initialization.
     * Default baud rate: 115200
     * Default log level: LOG_LEVEL_DEBUG
     * @note If USB_UART_RX and USB_UART_TX 
     * are defined as HAL_PIN_NC, you will 
     * need to define them manually for log to work. 
     * See @b LOG_MAP_USB_UART macro definition for detailed explanation.
     */
    LOG_MAP_USB_UART( log_cfg );
    log_init( &logger, &log_cfg );
    log_info( &logger, " Application Init " );

    // Click initialization.
    rotaryswitch_cfg_setup( &rotaryswitch_cfg );
    ROTARYSWITCH_MAP_MIKROBUS( rotaryswitch_cfg, MIKROBUS_1 );
    if ( I2C_MASTER_ERROR == rotaryswitch_init( &rotaryswitch,
                                                &rotaryswitch_cfg ) ) 
    {
        log_error( &logger, " Communication init." );
        for ( ; ; );
    }

    if ( ROTARYSWITCH_ERROR == rotaryswitch_default_cfg ( &rotaryswitch ) )
    {
        log_error( &logger, " Default configuration." );
        for ( ; ; );
    }

    // Click initialization.
    speaker2_cfg_setup( &speaker2_cfg );
    SPEAKER2_MAP_MIKROBUS( speaker2_cfg, MIKROBUS_2 );
    if ( SPI_MASTER_ERROR == speaker2_init( &speaker2, &speaker2_cfg ) )
    {
        log_error( &logger, " Communication init." );
        for ( ; ; );
    }

    if ( SPEAKER2_ERROR == speaker2_default_cfg ( &speaker2 ) )
    {
        log_error( &logger, " Default configuration." );
        for ( ; ; );
    }

    log_info( &logger, " Application Task " );
}

void application_task ( void )
{
    static uint8_t prev_rotary_position = 0xFF; // Initially invalid
    uint8_t rotary_position = 0;

    if ( ROTARYSWITCH_OK == rotaryswitch_get_position( &rotaryswitch,
                                                       &rotary_position ) )
    {
        uint8_t current_zone = rotary_position / SPEAKER_2_ZONE_WIDTH;
        if ( current_zone >= SPEAKER_2_NUM_SOUNDS )
        {
            current_zone = SPEAKER_2_NUM_SOUNDS - 1;
        }

        // Calculate current zone boundaries
        uint8_t zone_min = current_zone * SPEAKER_2_ZONE_WIDTH;
        uint8_t zone_max = ( ( current_zone + 1 ) * SPEAKER_2_ZONE_WIDTH ) - 1;
        if ( current_zone == SPEAKER_2_NUM_SOUNDS - 1 )
        {
            zone_max = ROTARY_SWITCH_MAX_RANGE - 1;
        }

        // Check if rotary moved into a NEW range (new zone boundaries)
        if ( ( rotary_position >= zone_min && rotary_position <= zone_max ) &&
             !( prev_rotary_position >= zone_min &&
                prev_rotary_position <= zone_max ) )
        {
            prev_rotary_position = rotary_position;

            log_printf( &logger, " Rotary position: %u -> Zone %u (%u - %u)\r\n", 
                        rotary_position, current_zone, zone_min, zone_max );

            if ( SPEAKER2_OK == speaker2_play_voice( &speaker2,
                                                     speaker2_voice_map[ current_zone ] ) )
            {
                log_printf( &logger, " Voice played: %u\r\n\n", current_zone );
            }
            else
            {
                log_error( &logger,
                           " Failed to play voice for zone %u\r\n\n",
                           current_zone );
            }
        }
    }

    Delay_ms( 20 );
}

int main ( void ) 
{
    /* Do not remove this line or clock might not be set correctly. */
    #ifdef PREINIT_SUPPORTED
    preinit();
    #endif

    application_init( );

    for ( ; ; ) 
    {
        application_task( );
    }

    return 0;
}

// ------------------------------------------------------------------------ END

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.