Tinkers Projects

Imagine | Develop | Create

Torch V5

Categories: Lighting
Torch V5Main
Torch V50
Torch V51
Torch V52

Torch V5

Categories: Lighting
This is version 5 of the torch module with power-down switch. The power-down switch allows the module to power down and not use any power from the battery. This makes the battery last longer. The power-down switch is made of 3 transistors and is activated by the press of the button. it is deactivated by the microcontroller switching itself off. Once the device is switched off, it cannot re-activated itself but required a user to press the button again.

Code for Project

GNU General Public License v3.0
#include <ArduinoJson.h>
#include <EEPROM.h>
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClientSecureBearSSL.h>

#define EnPin 13
#define LightPin 14
#define ButtonPin 12

String URL="https://project2.tinkersprojects.com/api.php";
String ApiKey ="add api key here";
String ApiSecret ="add secret key here";
String IotID ="add IoT ID here";
String LightData = "[{\"light\":1023},{\"light\":512},{\"light\":255}]";

bool LightOn = true;
int  LightFuntion = 0;
int  LightSubFuntion = 0;
unsigned long LastTime = 0;

// Fingerprint for demo URL, expires on June 2, 2021, needs to be updated well before this date
const uint8_t fingerprint[20] = {0x40, 0xaf, 0x00, 0x6b, 0xec, 0x90, 0x22, 0x41, 0x8e, 0xa3, 0xad, 0xfa, 0x1a, 0xe8, 0x25, 0x41, 0x1d, 0x1a, 0x54, 0xb3};
ESP8266WiFiMulti wifiMulti;

const size_t capacity = 512;
DynamicJsonDocument doc(capacity);

void setup() 
{
  delay(3000);
  Serial.begin(115200);
  Serial.println("started");
  pinMode(LightPin, OUTPUT);
  pinMode(EnPin, OUTPUT);
  pinMode(ButtonPin, INPUT);
  digitalWrite(EnPin, HIGH);

  WiFi.mode(WIFI_OFF);
  LightData = readString();

  DeserializationError error = deserializeJson(doc, LightData);
  if (error) 
  {
    Serial.print(F("deserializeJson() failed: "));
    Serial.println(error.c_str());
    connectToWiFi();
  }    
    Serial.print("LightData:");
    Serial.println(LightData); 
}

void loop() 
{
    Serial.println("LOOP");
  if(LightOn)
  {
    Serial.println("ON");
    digitalWrite(EnPin, HIGH);
  }
  else
  {
    Serial.println("OFF");
    digitalWrite(EnPin, LOW);
  }
  

  if(digitalRead(ButtonPin) == HIGH)
  {
    LastTime = millis();
    LightSubFuntion = 0;
    LightFuntion++;
    delay(100);
    while(digitalRead(ButtonPin) == HIGH)
    {
      if(LastTime + 5000 < millis())
      {
        digitalWrite(LightPin, LOW);
        delay(100);
        digitalWrite(LightPin, HIGH);
        delay(100);
        digitalWrite(LightPin, LOW);
        delay(100);
        digitalWrite(LightPin, HIGH);
        delay(100);
        analogWrite(LightPin, 80);

        connectToWiFi();
        LightOn = false;
      }
      functions();
    }
  }

  functions();
}

void functions()
{
  if(!doc.as<JsonObject>().isNull() && doc.containsKey("light") && LightFuntion == 0)
  {
    analogWrite(LightPin,doc["light"]);
    Serial.print("Light signal:");
    Serial.println(doc["light"].as<String>());
  }
  else if(LightFuntion < doc.size() && !(doc.as<JsonArray>()).isNull())
  {
    if(doc[LightFuntion].containsKey("light"))
    {
      analogWrite(LightPin,doc[LightFuntion]["light"]);
      Serial.print("Light Array:");
      Serial.print(LightFuntion);
      Serial.print(",");
      Serial.println(doc[LightFuntion]["light"].as<String>());
    }
    else if( LightFuntion < doc[LightFuntion].size() && !(doc[LightFuntion].as<JsonArray>()).isNull() && doc[LightFuntion][LightSubFuntion].containsKey("light") && doc[LightFuntion][LightSubFuntion].containsKey("delay"))
    {
      
      Serial.print("Light Funuction:");
      Serial.print(LightFuntion);
      Serial.print(",");
      Serial.print(LightSubFuntion);
      Serial.print(",");
      Serial.println(doc[LightFuntion][LightSubFuntion]["light"].as<String>());
      
      analogWrite(LightPin,doc[LightFuntion][LightSubFuntion]["light"]);
      long delay = doc[LightFuntion][LightSubFuntion]["delay"];
      if(LastTime+delay < millis())
      {
        LightSubFuntion++;
        LastTime = millis();
      }
    }
    else
    {
      LightSubFuntion=0;
    }
  }
  else
  {
    LightOn = false;
  }
  
  

  /*doc.containsKey("city")
                doc.size();
                int id = doc["id"]; // 1
                const char* name = doc["name"]; // "Leanne Graham"
                const char* username = doc["username"]; // "Bret"
                const char* email = doc["email"]; // "Sincere@april.biz"*/


}



void connectToWiFi()
{
  WiFi.mode(WIFI_STA);
  wifiMulti.addAP("wifi", "password");
  wifiMulti.addAP("wifi", "password");
  wifiMulti.addAP("wifi", "password");

  Serial.println("Connecting Wifi...");
  delay(3000);
  unsigned long startTestComs = millis();
  while(wifiMulti.run() != WL_CONNECTED && startTestComs+3000>millis())
  {
    Serial.println("WiFi not connected!");
    delay(100);
  }
    Serial.println("finished!");
  
  if (wifiMulti.run() == WL_CONNECTED) 
  {
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
    postData();
  }
  WiFi.mode(WIFI_OFF);
}



bool postData() 
{
    std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
    //client->setFingerprint(fingerprint);
    client->setInsecure();
    
    HTTPClient http;
    if(http.begin(*client,URL))
    {
      http.addHeader("Content-Type", "application/json");
      http.addHeader("Accept", "application/json");
      http.addHeader("HTTP_ACCEPT", "application/json");
      
  
      int httpCode = http.POST("{\"ApiKey\":\""+ApiKey+"\",\"ApiSecret\":\""+ApiSecret+"\",\"Iot\":{\"Id\":"+IotID+"}}");
       
       if (httpCode > 0)
      {
          Serial.printf("[HTTP] POST... code: %d\n", httpCode);
          Serial.println(http.getString());
          if(httpCode == HTTP_CODE_OK) 
          {
              DeserializationError error = deserializeJson(doc, http.getString());
              if (error) 
              {
                Serial.print(F("deserializeJson() failed: "));
                Serial.println(error.c_str());
                return false;
              }
              if(doc.containsKey("success") && doc.containsKey("Iot") && (doc["success"]==true || doc["success"]=="true"))
              {
                if(doc["Iot"].containsKey("Data") && doc["Iot"]["Data"].containsKey("data") )
                {
                  LightData = doc["Iot"]["Data"]["data"].as<String>();
                  Serial.println(LightData);
                }
              }              
              http.end();
              return true;
          }
      } 
      else 
      {
          Serial.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str());
          Serial.println(http.getString());
      }
      
      http.end();
    } 
    else 
    {
      Serial.printf("[HTTPS] Unable to connect\n");
    }
    return false;
}






void writeString(String data)
{
  int stringSize = data.length();
  int address = sizeof(stringSize);
  EEPROM.put(0, stringSize);

  for(int i=0;i<data.length();i++)
  {
    EEPROM.write(address+i, data.charAt(i));
  }
}

String readString()
{
  int stringSize=0;
  EEPROM.get( 0, stringSize );

  if(stringSize<=0)
    return LightData;

  int address = sizeof(stringSize);
  String data = "";
  for (int i = 0; i < stringSize; i++)
  {
    data += String((char)EEPROM.read(address + i));
  }

  if(data == "")
    return LightData;

  return data;
}
This is version 5 of the torch module with power-down switch. The power-down switch allows the module to power down and not use any power from the battery. This makes the battery last longer. The power-down switch is made of 3 transistors and is activated by the press of the button. it is deactivated by the microcontroller switching itself off. Once the device is switched off, it cannot re-activated itself but required a user to press the button again.

Related Projects