Qwiic Single Relay Hookup Guide
Example Code
The Qwiic Relay is pretty simple, so all of the functions to control it are simply contained in the first example of the SparkFun Qwiic Relay Arduino Library.
Example 1 - Single Relay Basics
Go ahead and unzip the folder to a directory of your choosing and open up Example1_Single_Relay_Basics
.
Starting at the top, we have #include
-ed the path to the library's header file as well as to Arduino's I²C library: Wire.h
. To use the functions in the SparkFun Qwiic Relay Library we create a version of it, and name it relay
. You'll notice that in parentheses we have given it the board's address. If you have changed this address or closed the address jumper, than change the RELAY_ADDR
to your address.
language:c
#include <Wire.h>
#include "SparkFun_Qwiic_Relay.h"
#define RELAY_ADDR 0x18 // Alternate address 0x19
Qwiic_Relay relay(RELAY_ADDR);
Let's look at the setup. First we check that we can communicate correctly with the Single Qwiic Relay with the relay.begin()
function call. If there are some connection issues we'll find out about them here. Note that the code will not stop if there is an error, so keep an eye out for an eror message. Next we check the version of the firmware that is on your product with the relay.singleRelayVersion()
function.
language:c
void setup()
{
Wire.begin();
Serial.begin(115200);
// Let's see
if(!relay.begin())
Serial.println("Check connections to Qwiic Relay.");
else
Serial.println("Ready to flip some switches.");
float version = relay.singleRelayVersion();
Serial.print("Firmware Version: ");
Serial.println(version);
Now we turn on and off the relay by using two functions. First the more obvious function turnRelayOn()
turns on the relay, which can then be turned off with turnRelayOff
. Next the relay is toggled on and off, with the toggleRelay()
function. The difference here is that the relay is turned off or on depending on the current state of the relay: if off ---> turn on and vice versa.
language:c
// Let's turn on the relay...
relay.turnRelayOn();
delay(500);
// Let's turn that relay off...
relay.turnRelayOff();
delay(500);
// Let's 'toggle' the relay; if it's off turn it on and vice versa.
relay.toggleRelay();
delay(500);
// Toggle the relay back off.
relay.toggleRelay();
delay(500);
You're probably wondering why I'm doing this entirely in the setup? In the chance that you're running this for the first time without reading, you won't have a relay constantly turning on and off. Now at the end of the setup we see the final feature of the SparkFun Qwiic Arduino Library.
language:c
Serial.print("The Relay is now: ");
// Is the relay on or off?
int state = relay.getState();
if(state == 1)
Serial.print("On!");
else if(state == 0)
Serial.print("Off!");
}
Using the getState
function we can check whether or not the relay is on or off without looking at the board. This can help you programmatically make decisions based on your project's needs.