/*
 * Copyright (c) 2015, Texas Instruments Incorporated
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * *  Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * *  Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * *  Neither the name of Texas Instruments Incorporated nor the names of
 *    its contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 *    ======== i2crf430cl330_load.c ========
 */

/* XDCtools Header files */
#include <xdc/std.h>
#include <xdc/runtime/Error.h>
#include <xdc/runtime/System.h>

/* BIOS Header files */
#include <ti/sysbios/BIOS.h>
#include <ti/sysbios/knl/Task.h>
#include <ti/sysbios/knl/Semaphore.h>
#include <ti/sysbios/utils/Load.h>

/* TI-RTOS Header files */
#include <ti/drivers/GPIO.h>
#include <ti/drivers/I2C.h>

#include <inc/hw_memmap.h>
#include <driverlib/gpio.h>
#include <driverlib/i2c.h>
#include "driverlib/sysctl.h"


/* Example/Board Header files */
#include "Board.h"

#include <stdio.h>
#include <stdlib.h>

#define PWMR_MGMT           0x6B
#define MPU6050_I2C_ADDRESS 0x68
#define MPU6050_I2C_BASE I2C3_BASE

#define TASKSTACKSIZE       768


Task_Struct task0Struct;
Char task0Stack[TASKSTACKSIZE];



struct MPU6050
{
    uint8_t AccelXH;
    uint8_t AccelXL;
    uint8_t AccelYH;
    uint8_t AccelYL;
    uint8_t AccelZH;
    uint8_t AccelZL;
    uint8_t TempH;
    uint8_t TempL;
    uint8_t GyroXH;
    uint8_t GyroXL;
    uint8_t GyroYH;
    uint8_t GyroYL;
    uint8_t GyroZH;
    uint8_t GyroZL;
} mpu6050;

void writeRegister(I2C_Handle handle, uint16_t regAddr, uint16_t value)
{
    uint8_t             txBuffer[4];
    I2C_Transaction     i2cTransaction;

    i2cTransaction.slaveAddress = MPU6050_I2C_ADDRESS;

    /* Write to a 16-bit status register */
    i2cTransaction.writeBuf = txBuffer;
    i2cTransaction.writeCount = 4;
    i2cTransaction.readCount = 0;

    txBuffer[0] = regAddr >> 8;   //HB Addr
    txBuffer[1] = regAddr & 0xFF; //LB Addr
    txBuffer[2] = value   & 0xFF;
    txBuffer[3] = value   >> 8;

    if (!I2C_transfer(handle, &i2cTransaction)) {
        GPIO_write(Board_LED2, Board_LED_ON);
        System_abort("Bad I2C transfer!");
    }
}

void readRegister(I2C_Handle handle,
                  uint16_t regAddr,
                  uint8_t *data,
                  size_t   length)
{
    uint8_t             txBuffer[2];
    I2C_Transaction     i2cTransaction;

    i2cTransaction.slaveAddress = MPU6050_I2C_ADDRESS;

    /* Write to a 16-bit status register */
    i2cTransaction.writeBuf = txBuffer;
    i2cTransaction.readBuf = data;
    i2cTransaction.writeCount = 2;
    i2cTransaction.readCount = length;

    txBuffer[0] = regAddr >> 8;   //HB Addr
    txBuffer[1] = regAddr & 0xFF; //LB Addr

    if (!I2C_transfer(handle, &i2cTransaction)) {
        GPIO_write(Board_LED2, Board_LED_ON);
        System_abort("Bad I2C transfer!");
    }
}

/*
 *  ======== taskFxn ========
 *  Task for this function is created statically. See the project's .cfg file.
 */
Void imuTask(UArg arg0, UArg arg1)
{
    I2C_Handle i2c;
    I2C_Params i2cParams;
    unsigned int i;
    uint8_t  pwr;
    pwr = 0x00;

    /* Create I2C for usage */
    I2C_Params_init(&i2cParams);
    i2cParams.bitRate = I2C_100kHz;
    i2c = I2C_open(Board_I2C_NFC, &i2cParams);
    if (i2c == NULL)
    {
        System_abort("Error Initializing I2C\n");
    }
    else
    {
        System_printf("I2C Initialized!\n");
    }
    // Initialize the MPU6050
    writeRegister(i2c,0x6B, 0x80);
    readRegister(i2c, 0x6B, &pwr, 1);
    do {
        readRegister(i2c, 0x6B, &pwr, 1);
    } while (pwr & 0x40 != 0x40);

    // Use PLL with X axis gyroscope reference
    writeRegister(i2c,0x6B, 0x01);
    // Enable I2C Master mode
    writeRegister(i2c,0x6A, 0x20);
    // Set sample rate divider
    writeRegister(i2c,0x19, 0x13);
    writeRegister(i2c,0x67, 0x11);

    GPIO_write(Board_LED0, Board_LED_OFF);

   while(1)
    {
        while (GPIOPinRead(GPIO_PORTB_BASE, GPIO_PIN_2) == GPIO_PIN_2);
        //readRegister(i2c, 0x3B, (uint8_t *)&mpu6050, 14);
        readRegister(i2c, 0x3B, (uint8_t *) &mpu6050, 14);
    }

    /* Deinitialized I2C */
    I2C_close(i2c);
    System_printf("I2C closed!\n");
    System_flush();

}


/*
 *  ======== main ========
 */
int main(void)
{
    Task_Params taskParams;

    /* Call board init functions */
    Board_initGeneral();
    Board_initGPIO();
    Board_initI2C();

    SysCtlClockSet(SYSCTL_SYSDIV_4|SYSCTL_USE_PLL|SYSCTL_XTAL_16MHZ|
                    SYSCTL_OSC_MAIN);

    /* Construct nfcLoad Task thread */
    Task_Params_init(&taskParams);
    taskParams.stackSize = TASKSTACKSIZE;
    taskParams.stack = &task0Stack;
    taskParams.instance->name = "imusensor";
    taskParams.priority = 1;
    Task_construct(&task0Struct, (Task_FuncPtr)imuTask, &taskParams, NULL);

    GPIO_write(Board_LED0, Board_LED_ON);

    System_printf("Starting the I2C example\nSystem provider is set to SysMin."
                  " Halt the target to view any SysMin contents in ROV.\n");
    /* SysMin will only print to the console when you call flush or exit */
    System_flush();

    srand(0xBEA5);

    /* Start BIOS */
    BIOS_start();

    return (0);
}
