nrf91 I2C驱动

#include <logging/log.h>
#include <zephyr.h>
#include <drivers/i2c.h>
#include <stdio.h>
#include "twi.h"

LOG_MODULE_REGISTER(slm_twi, CONFIG_SLM_LOG_LEVEL);

#if defined(CONFIG_HAS_HW_NRF_TWIM3)
#define TWI_MAX_INSTANCE	4
#elif defined(CONFIG_HAS_HW_NRF_TWIM2)
#define TWI_MAX_INSTANCE	3
#elif defined(CONFIG_HAS_HW_NRF_TWIM1)
#define TWI_MAX_INSTANCE	2
#elif defined(CONFIG_HAS_HW_NRF_TWIM0)
#define TWI_MAX_INSTANCE	1
#endif
#define TWI_ADDR_LEN		2
#define TWI_DATA_LEN		128


static const struct device *slm_twi_dev[TWI_MAX_INSTANCE];
static uint8_t twi_data[TWI_DATA_LEN * 2 + 1];


int do_twi_write(uint16_t index, uint16_t dev_addr, uint8_t *data, uint16_t len)
{
	int ret = -EINVAL;

	ret = i2c_write(slm_twi_dev[index], data, len, dev_addr);
	if (ret < 0) {
		LOG_ERR("Fail to write twi data at address: %hx", dev_addr);
	}

	return ret;
}

int do_twi_read(uint16_t index, uint16_t dev_addr, uint8_t num_read)
{
	int ret = -EINVAL;

	if (!slm_twi_dev[index]) {
		LOG_ERR("TWI device is not opened");
		return ret;
	}

	if (num_read > TWI_DATA_LEN) {
		LOG_ERR("Not enough buffer. Increase TWI_DATA_LEN");
		return -ENOBUFS;
	}

	memset(twi_data, 0, sizeof(twi_data));
	ret = i2c_read(slm_twi_dev[index], twi_data, (uint32_t)num_read, dev_addr);
	if (ret < 0) {
		LOG_ERR("Fail to read twi data");
		return ret;
	}
	return ret;
}

int twi_init(void)
{
#if DT_NODE_HAS_COMPAT_STATUS(DT_NODELABEL(i2c0), nordic_nrf_twim, okay)
	slm_twi_dev[0] = device_get_binding(DT_LABEL(DT_NODELABEL(i2c0)));
	LOG_DBG("bind %s", slm_twi_dev[0]->name);
#endif
#if DT_NODE_HAS_COMPAT_STATUS(DT_NODELABEL(i2c1), nordic_nrf_twim, okay)
	slm_twi_dev[1] = device_get_binding(DT_LABEL(DT_NODELABEL(i2c1)));
	LOG_DBG("bind %s", slm_twi_dev[1]->name);
#endif
#if DT_NODE_HAS_COMPAT_STATUS(DT_NODELABEL(i2c2), nordic_nrf_twim, okay)
	slm_twi_dev[2] = device_get_binding(DT_LABEL(DT_NODELABEL(i2c2)));
	LOG_DBG("bind %s", slm_twi_dev[2]->name);
#endif
#if DT_NODE_HAS_COMPAT_STATUS(DT_NODELABEL(i2c3), nordic_nrf_twim, okay)
	slm_twi_dev[3] = device_get_binding(DT_LABEL(DT_NODELABEL(i2c3)));
	LOG_DBG("bind %s", slm_twi_dev[3]->name);
#endif

	return 0;
}

static int twi_write_bytes(uint8_t addr, uint8_t *data, uint32_t num_bytes)
{
	do_twi_write( 2, addr, data, num_bytes );
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值