Hardware Reference
In-Depth Information
Testing the relays and Wi-Fi connection
Now that the hardware configuration is complete, we can start writing some code to test
our project. We'll first write a simple sketch to test a given relay. Go over to your Arduino
IDE and you can start writing some code. The most important parts of the code will be de-
tailed below, and you can find the complete code on the GitHub repository of the project at
The first step is to declare which pin the relay you want to test is connected to:
const int relay_pin = 6;
We use a
const int
variable here, which is similar to
#define
but better, since we are
sure the constant is of the right type. In the
setup()
function of the sketch, we need to
specify that this pin is a digital output with the
pinMode()
function:
pinMode(relay_pin,OUTPUT);
Then, inside the
loop()
function, we are basically going to activate the relay, wait for 5
seconds, switch it off again, wait for 5 seconds again, and repeat the process. This is done
with the following piece of code:
// Activate relay
digitalWrite(relay_pin, HIGH);
// Wait for 5 seconds
delay(5000);
// Deactivate relay
digitalWrite(relay_pin, LOW);
// Wait for 5 seconds
delay(5000);
You can now upload the code to the Arduino board. If you made the right hardware con-
nections, you should now see your lamp switching on and off every 5 seconds. If that's not
the case, you need to check your hardware connections, especially between the relay mod-
ule and Arduino. You should hear the relay click whenever the state of the relay is chan-
ging.