/* * Copyright (c) 2006-2023, RT-Thread Development Team * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * 2023-06-04 vandoul first version */ #include #include #include "board.h" #include #ifdef BSP_USING_SCI_I2C #define DBG_TAG "drv.sci2c" #ifdef DRV_DEBUG #define DBG_LVL DBG_LOG #else #define DBG_LVL DBG_INFO #endif /* DRV_DEBUG */ #include #include struct ra_sci_i2c_handle { struct rt_i2c_bus_device bus; char bus_name[RT_NAME_MAX]; const i2c_master_cfg_t *i2c_cfg; void *i2c_ctrl; struct rt_event event; }; enum { I2C_EVENT_ABORTED = 1UL<p_context; rt_event_send(&ra_sci_i2c->event, 1UL << p_args->event); LOG_D("event:%x", p_args->event); } LOG_D("p_args:%p", p_args); } static rt_err_t validate_i2c_event(struct ra_sci_i2c_handle *handle) { rt_uint32_t event = 0; if(RT_EOK != rt_event_recv(&handle->event, I2C_EVENT_ALL, RT_EVENT_FLAG_OR|RT_EVENT_FLAG_CLEAR, (rt_int32_t)rt_tick_from_millisecond(10), &event)) { return -RT_ETIMEOUT; } if(event != I2C_EVENT_ABORTED) { return RT_EOK; } return -RT_ERROR; } static rt_ssize_t ra_i2c_mst_xfer(struct rt_i2c_bus_device *bus, struct rt_i2c_msg msgs[], rt_uint32_t num) { rt_size_t i; struct rt_i2c_msg *msg = msgs; RT_ASSERT(bus != RT_NULL); struct ra_sci_i2c_handle *ra_sci_i2c = rt_container_of(bus, struct ra_sci_i2c_handle, bus); i2c_master_ctrl_t *master_ctrl = ra_sci_i2c->i2c_ctrl; fsp_err_t err = FSP_SUCCESS; bool restart = false; for (i = 0; i < num; i++) { if (msg[i].flags & RT_I2C_NO_START) { restart = true; } if (msg[i].flags & RT_I2C_ADDR_10BIT) { //LOG_E("10Bit not support"); //break; R_SCI_I2C_SlaveAddressSet(master_ctrl, msg[i].addr, I2C_MASTER_ADDR_MODE_10BIT); } else { //master_ctrl->slave = msg[i].addr; R_SCI_I2C_SlaveAddressSet(master_ctrl, msg[i].addr, I2C_MASTER_ADDR_MODE_7BIT); } if (msg[i].flags & RT_I2C_RD) { err = R_SCI_I2C_Read(master_ctrl, msg[i].buf, msg[i].len, restart); if (FSP_SUCCESS == err) { /* handle error */ if(RT_EOK != validate_i2c_event(ra_sci_i2c)) { //LOG_E("POWER_CTL reg I2C read failed,%d", ra_sci_i2c->event); break; } } /* handle error */ else { /* Write API returns itself is not successful */ //LOG_E("R_IIC_MASTER_Write API failed"); break; } } else { err = R_SCI_I2C_Write(master_ctrl, msg[i].buf, msg[i].len, restart); if (FSP_SUCCESS == err) { if(RT_EOK != validate_i2c_event(ra_sci_i2c)) { //LOG_E("POWER_CTL reg I2C write failed,%d", ra_sci_i2c->event); break; } } /* handle error */ else { /* Write API returns itself is not successful */ //LOG_E("R_IIC_MASTER_Write API failed"); break; } } } return (rt_ssize_t)i; } static const struct rt_i2c_bus_device_ops ra_i2c_ops = { .master_xfer = ra_i2c_mst_xfer, .slave_xfer = RT_NULL, .i2c_bus_control = RT_NULL }; int ra_hw_i2c_init(void) { fsp_err_t err = FSP_SUCCESS; for(rt_uint32_t i=0; i