// main.cpp
#include "mbed.h"

#define MAXIMUM_BUFFER_SIZE 32

PwmOut led_pwm(LED1);
DigitalIn  button(PC_13);

static BufferedSerial serial_port(USBTX, USBRX);

int press_duty(int num_presses) {
    if (num_presses > 10) {
        num_presses = 0;
    }
    num_presses += 1;

    return num_presses;
}

int main()
{
    serial_port.set_baud(9600);
    serial_port.set_format(
        /* bits */ 8,
        /* parity */ BufferedSerial::None,
        /* stop bit */ 1
    );

    char buf[MAXIMUM_BUFFER_SIZE] = {0};
    char msg[64];

    int num_presses = 1;
    float strieda = 0.0f;
    led_pwm.period(0.02f);
    led_pwm.write(0.50f);
    while (1) {
        float strieda = 0;

        if (uint32_t num = serial_port.read(buf, sizeof(buf))) {
          strieda = press_duty(num_presses)/10.0;
          led_pwm.write(strieda);
          int len = snprintf(msg, sizeof(msg), "strieda = %.3f\r\n", strieda);
          // serial_port.write(buf, len);

          // Echo the input back to the terminal.
          serial_port.write(buf, strieda);

          num_presses = press_duty(num_presses);
          while (num == 0) {
            ThisThread::sleep_for(10ms);
          }
        }

        ThisThread::sleep_for(150ms);
    }
}
