/*
 * main.c
 *
 *  Created on: Aug 2, 2016
 *      Author: tkl
 */

#include <stdbool.h>
#include <string.h>
#include <stdio.h>

#include "driver.h"
#include "board.h"
#include "stack.h"
#include "queue.h"
#include "kernel.h"
#include "driver.h"
#include "list.h"
#include "shell.h"

int main(void)
{
	char print_buffer[80];

	drv_open(&pwm_1);
	drv_open(&pwm_2);
	drv_open(&pwm_3);
	drv_open(&pwm_4);

	drv_open(&pwm5_c2);
	drv_open(&pwm2_c4);

	drv_open(&uart_1);

	while(1) {
		for(unsigned int duty = 0; duty < 100; duty++) {
			drv_ioctl(&pwm_1, IOCTL_PWM_SET_DUTY_CYCLE, (const void *)&duty);
			drv_ioctl(&pwm_2, IOCTL_PWM_SET_DUTY_CYCLE, (const void *)&duty);
			drv_ioctl(&pwm_3, IOCTL_PWM_SET_DUTY_CYCLE, (const void *)&duty);
			drv_ioctl(&pwm_4, IOCTL_PWM_SET_DUTY_CYCLE, (const void *)&duty);
			sleep_ms(100);

			int pulse = drv_ioctl(&pwm2_c4, IOCTL_PWM_GET_PULSE_WIDTH_NS, NULL);
			int period = drv_ioctl(&pwm2_c4, IOCTL_PWM_GET_PERIOD_NS, NULL);
			int frq = 1000000 / period;
			sprintf(print_buffer, "Frequency: %dHz\r\n", frq);
			drv_write(&uart_1, print_buffer, strlen(print_buffer));

			int dist = 343 * pulse / 1000 / 2;
			sprintf(print_buffer, "distance: %d mm\r\n", dist);
			drv_write(&uart_1, print_buffer, strlen(print_buffer));
		}
		for(unsigned int duty = 98; duty > 0; duty--) {
			drv_ioctl(&pwm_1, IOCTL_PWM_SET_DUTY_CYCLE, (const void *)&duty);
			drv_ioctl(&pwm_2, IOCTL_PWM_SET_DUTY_CYCLE, (const void *)&duty);
			drv_ioctl(&pwm_3, IOCTL_PWM_SET_DUTY_CYCLE, (const void *)&duty);
			drv_ioctl(&pwm_4, IOCTL_PWM_SET_DUTY_CYCLE, (const void *)&duty);
			sleep_ms(100);

			int pulse = drv_ioctl(&pwm2_c4, IOCTL_PWM_GET_PULSE_WIDTH_NS, NULL);
			int period = drv_ioctl(&pwm2_c4, IOCTL_PWM_GET_PERIOD_NS, NULL);
			int frq = 1000000 / period;
			sprintf(print_buffer, "Frequency: %dHz\r\n", frq);
			drv_write(&uart_1, print_buffer, strlen(print_buffer));

			int dist = 343 * pulse / 1000 / 2;
			sprintf(print_buffer, "distance: %d mm\r\n", dist);
			drv_write(&uart_1, print_buffer, strlen(print_buffer));
		}
	}

	return 0;
}
