目前,我有两个 2 channel 1 Amp SPDT 信号继电器 Controller 通过 I2C 连接到我的 Raspberry Pi 3,当我当前运行打开一个继电器的功能时,另一个继电器将同时关闭(其中一个已打开)。此外,用于关闭继电器 1 的按钮和用于关闭继电器 2 的按钮将关闭两个继电器。
我的程序是用 Windows 窗体(Visual Studio)编写的,我正在通过 Dll 导入访问 C 共享库,但我知道我的问题出在我的 C 库中。我对 C 以及移位的工作原理非常陌生,所以我的问题的根源在于我的代码的逻辑和结构。坦率地说,我对如何正确编码感到困惑。
这是当前打开继电器 1 的方法。它会正确打开继电器,但同时也会关闭继电器 2。
void Relay1On() ***CURRENTLY TURNS OTHER OFF WHEN ACTIVATED***
{
// Create I2C bus
int file;
char *bus = "/dev/i2c-1";
if ((file = open(bus, O_RDWR)) < 0)
{
printf("Failed to open the bus. \n");
exit(1);
}
// Get I2C device, MCP23008 I2C address is 0x20(32)
ioctl(file, I2C_SLAVE, 0x20);
// Configure all pins of port as output (0x00)
char config[2] = {0};
config[0] = 0x00;
config[1] = 0x00;
write(file, config, 2);
//Turn the first relay on
char data = 0x01;
config[0] = 0x09;
config[1] = data;
write(file, config, 2);
}
这是 Relay 1 Off 的代码,我不会发布 Relay 2 On/Off 因为它基本相同,Relay2On 只是在 char 之后添加了
。两种“关闭”方法都会导致两个继电器关闭。 data += 1;
数据 = 0x01;
void Relay1Off()
{
// Create I2C bus
int file;
char *bus = "/dev/i2c-1";
if ((file = open(bus, O_RDWR)) < 0)
{
printf("Failed to open the bus. \n");
exit(1);
}
// Get I2C device, MCP23008 I2C address is 0x20(32)
ioctl(file, I2C_SLAVE, 0x20);
// Configure all pins of port as output (0x00)
char config[2] = {0};
config[0] = 0x00;
config[1] = 0x00;
write(file, config, 2);
//Turn the first relay off *****Turns all off at the moment******
char data = 0xFE;
data = (data << 1);
config[0] = 0x09;
config[1] = data;
write(file, config, 2);
}
我想要的只是按照所描述的方法执行操作,在调用该方法时打开继电器 1。调用 Relay1Off 时,仅关闭继电器 1。我确信它很简单,但正如我上面所说,C 对我来说相当陌生。
预先感谢您的贡献。
最佳答案
我不知道奇特的 ioctl
东西是如何工作的,但我会尝试在此函数之外进行所有初始化,包括将所有 GPIO 设置为输出。
您可能应该只调用一个函数来设置/清除继电器。我会做这样的事情来开始:
void RelayOnOff(unsigned char relay, unsigned char enable)
{
//Init to all off
static unsigned char data = 0x00;
...
if (enable){
data |= ( 1 << relay );
}
else{
data &= ~( 1 << relay );
}
config[0] = 0x09;
config[1] = data;
write(file, config, 2);
}
您传入要控制的继电器以及用于启用/禁用的 bool 值。如果将数据变量设为静态,它会在函数调用之间“记住”该值。启用/禁用设置/清除您在 (0-7) 中传递的任何继电器的位。
关于c - 打开一个 Raspberry Pi I2C 连接的继电器会关闭另一个继电器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57083604/