Pier8283
Published © GPL3+

Webserver relay control with Arduino PICO W

In this tutorial we explain how to control the Relay Board V1.0.0 for Raspberry with a Web Server on PICO W.

IntermediateWork in progress2 hours2,136
Webserver relay control with Arduino PICO W

Things used in this project

Hardware components

Relays Board V1.0.0
×1
Raspberry PICO W
×1

Software apps and online services

Arduino IDE
Arduino IDE

Hand tools and fabrication machines

Premium Female/Male Extension Jumper Wires, 40 x 6" (150mm)
Premium Female/Male Extension Jumper Wires, 40 x 6" (150mm)

Story

Read more

Schematics

pico_wireless_relay_F2q5b3EPa3.pdf

Code

Pico_Wireless_Relay.ino

Arduino
/****************************************************************************************************************************
  Wireless PICO W relays control
  SG Electronic Systems srls
  
  derived from Async_AdvancedWebServer.ino

  For RP2040W with CYW43439 WiFi

  AsyncWebServer_RP2040W is a library for the RP2040W with CYW43439 WiFi

  Based on and modified from ESPAsyncWebServer (https://github.com/me-no-dev/ESPAsyncWebServer)
  Built by Khoi Hoang https://github.com/khoih-prog/AsyncWebServer_RP2040W
  Licensed under GPLv3 license

  Copyright (c) 2015, Majenko Technologies
  All rights reserved.

  Redistribution and use in source and binary forms, with or without modification,
  are permitted provided that the following conditions are met:

  Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

  Redistributions in binary form must reproduce the above copyright notice, this
  list of conditions and the following disclaimer in the documentation and/or
  other materials provided with the distribution.

  Neither the name of Majenko Technologies nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *****************************************************************************************************************************/

// See the list of country codes in
// https://github.com/earlephilhower/cyw43-driver/blob/02533c10a018c6550e9f66f7699e21356f5e4609/src/cyw43_country.h#L59-L111
// To modify https://github.com/earlephilhower/arduino-pico/blob/master/variants/rpipicow/picow_init.cpp
// Check https://github.com/khoih-prog/AsyncWebServer_RP2040W/issues/3#issuecomment-1255676644

#if !( defined(ARDUINO_RASPBERRY_PI_PICO_W) )
	#error For RASPBERRY_PI_PICO_W only
#endif

#define _RP2040W_AWS_LOGLEVEL_     1

#define REL1   0  //GP00
#define REL2   1  //GP01
#define REL3   2  //GP02
#define REL4   3  //GP03
#define REL5   4  //GP04
#define REL6   5  //GP05
#define REL7   6  //GP06
#define REL8   7  //GP07



///////////////////////////////////////////////////////////////////

#include <pico/cyw43_arch.h>

///////////////////////////////////////////////////////////////////

#include <AsyncWebServer_RP2040W.h>

char ssid[] = "your network SSID";        // your network SSID (name) 
char pass[] = "your network password";         // your network password (use for WPA, or use as key for WEP), length must be 8+

int status = WL_IDLE_STATUS;

AsyncWebServer    server(80);

int reqCount = 0;                // number of requests received

#define LED_OFF             LOW
#define LED_ON              HIGH
#define REL_OFF             HIGH
#define REL_ON              LOW

#define BUFFER_SIZE         2048
char temp[BUFFER_SIZE];
char relay_status[8] = {HIGH,HIGH,HIGH,HIGH,HIGH,HIGH,HIGH,HIGH};
char rel_status_text[8][10];


void set_relay(void)
{
  digitalWrite(REL1, relay_status[0]);
  digitalWrite(REL2, relay_status[1]);
  digitalWrite(REL3, relay_status[2]);
  digitalWrite(REL4, relay_status[3]);
  digitalWrite(REL5, relay_status[4]);
  digitalWrite(REL6, relay_status[5]);
  digitalWrite(REL7, relay_status[6]);
  digitalWrite(REL8, relay_status[7]);
}

void handleRoot(AsyncWebServerRequest *request)
{
	static uint32_t pageCount   = 0;
	static uint32_t maxfreeHeap = 0;
	static uint32_t minFreeHeap = 0xFFFFFFFF;
	uint32_t curFreeHeap = rp2040.getFreeHeap();

	if (maxfreeHeap < curFreeHeap)
		maxfreeHeap = curFreeHeap;

	if (minFreeHeap > curFreeHeap)
		minFreeHeap = curFreeHeap;

	digitalWrite(LED_BUILTIN, LED_ON);

	int sec = millis() / 1000;
	int min = sec / 60;
	int hr = min / 60;
	int day = hr / 24;


	snprintf(temp, BUFFER_SIZE - 1,
	         "<html>\
<head>\
<meta http-equiv='refresh' content='5'/>\
<title>AsyncWebServer-%s</title>\
<style>\
body { background-color: #f1c40f; font-family: Arial, Helvetica, Sans-Serif; Color: #000000; }\
</style>\
</head>\
<body>\
<h2>Relay_Control_RP2040W!</h2>\
<h3>running WiFi on %s</h3>\
<p>Uptime: %d d %02d:%02d:%02d, pageCount: %lu</p>\
<p>Heap Free: %lu, Max: %lu, Min: %lu</p>\
<h1>Pico W</h1>\
<p>Control the onboard RELAYS</p>\
<a href=\"?RELAY=1&status=on\"><button>REL 1 ON</button></a>&nbsp;\
<a href=\"?RELAY=1&status=off\"><button>REL 1 OFF</button></a>&nbsp; RELAY 1 - %s\
<br>\
<a href=\"?RELAY=2&status=on\"><button>REL 2 ON</button></a>&nbsp;\
<a href=\"?RELAY=2&status=off\"><button>REL 2 OFF</button></a>&nbsp; RELAY 2 - %s\
<br>\
<a href=\"?RELAY=3&status=on\"><button>REL 3 ON</button></a>&nbsp;\
<a href=\"?RELAY=3&status=off\"><button>REL 3 OFF</button></a>&nbsp; RELAY 3 - %s\
<br>\
<a href=\"?RELAY=4&status=on\"><button>REL 4 ON</button></a>&nbsp;\
<a href=\"?RELAY=4&status=off\"><button>REL 4 OFF</button></a>&nbsp; RELAY 4 - %s\
<br>\
<a href=\"?RELAY=5&status=on\"><button>REL 5 ON</button></a>&nbsp;\
<a href=\"?RELAY=5&status=off\"><button>REL 5 OFF</button></a>&nbsp; RELAY 5 - %s\
<br>\
<a href=\"?RELAY=6&status=on\"><button>REL 6 ON</button></a>&nbsp;\
<a href=\"?RELAY=6&status=off\"><button>REL 6 OFF</button></a>&nbsp; RELAY 6 - %s\
<br>\
<a href=\"?RELAY=7&status=on\"><button>REL 7 ON</button></a>&nbsp;\
<a href=\"?RELAY=7&status=off\"><button>REL 7 OFF</button></a>&nbsp; RELAY 7 - %s\
<br>\
<a href=\"?RELAY=8&status=on\"><button>REL 8 ON</button></a>&nbsp;\
<a href=\"?RELAY=8&status=off\"><button>REL 8 OFF</button></a>&nbsp; RELAY 8 - %s\
</body>\
</html>", BOARD_NAME, BOARD_NAME, day, hr % 24, min % 60, sec % 60, ++pageCount, curFreeHeap, maxfreeHeap, minFreeHeap, 
rel_status_text[0], rel_status_text[1], rel_status_text[2], rel_status_text[3], rel_status_text[4], rel_status_text[5], rel_status_text[6], rel_status_text[7]);

	request->send(200, "text/html", temp);
 	digitalWrite(LED_BUILTIN, LED_OFF);
}

void handleNotFound(AsyncWebServerRequest *request)
{
	digitalWrite(LED_BUILTIN, LED_ON);
	String message = "File Not Found\n\n";
	message += "URI: ";
	message += request->url();
	message += "\nMethod: ";
	message += (request->method() == HTTP_GET) ? "GET" : "POST";
	message += "\nArguments: ";
	message += request->args();
	message += "\n";

	for (uint8_t i = 0; i < request->args(); i++)
	{
		message += " " + request->argName(i) + ": " + request->arg(i) + "\n";
	}

	request->send(404, "text/plain", message);
	digitalWrite(LED_BUILTIN, LED_OFF);
}

void printWifiStatus()
{
	// print the SSID of the network you're attached to:
	Serial.print("SSID: ");
	Serial.println(WiFi.SSID());

	// print your board's IP address:
	IPAddress ip = WiFi.localIP();
	Serial.print("Local IP Address: ");
	Serial.println(ip);

	// print your board's country code
	// #define CYW43_COUNTRY(A, B, REV) ((unsigned char)(A) | ((unsigned char)(B) << 8) | ((REV) << 16))
	uint32_t myCountryCode = cyw43_arch_get_country_code();
	char countryCode[3] = { 0, 0, 0 };

	countryCode[0] = myCountryCode & 0xFF;
	countryCode[1] = (myCountryCode >> 8) & 0xFF;

	Serial.print("Country code: ");
	Serial.println(countryCode);
}

void setup()
{
  for (int init_rel_status = 0; init_rel_status<8; init_rel_status++ )
  {
    strcpy(rel_status_text[init_rel_status], "OFF");
  }
	pinMode(LED_BUILTIN, OUTPUT);
	digitalWrite(LED_BUILTIN, LED_OFF);
  // Init relay pins
  pinMode(REL1, OUTPUT);
  digitalWrite(REL1, REL_OFF);
  pinMode(REL2, OUTPUT);
  digitalWrite(REL2, REL_OFF);
  pinMode(REL3, OUTPUT);
  digitalWrite(REL3, REL_OFF);
  pinMode(REL4, OUTPUT);
  digitalWrite(REL4, REL_OFF);
  pinMode(REL5, OUTPUT);
  digitalWrite(REL5, REL_OFF);
  pinMode(REL6, OUTPUT);
  digitalWrite(REL6, REL_OFF);
  pinMode(REL7, OUTPUT);
  digitalWrite(REL7, REL_OFF);
  pinMode(REL8, OUTPUT);
  digitalWrite(REL8, REL_OFF);
	Serial.begin(115200);

	while (!Serial && millis() < 5000);

	delay(200);
	Serial.println("Init PICO Wireless Relay V1.0");
	Serial.print("\nStart Async_AdvancedWebServer on for Relay board ");
	Serial.print(BOARD_NAME);
	Serial.print(" with ");
	Serial.println(SHIELD_TYPE);
	Serial.println(ASYNCTCP_RP2040W_VERSION);
	Serial.println(ASYNC_WEBSERVER_RP2040W_VERSION);

	///////////////////////////////////

	// check for the WiFi module:
	if (WiFi.status() == WL_NO_MODULE)
	{
		Serial.println("Communication with WiFi module failed!");

		// don't continue
		while (true);
	}

	Serial.print(F("Connecting to SSID: "));
	Serial.println(ssid);

	status = WiFi.begin(ssid, pass);

	delay(1000);
	// attempt to connect to WiFi network
	while ( status != WL_CONNECTED)
	{
		delay(500);
		// Connect to WPA/WPA2 network
		status = WiFi.status();
	}

	printWifiStatus();

	///////////////////////////////////


	server.on("/", HTTP_GET, [](AsyncWebServerRequest * request)
	{
		handleRoot(request);
    int paramsNr = request->params();
    
    if (paramsNr == 2)
    {
      AsyncWebParameter* p1 = request->getParam(0);
      AsyncWebParameter* p2 = request->getParam(1);
      if ((p1->name() == "RELAY") && (p2->name() == "status"))
      {
        int rel_number = p1->value().toInt();
        int rel_is_on = 0;
        Serial.print("Relay ");
        Serial.print(rel_number);
        if (p2->value() == "on")
        {
          Serial.println(" On");
          rel_is_on = REL_ON ;
        }
        else if (p2->value() == "off")
        {
          Serial.println(" Off");
          rel_is_on = REL_OFF;
        }

        if ((rel_number>=1) && (rel_number <=8))
        {
          relay_status[rel_number-1] = rel_is_on;
          if (rel_is_on == REL_ON)  strcpy(rel_status_text[rel_number-1], "ON");
          else if (rel_is_on == REL_OFF)  strcpy(rel_status_text[rel_number-1], "OFF");
          set_relay();
        }   
      }
    }

	});


	server.onNotFound(handleNotFound);
	server.begin();
	Serial.print(F("AsyncWebServer is @ IP : "));
	Serial.println(WiFi.localIP());
}

void heartBeatPrint()
{
	static int num = 1;

	Serial.print(F(""));

	if (num == 80)
	{
		Serial.println();
		num = 1;
	}
	else if (num++ % 10 == 0)
	{
		Serial.print(F(""));
	}
}

void check_status()
{
	static unsigned long checkstatus_timeout = 0;

#define STATUS_CHECK_INTERVAL     1000L

	// Send status report every STATUS_REPORT_INTERVAL (60) seconds: we don't need to send updates frequently if there is no status change.
	if ((millis() > checkstatus_timeout) || (checkstatus_timeout == 0))
	{
		heartBeatPrint();
		checkstatus_timeout = millis() + STATUS_CHECK_INTERVAL;
	}
}

void loop()
{
	check_status();
}

Credits

Pier8283

Pier8283

10 projects • 5 followers

Comments