This is my first program on mbed.org. A Small program for KL25Z that'll act as a Volume Control, thanks to samux for his code with USB keyboard support (https://mbed.org/users/samux/code/USBKeyboard_HelloWorld/) Just added functionality to let the user use the Touch Slider on the KL25Z board to control system volume.

Dependencies:   mbed TSI MMA8451Q USBDevice

Fork of USBKeyboard_HelloWorld by Samuel Mokrani

main.cpp

Committer:
lonczy
Date:
2022-05-17
Revision:
10:2c506aad93de
Parent:
9:0b6c84d01c5d

File content as of revision 10:2c506aad93de:

/**
* A simple app to make Volume Control with the KL25Z onboard Touch Slider
* 
* Simply use the top and bottom part of the slider as buttons.
*
* Green led's intensity is controlled by the slider.
* The Red component of the RGB led is changing intensity as you tilt the board on the X coordinate to have multiple actions at the same time.
*/

#include "mbed.h"
#include "MMA8451Q.h"
#include "USBKeyboard.h"
#include "TSISensor.h"

#define MMA8451_I2C_ADDRESS (0x1d<<1)

int main(void) {
    ///get leds, and set def. values
    PwmOut bled(LED_BLUE);
    bled=0.8;
    PwmOut rled(LED_RED);
    rled=1;
    PwmOut gled(LED_GREEN);
    gled=1;
    ///initializing the accelerometer
    MMA8451Q acc(PTE25, PTE24, MMA8451_I2C_ADDRESS);
    bled=0.6;
    //USB Keyboard interface:
    USBKeyboard keyboard;
    bled=0.4;
    //Touch Slider:
    TSISensor tsi;
    bled=0.2;

    ///switch on blue led
    bled=0.9;
    ///Wait until keyboard is configured
    while (!keyboard.configured()) {
        bled=0.1;
        wait(1);
        bled=0.9;
        wait(1);
    }
    bled=1;

    float current=-1; //< Current state of Slider
    float newRead; //< New readings of the slider

    while (true) {
        newRead=tsi.readPercentage();
        gled=1.0 - newRead;
        /// only if the slider is touched
        if (newRead>0)
            if (current!=newRead) {
                ///and you have a different reading.
                ///this is basically for not letting the volume be changed in every .1 seconds, and keeping the code responsive
                ///you could have a counter on every 10th reading or so.
                current=newRead;
                if (current<0.4)
                    //if touched in the bottom half lower the volume
                    keyboard.mediaControl(KEY_VOLUME_DOWN);
                else
                    if (current<0.6)
                        //if touched in the bottom half lower the volume
                        keyboard.mediaControl(KEY_PLAY_PAUSE);
                    else
                    //if touched in the top half rise the volume
                    keyboard.mediaControl(KEY_VOLUME_UP);
            }
        rled = 1.0 - (abs(acc.getAccX())/2);
        wait(0.1);
    }
}