Test script for PwmOut control LED with buttons

Dependencies:   mbed

main.cpp

Committer:
rubenlucas
Date:
2018-09-26
Revision:
0:2ba57c4723ea
Child:
1:9654405c52f4

File content as of revision 0:2ba57c4723ea:

#include "mbed.h"
#include "math.h"

PwmOut Led(D3);
InterruptIn Brighter(D1);
InterruptIn Dimmer(D0);
Ticker checkTicker;

volatile float DutyCycle = 0.2; // set start cycle percentage of 20% (this is free of choice)
volatile float Percentage;

void BrighterFcn()
{
    if (DutyCycle == 1.0) // check if duty cycle is already at max
    {return;}
    else 
    {DutyCycle = DutyCycle + 0.025;} // raise duty cycle with 2.5%
}

void DimmerFcn()
{
    if (DutyCycle == 0.0) // check if duty cycle is already at minimum
    {return;}
    else 
    {DutyCycle = DutyCycle - 0.025;}  // lower duty cycle with 2.5%
}

void CheckDutyCycle()
{
    Percentage = DutyCycle;
}

int main()
{
    float frequency = 10000; // 10 kHz
    Led.period(1/frequency); // set fixed period
    Brighter.rise(&BrighterFcn); //call function to raise dutycycle percentage if button is pressed and released
    Dimmer.rise(&DimmerFcn); //call function to lower dutycycle percentage if button is pressed and released
    checkTicker.attach(&CheckDutyCycle, 0.05); // call for percentage with 20 Hz to make the working smoother
    
        while (true) 
        {
        Led.write(Percentage);
        wait(0.1f);
        }
}