Torch V5

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;
}

Related Projects

Torch V4

Torch V4

This is a version of the torch module is a module that can be placed anywhere. The module does not have a LED or switch on the PCB but instead has 2 input pins and 2 output pins. These pins are used for the switch and the LED. To make more room in the front of the torch this module is made to be placed elsewhere, away from the LED.
Read more


Torch V3

Torch V3

This is a version of the torch module to test the shape and the power of the LED. This module is a similar shape to a star LED. Star LED is used in lots of different torches and I wanted to see if I can change one of these LEDs to this module. The will allow me to have a lot of control of the functions of the touch.
Read more


Torch V2 WiFi

Torch V2 WiFi

Every torch has set light and function setting but this module changes that. But allowing the torch module to access the internet or your mobile device, it opens the device for change. This torch module is the second version and it will be continued to be developed. Most of the time the torch will ack like any other torch, it has set lighting and function settings. When the WiFi is enabled, …
Read more


Torch V1 - Bluetooth

Torch V1 - Bluetooth

I had an idea a while ago to make a torch with more control. I wanted more control over the lighting, functions and order of a torch. I thought by adding Bluetooth, this device can be programmed from a phone or computer. Many people have said that adding Bluetooth to a touch is pointless until they knew that it was for programming the lighting not controlling the device. This means that the …
Read more


Torch_LED Library

Torch_LED Library

These are libraries for a torch that can do different functions. Each version is similar to each other with updated functionality and control. Torch_LED_V1 Torch_LED_V1 is the first library for the control of light functions within torches. There can be any number of functions that can be used to control the torch LEDs. There are 7 built-in functions within the library that can be used and 6 …
Read more


Latest Projects

Popular Projects