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

#define MAXIMUM_BUFFER_SIZE 32

DigitalOut led1(LED1);
DigitalOut led2(LED2);
DigitalOut led3(LED3);
DigitalIn  button(PC_13);

static BufferedSerial serial_port(USBTX, USBRX);

int another_press(int press_num) {
    press_num += 1;
    if (press_num >= 8) {
        press_num = 0;
    };

    return press_num;
}

void set_led(int number) {
    led1 = (number & 1) ? 1 : 0;
    led2 = (number & 2) ? 1 : 0;
    led3 = (number & 4) ? 1 : 0;
}

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};

    int num_presses = 0;
    while (1) {
        led1 = 0;
        led2 = 0;
        led3 = 0;

        if (uint32_t num = serial_port.read(buf, sizeof(buf))) {
          num_presses = another_press(num_presses);
          set_led(num_presses);

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

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

        }

        ThisThread::sleep_for(150ms);
    }
}
