#include <rtthread.h>
#include "board.h"
#include "motor.h"

//extern float Roll;

struct rt_device_pwm *pwm_dev; /* PWM设备句柄 */
ALIGN(RT_ALIGN_SIZE)
static uint8_t PWM_Thread_Stack[1024];
static void PWM_Thread_Entry(void *para);
static struct rt_thread pwm_thread;
rt_uint32_t period, pulse;
void Pwm_Init(void){
    period = 100000; /* 周期 = 1M/period kHz */
    pulse = 0; /* PWM脉冲宽度值(0 - period) */
    pwm_dev = (struct rt_device_pwm *)rt_device_find(PWM_DEV_NAME);
    RT_ASSERT(pwm_dev != RT_NULL);
    /* 设置PWM周期和脉冲宽度 */
    rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL, period, pulse);
    /* 使能设备 */
    rt_pwm_enable(pwm_dev, PWM_DEV_CHANNEL);
}

int Pwm_Thread_Init(void){
    rt_thread_init(&pwm_thread, "pwm_thread_motor", PWM_Thread_Entry, RT_NULL,
    &PWM_Thread_Stack[0], sizeof(PWM_Thread_Stack), 10, 10);
    rt_thread_startup(&pwm_thread);
    return 0;
}

//INIT_APP_EXPORT(Pwm_Thread_Init);

static void PWM_Thread_Entry(void *para){


 /*   while(1){
        output = (int)(Roll-90)*500;
        if(output<0){
            output=-output;
            rt_pin_write(dir1, PIN_HIGH);
        }else{
            rt_pin_write(dir1, PIN_LOW);
        }
        if(output>10000)output=10000;
        rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL, period, output);

    }*/

/*    while(1){
        使RGB灯红灯闪烁
        for (int var = 0; var < period; var += 10000) {
            rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL, period, var);
            rt_thread_mdelay(10);
        }
        for (int var = period; var >0; var -= 10000) {
            rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL, period, var);
            rt_thread_mdelay(10);
        }
    }*/
}
