Arduino Playground is read-only starting December 31st, 2018. For more info please look at this Forum Post

Introduction

This sketch is for Arduino Nano with ATmega328 implementation to control relays via HTTP requests.

!WARNING! Every network device must have an unique MAC address. So if you use more than one device or the sketch multiple times, then you MUST change MAC address.

Requirements

The sketch is designed for:

  • Arduino Nano (or any other compatible device)
  • Ethernet Shield with ENC28J60 chip
  • 8 channel relay module
  • Arduino UIP Library

Setup

Download the sketch from Download or copy it from Nano_WebRelay8. Download and install the Arduino UIP Library.

You may need to modify the sketch:

  • The pins you have connected the relay module to
  • The number of relays you have. It is also possible to use a 4 channel relay module with this sketch. In that case also the array where the port status is cached (variable portStatus)
  • The IP address
  • The MAC address
  • You can also change the maximum request size, which is set to 512 as default. Much bigger requests cannot be handled on a arduino with 2k RAM

Usage

Call your arduino at the IP address you have set in the sketch as soon you have modified and uploaded the sketch to it. e.g. If your arduino IP address is 192.168.1.20 then enter in your browser http://192.168.1.20/ Your browser will display a JSON string like this:

   {"r":[0,0,1,0,0,0,0,0]}  
   -> 0 means the relay is turned off  
   -> 1 means the relay is turned on

I used JSON, because it is very easy to consume with other devices.

If you call the alias about then you will get a JSON string with the version of the sketch. e.g. Calling http://192.168.1.20/about will result in: {"version":"0.2"}

You need to send a POST request to change the status of one or more relays. For this you can simply use cURL with the -d switch. The POST data must follow the following pattern: relay number = 0 or 1 or 2 => e.g. 0=1&1=2&2=1&3=0&4=1&5=1&6=1&7=1

  • The relay number can only be an integer between 0 and 7 (or more depending on your modifications
  • 0 turns the relay off
  • 1 turns the relay on
  • 2 changes the status of the relay. So a turned off relay would be switched on and the other way around

e.g. #curl -d "0=1&4=2&3=0" https://192.168.1.20 It will turn on the relay number 0, then invert the state of relay 4 and as last switch off relay 3.

That is it.