So you have a USB Power Shield (or anything that uses a latching relay). How do you control it in an Arduino Sketch?
Normal relays are pretty simple – supply voltage/current to the coil and it generates a magnetic field, which pushes the switch to the ON position. You only need one pin to run it, although you may need a transistor to supply more current because most microcontrollers can only supply 50mA, which often isn’t enough current to create a magnetic field to move the switch. You must maintain the current to keep the switch on.
Latching relays are similar to this, but once put into position, it “latches” there and requires no further current to stay in that position. This uses less power and makes the switching more reliable – if there is a decrease in current supplied, the switch will still stay in position, unlike the regular relay which could flicker. The downside is that the common types require two pins. Sending current in one direction switches on, and reversing the current switches it off.
So how do you control it? Set two pins to be outputs (the USB Power Shield uses 12/11 and 10/9 for the two relays). Write one pin LOW and the other pin HIGH. After a sufficient time to make the switching happen (50ms or less, check the datasheet for the relay), switch the HIGH pin back to low. This gives the magnetic field a place to sink, as well as making sure no more current is supplied to the coil, preventing overheating and wasting power.
Ideally, with a normal relay you’d like to force the stored current from the magnetic field back through the coil by using a flyback diode across it, but with a latched relay and current running in both directions, a diode would be needed in each direction. And that would simply cause a short circuit both ways. I’ve tested the relays used in the USB Power Shield and they don’t harm the Arduino (even over thousands of cycles) so this isn’t a huge worry here.
Below is some sample code for using the USB Power Shield with an Arduino.
Simply set up the pins for relay1 and relay2:
//give the pins names
int relay11 = 12;
int relay12 = 11;
int relay21 = 10;
int relay22 = 9;
//set the pins to outputs
//make sure they start in the off position
// do other stuff
Then add these functions to turn the relays on and off:
void relay1 (bool state)
digitalWrite(relay12,LOW); //set the current in one direction
delay(50); //hold long enough to switch
digitalWrite(relay11,LOW); //set both to ground to stop current
void relay2 (bool state)
Then simply write your main loop to do whatever you wish. Call relay1(true) to turn relay1 on, call relay2(false) to turn relay2 off, etc.