/*
 * pwmUtil.c
 *
 *  Created on: Oct 10, 2018
 *      Author: robert.applebee
 */

// includes
#include <stdint.h>
#include <stdbool.h>
#include "driverlib/sysctl.h"
#include "driverlib/pwm.h"
#include "inc/hw_memmap.h"
#include "pwmUtil.h"

void PWM_init(void)
{
    //
    // Enable the PWM0 module.
    //
    SysCtlPeripheralEnable(SYSCTL_PERIPH_PWM0);

    //
    // Wait for the PWM0 module to be ready.
    //
    while(!SysCtlPeripheralReady(SYSCTL_PERIPH_PWM0)) { }

    //
    // Configure the PWM generator for count down mode with immediate updates
    // to the parameters.
    //
    PWMGenConfigure(PWM0_BASE, PWM_GEN_0, PWM_GEN_MODE_DOWN | PWM_GEN_MODE_NO_SYNC);

    //
    // set the clock
    //
//    PWMClockSet(PWM0_BASE,  PWM_SYSCLK_DIV_64);

    //
    // Set the period. For a 100 KHz frequency, the period = 1/100,000, or 10
    // microseconds. For a 120 MHz clock, this translates to 600 clock ticks.
    // Use this value to set the period.
    //
    PWMGenPeriodSet(PWM0_BASE, PWM_GEN_0, 4096);

    //
    // Set the pulse width of PWM0 for a 0% duty cycle.
    //
    PWMPulseWidthSet(PWM0_BASE, PWM_OUT_0, 1);

    //
    // Set the pulse width of PWM1 for a 0% duty cycle.
    //
    PWMPulseWidthSet(PWM0_BASE, PWM_OUT_1, 1);

    //
    // Start the timers in generator 0.
    //
    PWMGenEnable(PWM0_BASE, PWM_GEN_0);

    //
    // Enable the outputs.
    //
    PWMOutputState(PWM0_BASE, (PWM_OUT_0_BIT | PWM_OUT_1_BIT), true);
}

void PWM_set(int channel, int count)
{

    // TMC129X PWM sets the output high if the pulse width is 0
    if (count == 0)
        count = 1;

    if (channel == 16) {
        // Set the pulse width of PWM0.
        PWMPulseWidthSet(PWM0_BASE, PWM_OUT_0, count);
    } else {
        // Set the pulse width of PWM1.
        PWMPulseWidthSet(PWM0_BASE, PWM_OUT_1, count);
    }




}


