/*
 * Kneron I2C driver API testing code
 *
 * Copyright (C) 2019 Kneron, Inc. All rights reserved.
 *
 */

#include "cmsis_os2.h"

#include "kdrv_i2c.h"
#include "kdrv_pinmux.h"
#include "kmdw_console.h"

static void i2c_sht20_thread(void *argument)
{
    uint16_t dev_addr = 0x40;
    uint8_t cmd = 0xF3;
    uint8_t data[3];
    kdrv_status_t status;

    while(1)
    {
        status = kdrv_i2c_write_register(KDRV_I2C_CTRL_0, dev_addr, 1, 1, 1, &cmd);
        if(status != KDRV_STATUS_OK){
            DSG("kdrv_i2c_write_register() failed, status = %d\n", status);
            break;
        }

        while(1)
        {
            osDelay(10);
            status = kdrv_i2c_read_register(KDRV_I2C_CTRL_0, dev_addr, 3, 3, 3, data);
            if(status != KDRV_STATUS_OK){
                continue;
            }
            else
            {
                DSG("read data = 0x%x 0x%x 0x%x\n", data[0], data[1], data[2]);
                osDelay(5000);
                break;
            }
        }

    }
}


void i2c_master_example()
{
    DSG("Configuring pins for I2C device, enable KDRV_PIN_I2C0_SCL and KDRV_PIN_I2C0_SCL\n");

    /*
       configure selected pins as GPIO function (pinmux)
       users must check pinmux table to configure specified pins
       as desired peripheral functions properly
    */
    kdrv_pinmux_config(KDRV_PIN_I2C0_SCL, PIN_MODE_0, PIN_PULL_NONE, PIN_DRIVING_8MA);
    kdrv_pinmux_config(KDRV_PIN_I2C0_SDA, PIN_MODE_0, PIN_PULL_NONE, PIN_DRIVING_8MA);

    DSG("init I2C0\n");

    // init GPIO controller
    kdrv_status_t status;
    if( KDRV_STATUS_OK == (status = kdrv_i2c_initialize(KDRV_I2C_CTRL_0, KDRV_I2C_SPEED_400K)))
        osThreadNew(i2c_sht20_thread, NULL, NULL);
    else{
        DSG("kdrv_i2c_initialize() failed, status = \n", status);
    }
}

