在使用rtthread set
tings配置完i2c后,与pca9535pw的第一通讯报错,不知道为什么?代码如下:
main:
/* 初始化PCA9535PW */
if (pca9535pw_init(I2C_BUS_NAME) != RT_EOK)
{
return 0;
}
rt_thread_delay(1000);
while(pca9535pw_write_reg(PCA9535PW_CONFIG_PORT_0, 0x00) != RT_EOK)
{
rt_kprintf("Failed to configure Port 0\n");
}
while(pca9535pw_write_reg(PCA9535PW_CONFIG_PORT_1, 0x00) != RT_EOK)
{
rt_kprintf("Failed to configure Port 1\n");
}
while (1)
{
/* 打开特定引脚 */
if (pca9535pw_write_reg(PCA9535PW_OUTPUT_PORT_0, 0x01) != RT_EOK)
{
rt_kprintf("Failed to write to Output Port 0\n");
}
if (pca9535pw_write_reg(PCA9535PW_OUTPUT_PORT_1, 0x06) != RT_EOK)
{
rt_kprintf("Failed to write to Output Port 1\n");
}
rt_thread_mdelay(500);
/* 读取输入引脚状态 */
if (pca9535pw_read_reg(PCA9535PW_INPUT_PORT_0, &value) == RT_EOK)
{
rt_kprintf("Input Port 0: 0x%02X\n", value);
}
else
{
rt_kprintf("Failed to read from Input Port 0\n");
}
if (pca9535pw_read_reg(PCA9535PW_INPUT_PORT_1, &value) == RT_EOK)
{
rt_kprintf("Input Port 1: 0x%02X\n", value);
}
else
{
rt_kprintf("Failed to read from Input Port 1\n");
}
rt_thread_mdelay(1000);
}
pca9535pw.c:
#include "pca9535pw.h"
#define PCA9535PW_ADDRESS 0x20 // PCA9535PW的I2C地址
static struct rt_i2c_bus_device *i2c_bus = RT_NULL;
/* 初始化I2C总线 */
rt_err_t pca9535pw_init(const char *i2c_bus_name)
{
i2c_bus = (struct rt_i2c_bus_device *)rt_device_find(i2c_bus_name);
if (i2c_bus == RT_NULL)
{
rt_kprintf("I2C bus %s not found!\n", i2c_bus_name);
return -RT_ERROR;
}
rt_kprintf("I2C bus %s found!\n", i2c_bus_name);
return RT_EOK;
}
/* 写寄存器函数 */
rt_err_t pca9535pw_write_reg(rt_uint8_t reg, rt_uint8_t value)
{
struct rt_i2c_msg msgs[2];
rt_uint8_t buffer[2];
buffer[0] = reg;
buffer[1] = value;
msgs[0].addr = PCA9535PW_ADDRESS;
msgs[0].flags = RT_I2C_WR;
msgs[0].buf = buffer;
msgs[0].len = 2;
if (rt_i2c_transfer(i2c_bus, msgs, 1) == 1)
{
return RT_EOK;
}
else
{
return -RT_ERROR;
}
}
/* 读寄存器函数 */
rt_err_t pca9535pw_read_reg(rt_uint8_t reg, rt_uint8_t *value)
{
struct rt_i2c_msg msgs[2];
msgs[0].addr = PCA9535PW_ADDRESS;
msgs[0].flags = RT_I2C_WR;
msgs[0].buf = ®
msgs[0].len = 1;
msgs[1].addr = PCA9535PW_ADDRESS;
msgs[1].flags = RT_I2C_RD;
msgs[1].buf = value;
msgs[1].len = 1;
if (rt_i2c_transfer(i2c_bus, msgs, 2) == 2)
{
return RT_EOK;
}
else
{
return -RT_ERROR;
}
}