IoT World Part 3: Keypad access on ESP8266 using Losant

Needed components

 

Creating device and setting up the workflow in Losant

Log in your account, in case of not having one, sing up, it’s really fast and easy

Create a device and set Device attributes to Data Type – String and Name – keycode or you can use my recipe

 

Add new workflow, mine is named Keypad workflow

While in the workflow add Device (Triggers) which connects to Conditional (Logic) with Expression {{data.keycode}} === ‘123’ (where 123 is the keycode which grants access)

Conditional connects to 2 Device Command (Outputs) on the red condition (false) set Command Name Template to false

On the green condition (true) set Command Name Template to true

My workflow is available

Here is a tutorial how to get started



Wiring the ESP8266 and the keypad

Connect D0 to D7 (ESP8266) to the keypad left to right.

With the keypad facing you and pins on the bottom side connect D0 to the first pin left to right. D1 to the second pin left to right and etc.

 

Adding the necessary library

Go to Platform IO Home under <> Libraries search for keypad (in case you don’t know how, check out my article)

Install Keypad by Mark Stanley Alexander Brevig 

When the installation is finished you need to go to Platform IO top menu and select Rebuild C/C++ Project Index



 

Flashing the code on the ESP8266

Create a file inside ProjectName/src/ called main.cpp and inside put

#include <ESP8266WiFi.h>
#include <Keypad.h>
#include <Losant.h>

// WiFi credentials.
const char *WIFI_SSID = "wifi-name";
const char *WIFI_PASS = "wifi-password";

// Losant credentials.
const char *LOSANT_DEVICE_ID = "device-id"; // Device id can be found under Applications > Devices > Your device > Right corner 
const char *LOSANT_ACCESS_KEY = "access-key";
const char *LOSANT_ACCESS_SECRET ="access-secret"; // To generate Key & Secret go to Applications > Security > Right corder + Add access key

WiFiClientSecure wifiClient;

// For an unsecure connection to Losant.
// WiFiClient wifiClient;

LosantDevice device(LOSANT_DEVICE_ID);

// Keypad input
String input = "";

const byte ROWS = 4; // four rows
const byte COLS = 4; // four columns

// define the cymbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] = {{'1', '2', '3', 'A'},
                             {'4', '5', '6', 'B'},
                             {'7', '8', '9', 'C'},
                             {'*', '0', '#', 'D'}};

byte rowPins[ROWS] = {D0, D1, D2, D3};
byte colPins[COLS] = {D4, D5, D6, D7};

// initialize an instance of class NewKeypad
Keypad keypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

// Called whenever the device receives a command from the Losant platform.
void handleCommand(LosantCommand *command) {
  Serial.println();
  Serial.print("Command received: ");
  Serial.println(command->name);

  if (strcmp(command->name, "true") == 0) {
    Serial.println("Access granted");
  } else if (strcmp(command->name, "false") == 0) {
    Serial.println("Access denied");
  }
}

void connect() {
  // Connect to Wifi.
  Serial.print("Connecting to ");
  Serial.println(WIFI_SSID);

  WiFi.begin(WIFI_SSID, WIFI_PASS);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println();
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  // Connect to Losant.
  Serial.println();
  Serial.print("Connecting to Losant...");

  device.connectSecure(wifiClient, LOSANT_ACCESS_KEY, LOSANT_ACCESS_SECRET);

  // For an unsecure connection.
  // device.connect(wifiClient, ACCESS_KEY, ACCESS_SECRET);

  while (!device.connected()) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("Connected successfully");
}

void setup() {
  Serial.begin(115200);
  while (!Serial) {
    // wait until Serial is initialized
  }

  // Register the command handler to be called when a command is received
  // from the Losant platform.
  device.onCommand(&handleCommand);

  // connects to WiFi
  connect();
}

void sendKeyCode() {
  // Losant uses a JSON protocol. Construct the simple state object.
  // { "button" : true }
  StaticJsonBuffer<200> jsonBuffer;
  JsonObject &root = jsonBuffer.createObject();
  // set the keycode
  root["keycode"] = input;

  // Send the state to Losant.
  device.sendState(root);
  Serial.println("Combination send");
}

void loop() {
  bool toReconnect = false;

  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("Disconnected from WiFi");
    toReconnect = true;
  }

  if (!device.connected()) {
    Serial.println("Disconnected from Losant");
    Serial.println(device.mqttClient.state());
    toReconnect = true;
  }

  if (toReconnect) {
    connect();
  }

  device.loop();

  char customKey = keypad.getKey();

  if (customKey) {
    if (customKey == '*') {
      // clear the current input
      Serial.println("Pressed *, clearing key code");
      input = "";
    } else if (customKey == '#') {
      // send the input and resets it
      Serial.println("Pressed #, sending key code");
      sendKeyCode();
      input = "";
    } else {
      Serial.println();
      Serial.print("Pressed: ");
      Serial.println(customKey);

      // add the current pressed key
      input += customKey;

      // print keycode combination
      Serial.print("Combination entered: ");
      Serial.println(input);
    }
  }
}

Project is available in GitHub

git clone https://github.com/beastovest/keypad.git

Connected to your ESP8266, on the right in Platform IO there is an arrow button > with tooltip Upload, press it, the upload should take few seconds

In case you get similar message

/dev/ttyUSB0: Access denied

You need to give rights to your current user to read ttyUSB0 port

 

If you have any questions or suggestions, feel free to leave a comment.

Become a Patron!