/*
 * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * o Redistributions of source code must retain the above copyright notice, this list
 *   of conditions and the following disclaimer.
 *
 * o 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.
 *
 * o Neither the name of Freescale Semiconductor, Inc. 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 HOLDER 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.
 */

#include "board.h"
#include "fsl_i2c_master_driver.h"
#include "fsl_device_registers.h"
#include "fsl_port_hal.h"
#include "fsl_debug_uart.h"
#include "fsl_clock_manager.h"
#include "fsl_uart_hal.h"
#include <string.h>
#include <math.h>
#include <stdio.h>
#include "sw_timer.h"

void LED_toggle_master(void)
{
    gpio_toggle_pin_output(kGpioLED1);
}
void LED_turnon_master(void)
{
    gpio_clear_pin_output(kGpioLED1);
}
void LED_toggle_slave(void)
{
    gpio_toggle_pin_output(kGpioLED2);
}
void LED_turnon_slave(void)
{
    gpio_clear_pin_output(kGpioLED2);
}

void delay(unsigned int delay_value)
{
    unsigned int i, j, k;

    for (i=0; i<delay_value; i++)
    {
        for (j=0; j<0xF; j++)
            for (k=0; k<0xFFFF; k++)
            {
                __ASM volatile("nop");
            }
    }

}


enum _subaddress_index_e
{
    Subaddress_Index_0 = 0x00,
    Subaddress_Index_1 = 0x01,
    Subaddress_Index_2 = 0x02,
    Subaddress_Index_3 = 0x03,
    Subaddress_Index_4 = 0x04,
    Subaddress_Index_5 = 0x05,
    Subaddress_Index_6 = 0x06,
    Subaddress_Index_7 = 0x07,
    Invalid_Subaddress_Index,
    Max_Subaddress_Index
};

////////////////////////////////////////////////////////////////////////////////
// Code
////////////////////////////////////////////////////////////////////////////////
void main(void)
{
    // status_t err;
    uint8_t i;
    uint8_t index, index_char, value;
    
    i2c_master_t master;
    uint8_t send_buf[1] = {0xFF};       //save data sent to i2c slave
    uint8_t receive_buf[1] = {0xFF};    //save data received from i2c slave
    i2c_status_t return_value;
    
    i2c_device_t slave = 
    {
        .address = 0x3A,
        .baudRate_kbps = 100
    };
    
    hardware_init();
    dbg_uart_init();

    gpio_init(0, ledPins);

    sw_timer_init_service();
    
    // Init I2C module
    i2c_master_init(BOARD_I2C_COMM_INSTANCE, &master);
    
    printf("\r\n====== I2C Master ======\r\n\r\n");
    delay(10);
    LED_toggle_master();
    delay(10);
    LED_toggle_master();
    delay(10);
    LED_toggle_master();
    delay(10);
    LED_toggle_master();
    
    while (1)
    {
        printf("\r\nI2C Master reads values from I2C Slave sub address:\r\n");
        printf("\r\n------------------------------------");
        printf("\r\nSlave Sub Address   |    Character         ");
        printf("\r\n------------------------------------");
        for (i=Subaddress_Index_0; i<Invalid_Subaddress_Index; i++)
        {
            return_value = i2c_master_transfer(&master, &slave, kI2CRead, false, i, 1, receive_buf, sizeof(receive_buf), NULL, 200);
            if (return_value == kStatus_I2C_Success)
            {
                printf("\r\n[%d]                      %c", i, receive_buf[0]);
            }
            else
            {
                printf("\r\nI2C communication failed, error code: %d", return_value);
            }

        }
        printf("\r\n------------------------------------");
        printf("\r\n");
        
        printf("\r\nPlease input Slave sub address and the new character.");

        do
        {
            printf("\r\nSlave Sub Address: ");
            while(!uart_hal_is_receive_data_register_full(BOARD_DEBUG_UART_INSTANCE));
            index_char= getchar();
            putchar(index_char);
            
            printf("\r\nInput New Character: ");      
            while(!uart_hal_is_receive_data_register_full(BOARD_DEBUG_UART_INSTANCE));
            value = getchar();
            putchar(value);
            
            printf("\n");

            index = (uint8_t)(index_char - '0');

            if (index >= Invalid_Subaddress_Index)
            {
                printf("\r\nInvalid Sub Address.");
            }
        } while (index >= Invalid_Subaddress_Index);
    
        send_buf[0] = value;
        return_value = i2c_master_transfer(&master, &slave, kI2CWrite, true, index, 1, send_buf, sizeof(send_buf), NULL, 200);
        if (return_value != kStatus_I2C_Success)
        {
            printf("\r\nI2C communication failed, error code: %d", return_value);
        }
        
    }
}

////////////////////////////////////////////////////////////////////////////////
// EOF
////////////////////////////////////////////////////////////////////////////////

