/*********
Rui Santos
Complete project details at https://RandomNerdTutorials.com/esp32-relay-module-ac-web-server/
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*********/
// Import required libraries
#include "Shifty.h"
#include <Keypad.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
#define CORE_1 1
// Set to true to define Relay as Normally Open (NO)
#define RELAY_NO true
// Set number of relays
#define NUM_RELAYS 8
#define DataPin 27
#define ClockPin 32
#define LatchPin 33
#define DELAY 150
Shifty myreg;
const uint8_t ROWS = 4;
const uint8_t COLS = 4;
char keys[ROWS][COLS] = {
{ '1', '2', '3', 'A' },
{ '4', '5', '6', 'B' },
{ '7', '8', '9', 'C' },
{ '*', '0', '#', 'D' }
};
uint8_t colPins[COLS] = { 21, 19, 18, 17 }; // Pins connected to C1, C2, C3, C4
uint8_t rowPins[ROWS] = { 26, 25, 23, 22 }; // Pins connected to R1, R2, R3, R4
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
void setup(){
// Serial port for debugging purposes
Serial.begin(115200);
myreg.setBitCount(NUM_RELAYS);
myreg.setPins(DataPin, ClockPin, LatchPin);
// Set all relays to off when the program starts - if set to Normally Open (NO), the relay is off when you set the relay to HIGH
myreg.batchWriteBegin();
for(int i=0; i<NUM_RELAYS; i++){
// pinMode(relayGPIOs[i-1], OUTPUT);
if(RELAY_NO){
// digitalWrite(relayGPIOs[i-1], HIGH);
Serial.println("open Pin " + String(i) + " to High");
myreg.writeBit(i, HIGH);
}
else{
// digitalWrite(relayGPIOs[i-1], LOW);
myreg.writeBit(i, LOW);
}
}
myreg.batchWriteEnd();
xTaskCreatePinnedToCore(keyboardTask, "Keyboard Reading", 2048, (void*)&keypad, 0, NULL, CORE_1);
readKeyboxConfig();
}
void loop() {
myreg.writeBit(0, LOW);
myreg.writeBit(1, LOW);
myreg.writeBit(2, LOW);
delay(DELAY);
myreg.writeBit(0, HIGH);
delay(DELAY);
myreg.writeBit(0, LOW);
myreg.writeBit(1, HIGH);
delay(DELAY);
myreg.writeBit(1, LOW);
myreg.writeBit(2, HIGH);
delay(DELAY);
}
void readKeyboxConfig(){
WiFiClientSecure *client;
client->setInsecure();
HTTPClient httpClient;
httpClient.begin(*client, "https://hghelbig.com/keybox.json");
int httpCode = httpClient.GET();
if(httpCode > 0){
Serial.printf("[HTTP] GET... code: %d\n", httpCode);
if(httpCode == HTTP_CODE_OK){
Serial.println(httpClient.getString());
}
} else {
Serial.printf("[HTTP] GET... failed, error: %s\n", httpClient.errorToString(httpCode).c_str());
}
httpClient.end();
}
void keyboardTask(void * pvParameters) {
Keypad& keypad = *((Keypad*)pvParameters);
Serial.println("keyboardTask started");
String enteredCode = "";
while(true){
char key = keypad.getKey();
while(key != NO_KEY){
Serial.println(key);
if(key == '#'){
Serial.println("code: " + enteredCode);
enteredCode = "";
} else {
enteredCode += key;
}
key = NO_KEY;
}
}
}