Connecting a Relay Block to an Arduino via I²C
Do you love I²C as much as I do? Truly an ingenious invention – you can connect up to 64 devices with just two wires (not counting power). Today’s article is a tutorial for beginners. We will connect a ready-made relay block of 8 pieces, using only two pins. Oddly enough, I never found normal tutorials, including in the English-speaking segment. I will try to fill this gap.
The relays already have all the necessary wiring and can be controlled directly by digital outputs. But our task is to connect them via I²C. As in my last article about USB keyboard (https://habr.com/en/post/645109/), I took an I²C I/O port expander on a PCF8574 chip. It has 8 ports (P0 – P7) and one interrupt pin, which we will not use in this case. Connecting the relay module and the PCF8574 module is very simple – solder IN1 – IN8 to P0 – P7, respectively. It is very convenient to solder the module directly onto the relay block pins. You can also solder a cable with a connector for convenience. I took “twisted pair” and a DIN-5 connector. The relay block lay in my box on the mezzanine for 7 years, so it got a little dusty. A big plus of this block is the presence of LEDs signaling the inclusion of the relay.
We connect A4> SDA, A5> SCL to Arduino Nano. And, of course, food.
The I²C device is accessed at an address that can be set with DIP switches on the PCF8574 module board. When they are all off (0 0 0), this corresponds to address 0x20. I took the PU2CLR library – PCF8574 Arduino Library (https://github.com/pu2clr/PCF8574), it can also be installed via the Arduino IDE Library Manager. The following sketch will “flip” all 8 relays in a loop with a 1 second delay.
#include <pu2clr_pcf8574.h>
PCF pcf;
void setup()
{
// I2C адрес устройства 0x20
pcf.setup(0x20);
}
void loop()
{
// перебираем в цикле все 8 реле
for (int i=0; i<8; i++)
{
// включить реле
pcf.digitalWrite(i,LOW);
delay(1000);
// выключить реле
pcf.digitalWrite(i,HIGH);
}
}
As a bonus, my box is a tester. I collected it specifically for such experiments. It consists of an Arduino Nano, a 1602 LCD screen with a soldered module… I²C of course, an encoder with a button, and a tweeter (which can only squeak, i.e. make a single tone sound, just for fun). With two clicks on the encoder knob, you can, for example, find out the addresses of all connected I²C devices, by turning the knob you can switch ports. What’s funny, all the filling fit in the lid of the box. The housing only has a DIN-5 connector. How the relay works with this device is in the video.