RT-Thread--设备(I2C设备)

/*find slave i2c device address*/
static rt_device_t _i2c_find(const char *name)
{
    rt_device_t dev;

    dev = rt_device_find(name);
    if (!dev)
    {
        rt_kprintf("search device failed: %s\n", name);
        return RT_NULL;
    }

    if (rt_device_open(dev, RT_DEVICE_OFLAG_RDWR) != RT_EOK)
    {
        rt_kprintf("open device failed: %s\n", name);
        return RT_NULL;
    }

    rt_kprintf("open i2c bus: %s\n", name);

    return dev;
}

static void _search_i2c_device(rt_device_t dev, uint8_t cmd)
{
    int count = 0;
    struct rt_i2c_msg msgs[2];
    uint8_t buf = 0;

    msgs[0].flags = RT_I2C_WR;
    msgs[0].buf   = &cmd;
    msgs[0].len   = sizeof(cmd);

    msgs[1].flags = RT_I2C_RD;
    msgs[1].buf   = &buf;
    msgs[1].len   = 1;

    for (int i = 0; i <= 0x7f; i++)
    {
        int len;

        msgs[0].addr  = i;
        msgs[1].addr  = i;
        len = rt_i2c_transfer((struct rt_i2c_bus_device *)dev, msgs, 2);
        if (len == 2)
        {
            count++;
            rt_kprintf("add:%02X transfer success, id: %02X\n", i, buf);
        }
    }

    rt_kprintf("i2c device: %d\n", count);
}

static int i2c_test(const char *name, uint8_t cmd)
{
    rt_device_t dev = _i2c_find(name);

    if (dev == RT_NULL)
    {
        rt_kprintf("search i2c device faild\n");
        return -1;
    }

    _search_i2c_device(dev, cmd);
    rt_device_close(dev);

    return 0;
}

static void i2c_find_address()
{
    i2c_test("i2c1", 0xa3);
}

MSH_CMD_EXPORT(i2c_find_address, find i2c address);
/*i2c write and read AT24C02 test*/
#define EEP_I2CBUS_NAME          "i2c1"  
#define EEP_ADDR                  0x50 
rt_uint8_t wr_data = 0x15;
#define SIZE sizeof(wr_data)	
 
static struct rt_i2c_bus_device *eep_i2c_bus = RT_NULL;
 

rt_err_t eeprom_iic_write(rt_uint8_t write_addr, rt_uint8_t data, rt_uint32_t number)
{
   rt_uint8_t buf[2];
 
    buf[0] = write_addr;
    buf[1] = data;
    rt_size_t result;
  
    result = rt_i2c_master_send(eep_i2c_bus, EEP_ADDR, RT_I2C_WR, buf, 2);
    rt_thread_mdelay(10);  
    if (result == 2)
    {
        rt_kprintf("EEP write ok \r\n");
        return RT_EOK;       
    }
    else
    {
        rt_kprintf("EEP write failed ,ERR is: %d \r\n",result);
        return -RT_ERROR;       
    }
}
 

void eeprom_iic_read(rt_uint8_t read_addr, rt_uint32_t len, rt_uint8_t *buf)
{   
    rt_i2c_master_send(eep_i2c_bus, EEP_ADDR, RT_I2C_WR, &read_addr, 1);
    
    rt_i2c_master_recv(eep_i2c_bus, EEP_ADDR, RT_I2C_RD, buf, len);
}
 
void i2c_drive_test(void)
{
    rt_uint8_t buf;
     eep_i2c_bus = rt_i2c_bus_device_find(EEP_I2CBUS_NAME);
     rt_kprintf("EEP set i2c bus to %s\r\n", EEP_I2CBUS_NAME);
    
     eeprom_iic_write(0x09,wr_data,SIZE);
     
     eeprom_iic_read(0x09, 1, &buf);
    
     if(buf == wr_data)
     {
        rt_kprintf("EEP read ok ,data is: 0x%02x \r\n",buf);
     }
}
 
MSH_CMD_EXPORT(i2c_drive_test, i2c drive test);

 

你可能感兴趣的:(RTOS)