Igor Fonseca Albuquerque
Published © CC BY-NC-SA

IoT Smart Wallet (with Firebeetle ESP32 and Arduino IDE)

This wallet can connect the internet, read the value of your cryptocurrencies from a Google spreadsheet and even work as a pedometer!

IntermediateFull instructions provided4 hours6,564
IoT Smart Wallet (with Firebeetle ESP32 and Arduino IDE)

Things used in this project

Hardware components

ESP32S
Espressif ESP32S
×1
DFRobot Firebeetle ESP32
×1
0.96'' OLED display
×1
GY-521 MPU-6050
×1

Software apps and online services

Arduino IDE
Arduino IDE
Fusion 360
Autodesk Fusion 360

Hand tools and fabrication machines

3D Printer (generic)
3D Printer (generic)
3D Printer (generic)
3D Printer (generic)
Anet A8

Story

Read more

Code

walliot-v1-0.ino

Arduino
Arduino code with Google spreadsheet + deepsleep + quotes
// ----------------------------
// Add libraries
// ----------------------------
#include <WiFi.h>             // Library for Wi-Fi
#include <WiFiMulti.h>        // Library for multiple Wi-Fi connections
#include <WiFiClientSecure.h> // Library for creating a https client
#include <ArduinoJson.h>      // Library for reading data from json
#include <Wire.h>             // Library for I2C communication to OLED display
#include "esp_deep_sleep.h"   // Library for ESP32 deep sleep
#include "SH1106.h"           // Library for OLED display (https://github.com/squix78/esp8266-oled-ssd1306)

// ----------------------------
// Configurations
// ----------------------------
// The following will have to be updated according to your hardware and accounts
// ------------------------------------------------------------------------------------

const char* ssid1     = "XXXXXX";    // Wi-Fi router SSID
const char* password1 = "YYYYYY"; // Wi-Fi router  password

const char* ssid2     = "XXXXXX";       // Wi-Fi rounter SSID
const char* password2 = "YYYYYY";   // Wi-Fi router password

String spreadSheetID = "ZZZZZZ";  // ID from Google spreadsheet
String key = "?key=WWWWWW";            // Google API key

const size_t bufferSize = JSON_ARRAY_SIZE(1) + JSON_ARRAY_SIZE(5) + JSON_OBJECT_SIZE(3) + 100;  // buffer for json message

#define SCL_PIN D5 // ESP32 pin connected to OLED display SCL pin
#define SDA_PIN D3 // ESP32 pin connected to OLED display SDA pin

#define Threshold 400   // Touch sensor sensitivity


// ----------------------------

String getString = "GET /v4/spreadsheets/" + spreadSheetID + "/values/"; 

WiFiMulti WiFiMulti;

WiFiClientSecure wificlient; // Create https client

SH1106 display(0x3c, SDA_PIN, SCL_PIN); // Start OLED display
  
RTC_DATA_ATTR int bootCount = 0; // Store boot count

String array[] = { 
  "The safe way to double\nyour money is to fold it\nover once and put it in\nyour pocket\n- Kin Hubbard", 
  "Be saving, but not at the\ncost of all liberality. Have\nthe soul of a king and the\nhand of a wise economist.\n- Joseph Joubert",
  "Look everywhere you can\nto cut a little bit from your\nexpenses. It will all add up\nto a meaningful sum.\n- Suze Orman", 
  "The quickest way to\ndouble your money is to\nfold it in half and put it in\nyour back pocket.\n- Will Rogers",
  "A budget is telling your\nmoney where to go instead\nof wondering where it went\n- John C. Maxwell",
  "You must learn to save\nfirst and spend afterwards.\n- John Poole",
  "Balancing your money is\nthe key to having enough.\n- Elizabeth Warren",
  "Saving must become a\npriority, not just a thought.\nPay yourself first.\n- Dave Ramsey",
  "By definition, saving for\nanything requires us to not\nget things now so that we\ncan get bigger ones later.\n- Jean Chatzky",
  "The art is not in making\nmoney, but in keeping it.\n- Anonymous",
  "He who will not economize\nwill have to agonize.\n- Confucius",
  "The easiest way to save\nmoney is to waste less\nenergy.\n- Barack Obama",
  "A simple fact that is hard\nto learn is that the time to\nsave money is when you\nhave some.\n- Joe Moore",
  "Saving is a very fine thing.\nEspecially when your\nparents have done it\nfor you.\n- Winston Churchill",
  "Money looks better in the\nbank than on your feet.\n- Sophia Amoruso",
  "Wealth consists not in\nhaving great possessions,\nbut in having few wants.\n- Epictetus",
  "If we command our wealth,\nwe shall be rich and free.\nIf our wealth commands\nus, we are poor indeed.\n- Edmund Burke",
  "When a man has learned\nto live without money, he\nthought, a few rubles can\ngo a long way.\n- Dan Millman",
  "Spend not where you may\nsave; spare not where you\nmust spend.\n- John Ray",
  "Save a little money each\nmonth and at the end of\nthe year you'll be surprised\nat how little you have.\n- Ernest Haskins",
  "A man is usually more\ncareful of his money than\nhe is of his principles.\n- Ralph Waldo Emerson",
  "If you can count your\nmoney,you don't have\na billion dollars.\n- J. Paul Getty",
  "There is a gigantic\ndifference between\nearning a great deal of\nmoney and being rich.\n- Marlene Dietrich",
  "Saving requires us to not\nget things now so that we\ncan get bigger ones later.\n- Jean Chatzky",
  "Never spend your money\nbefore you have earned it.\n- Thomas Jefferson",
  "All days are not same.\nSave for a rainy day. When\nyou dont work, savings\nwill work for you.\n- M.K. Soni",
  "A penny saved is\na penny earned.\n- Benjamin Franklin",
  "If you cannot save\nmoney, the seeds of\ngreatness are not in you.\n- W. Clement Stone",
  "A man who both spends\nand saves money is the\nhappiest man, because\nhe has both enjoyments.\n- Samuel Johnson",
  "You must gain control\nover your money or the\nlack of it will forever\ncontrol you.\n- Lydia Sweatt",
  "Saving comes too late\nwhen you get to the\nbottom.\n- Seneca",
  "Stop buying things\nyou don't need to\nimpress people you\ndon't even like.\n- Suze Orman",
  "A man is rich in\nproportion to the things\nhe can afford to let alone.\n- Henry David Thoreau",
  "Beware of little expenses.\nA small leak will sink a\ngreat ship.\n- Benjamin Franklin",
  "People suddenly know\nhow to use money when\nthere are none left.\n- Bangambiki Habyarimana",
  "Save one-third,\nlive on one-third,\nand give away one-third.\n- Angelina Jolie",
  "Do not save what is\nleft after spending,\nbut spend what is left\nafter saving.\n- Warren Buffet",
  "If you would be wealthy,\nthink of saving as well\nas getting.\n- Benjamin Franklin",
  "A wise person should\nhave money in their head,\nbut not in their heart.\n- Jonathan Swift",
  "Money is usually attracted,\nnot pursued.\n- Jim Rohn",
  "Many folks think they\narent good at earning\nmoney, when what they\ndont know is how to use it.\n- Frank A. Clark",
  "That's 49 cents of milk\nspilt over the table!\nSomebody's gonna drink\nthat!\n- Julius Rock",
};

// ----------------------------
// Setup
// ----------------------------

void setup() {

  Serial.begin(115200); // Start serial communication

  // Initialising the display
  display.init();
  display.clear();
  display.displayOn();
  display.flipScreenVertically();
  display.setTextAlignment(TEXT_ALIGN_CENTER);
  display.setFont(ArialMT_Plain_16);
  display.drawString(64, 0, F("IoT wallet"));
  display.setFont(ArialMT_Plain_10);
  display.drawString(64, 18, F("By igorF2"));
  display.display();

  delay(500);
  display.clear();
  display.setTextAlignment(TEXT_ALIGN_CENTER);
  display.setFont(ArialMT_Plain_10);
  display.drawString(64, 0, array[random(0, 41)]);
  display.display();

  // Increment boot number and print it every reboot
  ++bootCount;
  Serial.println("Boot number: " + String(bootCount));
  
  Connect_to_Wifi(); // Connect Wi-Fi network
  delay(100);

  touchAttachInterrupt(T0, callback, Threshold);  // Enable touch sensor wake up
  esp_deep_sleep_enable_touchpad_wakeup();        // Enable touch sensor wake up

  btStop(); // Turn off bluetooth for saving battery
}



// ----------------------------
// Main Loop
// ----------------------------

void loop() {

  Serial.println("Reading Google Spreadsheet data...");
  readGoogleSheet(); // Read Google Sheet data and display on OLED display

  Serial.println("Going to sleep now...");
  display.displayOff();
  esp_deep_sleep_start(); // Start sleeping
  WiFi.mode(WIFI_OFF); //turn off WiFi for saving battery  
}

// ----------------------------


// ----------------------------
// Auxiliary functions
// ----------------------------

// Connect Wi-Fi network
void Connect_to_Wifi()
{

  // We start by connecting to a WiFi network
  WiFiMulti.addAP(ssid1, password1);
  WiFiMulti.addAP(ssid2, password2);

  Serial.println();
  Serial.print("Wait for WiFi... ");

  String displayText = "connecting";
  while (WiFiMulti.run() != WL_CONNECTED) {
    Serial.print(".");
    displayText += ".";
    display.clear();
    display.setTextAlignment(TEXT_ALIGN_CENTER);
    display.setFont(ArialMT_Plain_10);
    display.drawString(64, 0, displayText);
    delay(100);
  }

  // Display IP if connection successful
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

}


// Executed when touch sensor activated
void callback(){
  // placeholder callback function
  
  Serial.println("touch");
  //WiFi.mode(WIFI_ON); //turn off WiFi for saving battery
}


// Read Google Spreadsheet values and update OLED display
void readGoogleSheet(){
  boolean empty = false; // identifies if the last entry of the spreadsheet was read
  int row = 2; // row of the spreadsheet to be read
  while (!empty) {
    if (wificlient.connect("sheets.googleapis.com", 443) == true) // Try to connect Google APIs server at port 443 (https)
    {
        String toSend = getString; // GET string to be sent (columns from A to E)
        toSend += "A";
        toSend += row;
        toSend += ":";
        toSend += "E";
        toSend += row;
        
        // Cells to be read from the spreadsheet
        toSend += key; // Add API key
        toSend += " HTTP/1.1"; // End of GET instruction

        wificlient.println(toSend); // Send GET to server
        wificlient.println("Host: sheets.googleapis.com");
        wificlient.println();

        // Check HTTP status
        char status[32] = {0};
        wificlient.readBytesUntil('\r', status, sizeof(status));
        if (strcmp(status, "HTTP/1.1 200 OK") != 0) {
          Serial.print(F("Unexpected response: "));
          Serial.println(status);
          return;
        }

        // Skip HTTP headers
        char endOfHeaders[] = "\r\n\r\n";
        if (!wificlient.find(endOfHeaders)) {
          Serial.println(F("Invalid response"));
          return;
        }
        wificlient.readBytesUntil('\r', status, sizeof(status));

        // Create buffer
        DynamicJsonBuffer jsonBuffer(bufferSize);

        // Store values and convert to float
        JsonObject& root = jsonBuffer.parseObject(wificlient);
        String currency = root["values"][0][0];
        String amountStr = root["values"][0][1];
        String tickerStr = root["values"][0][2];
        String valueStr = root["values"][0][3];
        String changeStr = root["values"][0][4];
        float amount = amountStr.toFloat();
        float ticker = tickerStr.toFloat();
        float value = valueStr.toFloat();
        float change = changeStr.toFloat();

        // Update display
        if (currency != "") {
          Serial.println("Response:");
          Serial.println(currency);
          Serial.println(amount);
          Serial.println(ticker);
          Serial.println(value);
          Serial.println(change);

          display.clear();
          display.setTextAlignment(TEXT_ALIGN_CENTER);
          display.setFont(ArialMT_Plain_10);
          display.drawString(64, 0, String(amount) + currency);
          display.setFont(ArialMT_Plain_16);
          display.drawString(64, 20, String(value,2) + "BRL");
          display.setFont(ArialMT_Plain_10);
          display.setTextAlignment(TEXT_ALIGN_CENTER);
          display.drawString(64, 48, String(ticker,2) + "BRL"+"/"+currency+" ("+change+")");
          display.display();
        }
        else {
          empty = true;
        }
        wificlient.stop();  // Stop connection to the server
      }
      else
      {
        Serial.println("Connection failured");
      }
      row++;
    }
}

walliot-v0-0.ino

Arduino
Code for wallet with Google spreadsheet + deepsleep
// ----------------------------
// Add libraries
// ----------------------------
#include <WiFi.h>             // Library for Wi-Fi
#include <WiFiMulti.h>        // Library for multiple Wi-Fi connections
#include <WiFiClientSecure.h> // Library for creating a https client
#include <ArduinoJson.h>      // Library for reading data from json
#include <Wire.h>             // Library for I2C communication to OLED display
#include "esp_deep_sleep.h"   // Library for ESP32 deep sleep
#include "SH1106.h"           // Library for OLED display (https://github.com/squix78/esp8266-oled-ssd1306)

// ----------------------------
// Configurations
// ----------------------------

const char* ssid1     = "XXXXXX";    // Wi-Fi router SSID
const char* password1 = "YYYYYY"; // Wi-Fi router  password

const char* ssid2     = "XXXXXX";       // Wi-Fi rounter SSID
const char* password2 = "YYYYYY";   // Wi-Fi router password

String spreadSheetID = "ZZZZZZ";  // ID from Google spreadsheet
String key = "?key=WWWWWW";            // Google API key

const size_t bufferSize = JSON_ARRAY_SIZE(1) + JSON_ARRAY_SIZE(5) + JSON_OBJECT_SIZE(3) + 100;  // buffer for json message

#define SCL_PIN D5 // ESP32 pin connected to OLED display SCL pin
#define SDA_PIN D3 // ESP32 pin connected to OLED display SDA pin

#define Threshold 400   // Touch sensor sensitivity



// ----------------------------

String getString = "GET /v4/spreadsheets/" + spreadSheetID + "/values/"; 

WiFiMulti WiFiMulti;

WiFiClientSecure wificlient; // Create https client

SH1106 display(0x3c, SDA_PIN, SCL_PIN); // Start OLED display
  
RTC_DATA_ATTR int bootCount = 0; // Store boot count


// ----------------------------
// Setup
// ----------------------------

void setup() {

  Serial.begin(115200); // Start serial communication

  // Initialising the display
  display.init();
  display.clear();
  display.displayOn();
  display.flipScreenVertically();
  display.setTextAlignment(TEXT_ALIGN_CENTER);
  display.setFont(ArialMT_Plain_16);
  display.drawString(64, 0, F("IoT wallet"));
  display.setFont(ArialMT_Plain_10);
  display.drawString(64, 18, F("By igorF2"));
  display.display();

  delay(500);

  // Increment boot number and print it every reboot
  ++bootCount;
  Serial.println("Boot number: " + String(bootCount));
  
  Connect_to_Wifi(); // Connect Wi-Fi network
  delay(100);

  touchAttachInterrupt(T0, callback, Threshold);  // Enable touch sensor wake up
  esp_deep_sleep_enable_touchpad_wakeup();        // Enable touch sensor wake up

  btStop(); // Turn off bluetooth for saving battery
}



// ----------------------------
// Main Loop
// ----------------------------

void loop() {

  Serial.println("Reading Google Spreadsheet data...");
  readGoogleSheet(); // Read Google Sheet data and display on OLED display

  Serial.println("Going to sleep now...");
  display.displayOff();
  esp_deep_sleep_start(); // Start sleeping
  WiFi.mode(WIFI_OFF); //turn off WiFi for saving battery

  
}

// ----------------------------


// ----------------------------
// Auxiliary functions
// ----------------------------

// Connect Wi-Fi network
void Connect_to_Wifi()
{

  // We start by connecting to a WiFi network
  WiFiMulti.addAP(ssid1, password1);
  WiFiMulti.addAP(ssid2, password2);

  Serial.println();
  Serial.print("Wait for WiFi... ");

  String displayText = "connecting";
  while (WiFiMulti.run() != WL_CONNECTED) {
    Serial.print(".");
    displayText += ".";
    display.clear();
    display.setTextAlignment(TEXT_ALIGN_CENTER);
    display.setFont(ArialMT_Plain_10);
    display.drawString(64, 0, displayText);
    delay(100);
  }

  // Display IP if connection successful
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

}


// Executed when touch sensor activated
void callback(){
  // placeholder callback function
  
  Serial.println("touch");
  //WiFi.mode(WIFI_ON); //turn off WiFi for saving battery
}


// Read Google Spreadsheet values and update OLED display
void readGoogleSheet(){
  boolean empty = false; // identifies if the last entry of the spreadsheet was read
  int row = 2; // row of the spreadsheet to be read
  while (!empty) {
    if (wificlient.connect("sheets.googleapis.com", 443) == true) // Try to connect Google APIs server at port 443 (https)
    {
        String toSend = getString; // GET string to be sent (columns from A to E)
        toSend += "A";
        toSend += row;
        toSend += ":";
        toSend += "E";
        toSend += row;
        
        // Cells to be read from the spreadsheet
        toSend += key; // Add API key
        toSend += " HTTP/1.1"; // End of GET instruction

        wificlient.println(toSend); // Send GET to server
        wificlient.println("Host: sheets.googleapis.com");
        wificlient.println();

        // Check HTTP status
        char status[32] = {0};
        wificlient.readBytesUntil('\r', status, sizeof(status));
        if (strcmp(status, "HTTP/1.1 200 OK") != 0) {
          Serial.print(F("Unexpected response: "));
          Serial.println(status);
          return;
        }

        // Skip HTTP headers
        char endOfHeaders[] = "\r\n\r\n";
        if (!wificlient.find(endOfHeaders)) {
          Serial.println(F("Invalid response"));
          return;
        }
        wificlient.readBytesUntil('\r', status, sizeof(status));

        // Create buffer
        DynamicJsonBuffer jsonBuffer(bufferSize);

        // Store values and convert to float
        JsonObject& root = jsonBuffer.parseObject(wificlient);
        String currency = root["values"][0][0];
        String amountStr = root["values"][0][1];
        String tickerStr = root["values"][0][2];
        String valueStr = root["values"][0][3];
        String changeStr = root["values"][0][4];
        float amount = amountStr.toFloat();
        float ticker = tickerStr.toFloat();
        float value = valueStr.toFloat();
        float change = changeStr.toFloat();

        // Update display
        if (currency != "") {
          Serial.println("Response:");
          Serial.println(currency);
          Serial.println(amount);
          Serial.println(ticker);
          Serial.println(value);
          Serial.println(change);

          display.clear();
          display.setTextAlignment(TEXT_ALIGN_CENTER);
          display.setFont(ArialMT_Plain_10);
          display.drawString(64, 0, String(amount) + currency);
          display.setFont(ArialMT_Plain_16);
          display.drawString(64, 20, String(value,2) + "BRL");
          display.setFont(ArialMT_Plain_10);
          display.setTextAlignment(TEXT_ALIGN_CENTER);
          display.drawString(64, 48, String(ticker,2) + "BRL"+"/"+currency+" ("+change+")");
          display.display();
        }
        else {
          empty = true;
        }
        wificlient.stop();  // Stop connection to the server
      }
      else
      {
        Serial.println("Connection failured");
      }
      row++;
    }
}

walliot-v2-0.ino

Arduino
Arduino code with Google spreadsheet + deepsleep + quotes + clock
// ----------------------------
// Add libraries
// ----------------------------
#include <WiFi.h>             // Library for Wi-Fi
#include <WiFiMulti.h>        // Library for multiple Wi-Fi connections
#include <WiFiClientSecure.h> // Library for creating a https client
#include <ArduinoHttpClient.h>// Library for crating a http client
#include <ArduinoJson.h>      // Library for reading data from json
#include <Wire.h>             // Library for I2C communication to OLED display and Accelerometer
#include "SH1106.h"           // Library for OLED display (https://github.com/squix78/esp8266-oled-ssd1306)


// ------------------------------------------------------------------------------------
// Configurations
// ------------------------------------------------------------------------------------
// The following will have to be updated according to your hardware and accounts
// ------------------------------------------------------------------------------------

// Wi-Fi network
const char* ssid1     = "XXXXXX";    // Wi-Fi router SSID
const char* password1 = "YYYYYY"; // Wi-Fi router  password
const char* ssid2     = "XXXXXX";       // Wi-Fi rounter SSID
const char* password2 = "YYYYYY";   // Wi-Fi router password

// Hardware
#define SCL_PIN D5 // ESP32 pin connected to OLED display SCL pin
#define SDA_PIN D3 // ESP32 pin connected to OLED display SDA pin

// Google API
String spreadSheetID = "ZZZZZZ";  // ID from Google spreadsheet
String key = "?key=WWWWWW";            // Google API key
const size_t bufferSize = JSON_ARRAY_SIZE(1) + JSON_ARRAY_SIZE(5) + JSON_OBJECT_SIZE(3) + 100;  // buffer for json message
String getString = "GET /v4/spreadsheets/" + spreadSheetID + "/values/"; 

// Other
#define Threshold 400   // Touch sensor sensitivity
#define TIMEZONE  3 // Current time zone. Used for correction of server time

// ----------------------------

// ----------------------------
// Global variables
// ----------------------------

// Time
String TimeDate = ""; // Variable used to store the data received from the server
int hours; // Current hour
int minutes; // Current minute
int seconds; // Current second
int seconds0;

// WiFi
WiFiMulti WiFiMulti;
WiFiClientSecure wificlient; // Create https client

// Display
SH1106 display(0x3c, SDA_PIN, SCL_PIN); // Start OLED display

// Flags
boolean googleIt = false;

// Quotes
String array[] = { 
  "The safe way to double\nyour money is to fold it\nover once and put it in\nyour pocket\n- Kin Hubbard", 
  "Be saving, but not at the\ncost of all liberality. Have\nthe soul of a king and the\nhand of a wise economist.\n- Joseph Joubert",
  "Look everywhere you can\nto cut a little bit from your\nexpenses. It will all add up\nto a meaningful sum.\n- Suze Orman", 
  "The quickest way to\ndouble your money is to\nfold it in half and put it in\nyour back pocket.\n- Will Rogers",
  "A budget is telling your\nmoney where to go instead\nof wondering where it went\n- John C. Maxwell",
  "You must learn to save\nfirst and spend afterwards.\n- John Poole",
  "Balancing your money is\nthe key to having enough.\n- Elizabeth Warren",
  "Saving must become a\npriority, not just a thought.\nPay yourself first.\n- Dave Ramsey",
  "By definition, saving for\nanything requires us to not\nget things now so that we\ncan get bigger ones later.\n- Jean Chatzky",
  "The art is not in making\nmoney, but in keeping it.\n- Anonymous",
  "He who will not economize\nwill have to agonize.\n- Confucius",
  "The easiest way to save\nmoney is to waste less\nenergy.\n- Barack Obama",
  "A simple fact that is hard\nto learn is that the time to\nsave money is when you\nhave some.\n- Joe Moore",
  "Saving is a very fine thing.\nEspecially when your\nparents have done it\nfor you.\n- Winston Churchill",
  "Money looks better in the\nbank than on your feet.\n- Sophia Amoruso",
  "Wealth consists not in\nhaving great possessions,\nbut in having few wants.\n- Epictetus",
  "If we command our wealth,\nwe shall be rich and free.\nIf our wealth commands\nus, we are poor indeed.\n- Edmund Burke",
  "When a man has learned\nto live without money, he\nthought, a few rubles can\ngo a long way.\n- Dan Millman",
  "Spend not where you may\nsave; spare not where you\nmust spend.\n- John Ray",
  "Save a little money each\nmonth and at the end of\nthe year you'll be surprised\nat how little you have.\n- Ernest Haskins",
  "A man is usually more\ncareful of his money than\nhe is of his principles.\n- Ralph Waldo Emerson",
  "If you can count your\nmoney,you don't have\na billion dollars.\n- J. Paul Getty",
  "There is a gigantic\ndifference between\nearning a great deal of\nmoney and being rich.\n- Marlene Dietrich",
  "Saving requires us to not\nget things now so that we\ncan get bigger ones later.\n- Jean Chatzky",
  "Never spend your money\nbefore you have earned it.\n- Thomas Jefferson",
  "All days are not same.\nSave for a rainy day. When\nyou dont work, savings\nwill work for you.\n- M.K. Soni",
  "A penny saved is\na penny earned.\n- Benjamin Franklin",
  "If you cannot save\nmoney, the seeds of\ngreatness are not in you.\n- W. Clement Stone",
  "A man who both spends\nand saves money is the\nhappiest man, because\nhe has both enjoyments.\n- Samuel Johnson",
  "You must gain control\nover your money or the\nlack of it will forever\ncontrol you.\n- Lydia Sweatt",
  "Saving comes too late\nwhen you get to the\nbottom.\n- Seneca",
  "Stop buying things\nyou don't need to\nimpress people you\ndon't even like.\n- Suze Orman",
  "A man is rich in\nproportion to the things\nhe can afford to let alone.\n- Henry David Thoreau",
  "Beware of little expenses.\nA small leak will sink a\ngreat ship.\n- Benjamin Franklin",
  "People suddenly know\nhow to use money when\nthere are none left.\n- Bangambiki Habyarimana",
  "Save one-third,\nlive on one-third,\nand give away one-third.\n- Angelina Jolie",
  "Do not save what is\nleft after spending,\nbut spend what is left\nafter saving.\n- Warren Buffet",
  "If you would be wealthy,\nthink of saving as well\nas getting.\n- Benjamin Franklin",
  "A wise person should\nhave money in their head,\nbut not in their heart.\n- Jonathan Swift",
  "Money is usually attracted,\nnot pursued.\n- Jim Rohn",
  "Many folks think they\narent good at earning\nmoney, when what they\ndont know is how to use it.\n- Frank A. Clark",
  "That's 49 cents of milk\nspilt over the table!\nSomebody's gonna drink\nthat!\n- Julius Rock",
};


// ----------------------------
// Setup
// ----------------------------
void setup() {

  Serial.begin(115200); // Start serial communication

  // Initializing the display
  display.init();
  display.clear();
  display.displayOn();
  display.flipScreenVertically();
  display.setTextAlignment(TEXT_ALIGN_CENTER);
  display.setFont(ArialMT_Plain_16);
  display.drawString(64, 0, F("IoT wallet"));
  display.setFont(ArialMT_Plain_10);
  display.drawString(64, 18, F("By igorF2"));
  display.display();

  // Connect Wi-Fi network
  Connect_to_Wifi(); 
  delay(100);

  touchAttachInterrupt(T0, callback, Threshold);  // Enable touch sensor wake up

  getTime();
  showTime();
  seconds0 = millis();
  
  btStop(); // Turn off bluetooth for saving battery 
}



// ----------------------------
// Main Loop
// ----------------------------

void loop() {

  if ((millis() - seconds0) > 60000) {
      Connect_to_Wifi();
      getTime();
      // display clock
      showTime();
      seconds0 = millis();
      WiFi.mode(WIFI_OFF); //turn off WiFi for saving battery
      Serial.println("WiFi disabled...");
  }
  
  if (googleIt == true) {
    display.clear();
    display.setTextAlignment(TEXT_ALIGN_CENTER);
    display.setFont(ArialMT_Plain_10);
    display.drawString(64, 20, "Connecting...");
    showTime();
    display.display();
    Connect_to_Wifi();
    display.clear();
    display.setTextAlignment(TEXT_ALIGN_CENTER);
    display.setFont(ArialMT_Plain_10);
    display.drawString(64, 0, array[random(0, 41)]);
    display.display();
    delay(2000);
    Serial.println("Reading Google Spreadsheet data...");
    readGoogleSheet(); // Read Google Sheet data and display on OLED display
    googleIt = false;
    WiFi.mode(WIFI_OFF); //turn off WiFi for saving battery
    Serial.println("WiFi disabled...");
  }
}
// ----------------------------


// ----------------------------
// Auxiliary functions
// ----------------------------

// Connect Wi-Fi network
void Connect_to_Wifi()
{
  WiFi.mode(WIFI_STA);
  
  // We start by connecting to a WiFi network
  WiFiMulti.addAP(ssid1, password1);
  WiFiMulti.addAP(ssid2, password2);

  Serial.println();
  Serial.print("Wait for WiFi... ");

  String displayText = "connecting";
  while (WiFiMulti.run() != WL_CONNECTED) {
    Serial.print(".");
    displayText += ".";
    display.clear();
    display.setTextAlignment(TEXT_ALIGN_CENTER);
    display.setFont(ArialMT_Plain_10);
    display.drawString(64, 0, displayText);
    delay(100);
  }

  // Display IP if connection successful
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}


// Executed when touch sensor activated
void callback(){
  // placeholder callback function
  
  Serial.println("touche");
  googleIt = true;
  //WiFi.mode(WIFI_ON); //turn off WiFi for saving battery
}

// Read Google Spreadsheet values and update OLED display
void readGoogleSheet(){
  boolean empty = false; // identifies if the last entry of the spreadsheet was read
  int row = 2; // row of the spreadsheet to be read
  while (!empty) {
    if (wificlient.connect("sheets.googleapis.com", 443) == true) // Try to connect Google APIs server at port 443 (https)
    {
        String toSend = getString; // GET string to be sent (columns from A to E)
        toSend += "A";
        toSend += row;
        toSend += ":";
        toSend += "E";
        toSend += row;
        
        // Cells to be read from the spreadsheet
        toSend += key; // Add API key
        toSend += " HTTP/1.1"; // End of GET instruction

        wificlient.println(toSend); // Send GET to server
        wificlient.println("Host: sheets.googleapis.com");
        wificlient.println();

        // Check HTTP status
        char status[32] = {0};
        wificlient.readBytesUntil('\r', status, sizeof(status));
        if (strcmp(status, "HTTP/1.1 200 OK") != 0) {
          Serial.print(F("Unexpected response: "));
          Serial.println(status);
          return;
        }

        // Skip HTTP headers
        char endOfHeaders[] = "\r\n\r\n";
        if (!wificlient.find(endOfHeaders)) {
          Serial.println(F("Invalid response"));
          return;
        }
        wificlient.readBytesUntil('\r', status, sizeof(status));

        // Create buffer
        DynamicJsonBuffer jsonBuffer(bufferSize);

        // Store values and convert to float
        JsonObject& root = jsonBuffer.parseObject(wificlient);
        String currency = root["values"][0][0];
        String amountStr = root["values"][0][1];
        String tickerStr = root["values"][0][2];
        String valueStr = root["values"][0][3];
        String changeStr = root["values"][0][4];
        float amount = amountStr.toFloat();
        float ticker = tickerStr.toFloat();
        float value = valueStr.toFloat();
        float change = changeStr.toFloat();

        // Update display
        if (currency != "") {
          Serial.println("Response:");
          Serial.println(currency);
          Serial.println(amount);
          Serial.println(ticker);
          Serial.println(value);
          Serial.println(change);

          display.clear();
          display.setTextAlignment(TEXT_ALIGN_CENTER);
          display.setFont(ArialMT_Plain_10);
          display.drawString(64, 0, String(amount) + currency);
          display.setFont(ArialMT_Plain_16);
          display.drawString(64, 20, String(value,2) + "BRL");
          display.setFont(ArialMT_Plain_10);
          display.setTextAlignment(TEXT_ALIGN_CENTER);
          display.drawString(64, 48, String(ticker,2) + "BRL"+"/"+currency+" ("+change+")");
          display.display();
          delay(300);
        }
        else {
          empty = true;
        }
        wificlient.stop();  // Stop connection to the server
      }
      else
      {
        Serial.println("Connection failured");
      }
      row++;
    }
}

//Get current time Google server
void getTime() {

  WiFiClient client;
  while (!!!client.connect("google.com", 80)) {
    Serial.println("connection failed, retrying...");
  }

  client.print("HEAD / HTTP/1.1\r\n\r\n");

  delay(500); //wait a few milisseconds for incoming message

   //if there is an incoming message
   if(client.available()){
     while(client.available()){
       if (client.read() == '\n') {    
         if (client.read() == 'D') {    
           if (client.read() == 'a') {    
             if (client.read() == 't') {    
               if (client.read() == 'e') {    
                 if (client.read() == ':') {    
                   client.read();
                   String theDate = client.readStringUntil('\r');
                   client.stop();

                   TimeDate = theDate.substring(7);
                   Serial.println(TimeDate);
                   // time starts at pos 14
                   String strCurrentHour = theDate.substring(17,19);
                   String strCurrentMinute = theDate.substring(20,22);
                   String strCurrentSecond = theDate.substring(23,25);
                   Serial.println(strCurrentHour);
                   Serial.println(strCurrentMinute);
                   Serial.println(strCurrentSecond);
                   hours = strCurrentHour.toInt();
                   hours = hours - TIMEZONE;
                   if (hours < 0) {
                    hours += 24;
                   }
                   minutes = strCurrentMinute.toInt();
                   seconds = strCurrentSecond.toInt();
                 }
               }
             }
           }
         }
       }
     }
   }
   //if no message was received (an issue with the Wi-Fi connection, for instance)
   else{
     seconds = 0;
     minutes += 1;
     if (minutes > 59) {
       minutes = 0;
       hours += 1;
       if (hours > 11) {
         hours = 0;
       }
     }
   }
   
}

void showTime(){
  display.clear();
  display.setTextAlignment(TEXT_ALIGN_CENTER);
  display.setFont(ArialMT_Plain_16);
  display.drawString(64, 20, String(hours) +":"+String(minutes)); 
  display.display();
}

walliot-v3-0.ino

Arduino
Arduino code with Google spreadsheet + deepsleep + quotes + clock + step counter + thingspeak
// ----------------------------
// Add libraries
// ----------------------------
#include <WiFi.h>             // Library for Wi-Fi
#include <WiFiMulti.h>        // Library for multiple Wi-Fi connections
#include <WiFiClientSecure.h> // Library for creating a https client
#include <ArduinoHttpClient.h>// Library for crating a http client
#include <ArduinoJson.h>      // Library for reading data from json
#include <Wire.h>             // Library for I2C communication to OLED display and Accelerometer
//#include "esp_deep_sleep.h"   // Library for ESP32 deep sleep
#include "SH1106.h"           // Library for OLED display (https://github.com/squix78/esp8266-oled-ssd1306)


// ------------------------------------------------------------------------------------
// Configurations
// ------------------------------------------------------------------------------------
// The following will have to be updated according to your hardware and accounts
// ------------------------------------------------------------------------------------

// Wi-Fi network
const char* ssid1     = "XXXXXX";    // Wi-Fi router SSID
const char* password1 = "YYYYYY"; // Wi-Fi router  password
const char* ssid2     = "XXXXXX";       // Wi-Fi rounter SSID
const char* password2 = "YYYYYY";   // Wi-Fi router password

// Hardware
#define SCL_PIN D5 // ESP32 pin connected to OLED display SCL pin
#define SDA_PIN D3 // ESP32 pin connected to OLED display SDA pin
TwoWire I2Ctwo = TwoWire(1); // I2C port for the accelerometer
#define SCL1_PIN 21 // ESP32 pin connected to accelerometer SCL pin
#define SDA1_PIN 22 // ESP32 pin connected to accelerometer SDA pin

// Google API
String spreadSheetID = "ZZZZZZ";  // ID from Google spreadsheet
String key = "?key=WWWWWW";            // Google API key
const size_t bufferSize = JSON_ARRAY_SIZE(1) + JSON_ARRAY_SIZE(5) + JSON_OBJECT_SIZE(3) + 100;  // buffer for json message
String getString = "GET /v4/spreadsheets/" + spreadSheetID + "/values/"; 

// Thingspeak API
String thingspeakKey = "UUUUUU"; // Thingspeak API key

// Other
#define Threshold 400   // Touch sensor sensitivity
#define stepThreshold 180   // Step counter sensitivity
#define TIMEZONE  3 // Current time zone. Used for correction of server time

// ----------------------------

// ----------------------------
// Global variables
// ----------------------------

// Time
String TimeDate = ""; // Variable used to store the data received from the server
int hours; // Current hour
int minutes; // Current minute
int seconds; // Current second
int seconds0;

// WiFi
WiFiMulti WiFiMulti;
WiFiClientSecure wificlient; // Create https client

// Display
SH1106 display(0x3c, SDA_PIN, SCL_PIN); // Start OLED display

// MPU 6050 accelerometer
const int MPU = 0x68;  // MPU6050 I2C address
int AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ; // Variables from the accelerometer
int steps = 0; // Number of steps
int AcX0 = 0;
int AcY0 = 0;

// Flags
boolean googleIt = false;
boolean stepDown = false;

// Quotes
String array[] = { 
  "The safe way to double\nyour money is to fold it\nover once and put it in\nyour pocket\n- Kin Hubbard", 
  "Be saving, but not at the\ncost of all liberality. Have\nthe soul of a king and the\nhand of a wise economist.\n- Joseph Joubert",
  "Look everywhere you can\nto cut a little bit from your\nexpenses. It will all add up\nto a meaningful sum.\n- Suze Orman", 
  "The quickest way to\ndouble your money is to\nfold it in half and put it in\nyour back pocket.\n- Will Rogers",
  "A budget is telling your\nmoney where to go instead\nof wondering where it went\n- John C. Maxwell",
  "You must learn to save\nfirst and spend afterwards.\n- John Poole",
  "Balancing your money is\nthe key to having enough.\n- Elizabeth Warren",
  "Saving must become a\npriority, not just a thought.\nPay yourself first.\n- Dave Ramsey",
  "By definition, saving for\nanything requires us to not\nget things now so that we\ncan get bigger ones later.\n- Jean Chatzky",
  "The art is not in making\nmoney, but in keeping it.\n- Anonymous",
  "He who will not economize\nwill have to agonize.\n- Confucius",
  "The easiest way to save\nmoney is to waste less\nenergy.\n- Barack Obama",
  "A simple fact that is hard\nto learn is that the time to\nsave money is when you\nhave some.\n- Joe Moore",
  "Saving is a very fine thing.\nEspecially when your\nparents have done it\nfor you.\n- Winston Churchill",
  "Money looks better in the\nbank than on your feet.\n- Sophia Amoruso",
  "Wealth consists not in\nhaving great possessions,\nbut in having few wants.\n- Epictetus",
  "If we command our wealth,\nwe shall be rich and free.\nIf our wealth commands\nus, we are poor indeed.\n- Edmund Burke",
  "When a man has learned\nto live without money, he\nthought, a few rubles can\ngo a long way.\n- Dan Millman",
  "Spend not where you may\nsave; spare not where you\nmust spend.\n- John Ray",
  "Save a little money each\nmonth and at the end of\nthe year you'll be surprised\nat how little you have.\n- Ernest Haskins",
  "A man is usually more\ncareful of his money than\nhe is of his principles.\n- Ralph Waldo Emerson",
  "If you can count your\nmoney,you don't have\na billion dollars.\n- J. Paul Getty",
  "There is a gigantic\ndifference between\nearning a great deal of\nmoney and being rich.\n- Marlene Dietrich",
  "Saving requires us to not\nget things now so that we\ncan get bigger ones later.\n- Jean Chatzky",
  "Never spend your money\nbefore you have earned it.\n- Thomas Jefferson",
  "All days are not same.\nSave for a rainy day. When\nyou dont work, savings\nwill work for you.\n- M.K. Soni",
  "A penny saved is\na penny earned.\n- Benjamin Franklin",
  "If you cannot save\nmoney, the seeds of\ngreatness are not in you.\n- W. Clement Stone",
  "A man who both spends\nand saves money is the\nhappiest man, because\nhe has both enjoyments.\n- Samuel Johnson",
  "You must gain control\nover your money or the\nlack of it will forever\ncontrol you.\n- Lydia Sweatt",
  "Saving comes too late\nwhen you get to the\nbottom.\n- Seneca",
  "Stop buying things\nyou don't need to\nimpress people you\ndon't even like.\n- Suze Orman",
  "A man is rich in\nproportion to the things\nhe can afford to let alone.\n- Henry David Thoreau",
  "Beware of little expenses.\nA small leak will sink a\ngreat ship.\n- Benjamin Franklin",
  "People suddenly know\nhow to use money when\nthere are none left.\n- Bangambiki Habyarimana",
  "Save one-third,\nlive on one-third,\nand give away one-third.\n- Angelina Jolie",
  "Do not save what is\nleft after spending,\nbut spend what is left\nafter saving.\n- Warren Buffet",
  "If you would be wealthy,\nthink of saving as well\nas getting.\n- Benjamin Franklin",
  "A wise person should\nhave money in their head,\nbut not in their heart.\n- Jonathan Swift",
  "Money is usually attracted,\nnot pursued.\n- Jim Rohn",
  "Many folks think they\narent good at earning\nmoney, when what they\ndont know is how to use it.\n- Frank A. Clark",
  "That's 49 cents of milk\nspilt over the table!\nSomebody's gonna drink\nthat!\n- Julius Rock",
};


// ----------------------------
// Setup
// ----------------------------
void setup() {

  Serial.begin(115200); // Start serial communication

  // Initializing the display
  display.init();
  display.clear();
  display.displayOn();
  display.flipScreenVertically();
  display.setTextAlignment(TEXT_ALIGN_CENTER);
  display.setFont(ArialMT_Plain_16);
  display.drawString(64, 0, F("IoT wallet"));
  display.setFont(ArialMT_Plain_10);
  display.drawString(64, 18, F("By igorF2"));
  display.display();

  // Initializing accelerometer
  I2Ctwo.begin(21,22,100000);
  I2Ctwo.beginTransmission(MPU);
  I2Ctwo.write(0x6B);
  I2Ctwo.write(0); 
  I2Ctwo.endTransmission(true);
  calibrate();
  delay(500);

  // Connect Wi-Fi network
  Connect_to_Wifi(); 
  delay(100);

  touchAttachInterrupt(T0, callback, Threshold);  // Enable touch sensor wake up
  //esp_deep_sleep_enable_touchpad_wakeup();        // Enable touch sensor wake up

  getTime();
  seconds0 = millis();
  
  btStop(); // Turn off bluetooth for saving battery 
}



// ----------------------------
// Main Loop
// ----------------------------

void loop() {

  readSteps();
  delay(50); // Wait 50 ms

  if ((millis() - seconds0) > 60000) {
      Connect_to_Wifi();
      getTime();
      // display clock
      showTime();
      seconds0 = millis();
      sendToThingspeak();
      steps = 0;
      WiFi.mode(WIFI_OFF); //turn off WiFi for saving battery
      Serial.println("WiFi disabled...");
  }

  //Serial.println("Going to sleep now...");
  //display.displayOff();
  //esp_deep_sleep_start(); // Start sleeping
  //WiFi.mode(WIFI_OFF); //turn off WiFi for saving battery
  
  if (googleIt == true) {
    display.clear();
    display.setTextAlignment(TEXT_ALIGN_CENTER);
    display.setFont(ArialMT_Plain_10);
    display.drawString(64, 20, "Connecting...");
    showTime();
    display.display();
    Connect_to_Wifi();
    display.clear();
    display.setTextAlignment(TEXT_ALIGN_CENTER);
    display.setFont(ArialMT_Plain_10);
    display.drawString(64, 0, array[random(0, 41)]);
    display.display();
    delay(2000);
    Serial.println("Reading Google Spreadsheet data...");
    readGoogleSheet(); // Read Google Sheet data and display on OLED display
    googleIt = false;
    WiFi.mode(WIFI_OFF); //turn off WiFi for saving battery
    Serial.println("WiFi disabled...");
  }
}
// ----------------------------


// ----------------------------
// Auxiliary functions
// ----------------------------

// Connect Wi-Fi network
void Connect_to_Wifi()
{
  WiFi.mode(WIFI_STA);
  
  // We start by connecting to a WiFi network
  WiFiMulti.addAP(ssid1, password1);
  WiFiMulti.addAP(ssid2, password2);

  Serial.println();
  Serial.print("Wait for WiFi... ");

  String displayText = "connecting";
  while (WiFiMulti.run() != WL_CONNECTED) {
    Serial.print(".");
    displayText += ".";
    display.clear();
    display.setTextAlignment(TEXT_ALIGN_CENTER);
    display.setFont(ArialMT_Plain_10);
    display.drawString(64, 0, displayText);
    delay(100);
  }

  // Display IP if connection successful
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}


// Executed when touch sensor activated
void callback(){
  // placeholder callback function
  
  Serial.println("touche");
  googleIt = true;
  //WiFi.mode(WIFI_ON); //turn off WiFi for saving battery
}

// Read Google Spreadsheet values and update OLED display
void readGoogleSheet(){
  boolean empty = false; // identifies if the last entry of the spreadsheet was read
  int row = 2; // row of the spreadsheet to be read
  while (!empty) {
    if (wificlient.connect("sheets.googleapis.com", 443) == true) // Try to connect Google APIs server at port 443 (https)
    {
        String toSend = getString; // GET string to be sent (columns from A to E)
        toSend += "A";
        toSend += row;
        toSend += ":";
        toSend += "E";
        toSend += row;
        
        // Cells to be read from the spreadsheet
        toSend += key; // Add API key
        toSend += " HTTP/1.1"; // End of GET instruction

        wificlient.println(toSend); // Send GET to server
        wificlient.println("Host: sheets.googleapis.com");
        wificlient.println();

        // Check HTTP status
        char status[32] = {0};
        wificlient.readBytesUntil('\r', status, sizeof(status));
        if (strcmp(status, "HTTP/1.1 200 OK") != 0) {
          Serial.print(F("Unexpected response: "));
          Serial.println(status);
          return;
        }

        // Skip HTTP headers
        char endOfHeaders[] = "\r\n\r\n";
        if (!wificlient.find(endOfHeaders)) {
          Serial.println(F("Invalid response"));
          return;
        }
        wificlient.readBytesUntil('\r', status, sizeof(status));

        // Create buffer
        DynamicJsonBuffer jsonBuffer(bufferSize);

        // Store values and convert to float
        JsonObject& root = jsonBuffer.parseObject(wificlient);
        String currency = root["values"][0][0];
        String amountStr = root["values"][0][1];
        String tickerStr = root["values"][0][2];
        String valueStr = root["values"][0][3];
        String changeStr = root["values"][0][4];
        float amount = amountStr.toFloat();
        float ticker = tickerStr.toFloat();
        float value = valueStr.toFloat();
        float change = changeStr.toFloat();

        // Update display
        if (currency != "") {
          Serial.println("Response:");
          Serial.println(currency);
          Serial.println(amount);
          Serial.println(ticker);
          Serial.println(value);
          Serial.println(change);

          display.clear();
          display.setTextAlignment(TEXT_ALIGN_CENTER);
          display.setFont(ArialMT_Plain_10);
          display.drawString(64, 0, String(amount) + currency);
          display.setFont(ArialMT_Plain_16);
          display.drawString(64, 20, String(value,2) + "BRL");
          display.setFont(ArialMT_Plain_10);
          display.setTextAlignment(TEXT_ALIGN_CENTER);
          display.drawString(64, 48, String(ticker,2) + "BRL"+"/"+currency+" ("+change+")");
          display.display();
          delay(300);
        }
        else {
          empty = true;
        }
        wificlient.stop();  // Stop connection to the server
      }
      else
      {
        Serial.println("Connection failured");
      }
      row++;
    }
}

// Read sensor and add to steps count
void readSteps() {
  I2Ctwo.beginTransmission(MPU);
  I2Ctwo.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  I2Ctwo.endTransmission(false);
  I2Ctwo.requestFrom(MPU,14,true);  // Request reading

  // Store readings
  AcX=I2Ctwo.read()<<8|I2Ctwo.read();
  AcY=I2Ctwo.read()<<8|I2Ctwo.read();
  
  float amplitude;
  amplitude = sqrt((AcX-AcX0)^2 + (AcY-AcY0)^2);

  if (amplitude < stepThreshold) {
    stepDown = true;
  }

  if ((amplitude >= stepThreshold) && stepDown) {
    stepDown = false;
    steps++; 
  }

  display.clear();
  display.setTextAlignment(TEXT_ALIGN_CENTER);
  display.setFont(ArialMT_Plain_10);
  display.drawString(64, 20, "Step count:");
  display.setFont(ArialMT_Plain_16);
  display.setTextAlignment(TEXT_ALIGN_CENTER);
  display.drawString(64, 48, String(steps));
  showTime();
  display.display();
}


void calibrate() {
  I2Ctwo.beginTransmission(MPU);
  I2Ctwo.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  I2Ctwo.endTransmission(false);
  I2Ctwo.requestFrom(MPU,14,true);  // Request reading

  // Store readings
  AcX0=I2Ctwo.read()<<8|I2Ctwo.read();
  AcY0=I2Ctwo.read()<<8|I2Ctwo.read();
}


//Get current time Google server
void getTime() {

  WiFiClient client;
  while (!!!client.connect("google.com", 80)) {
    Serial.println("connection failed, retrying...");
  }

  client.print("HEAD / HTTP/1.1\r\n\r\n");

  delay(500); //wait a few milisseconds for incoming message

   //if there is an incoming message
   if(client.available()){
     while(client.available()){
       if (client.read() == '\n') {    
         if (client.read() == 'D') {    
           if (client.read() == 'a') {    
             if (client.read() == 't') {    
               if (client.read() == 'e') {    
                 if (client.read() == ':') {    
                   client.read();
                   String theDate = client.readStringUntil('\r');
                   client.stop();

                   TimeDate = theDate.substring(7);
                   Serial.println(TimeDate);
                   // time starts at pos 14
                   String strCurrentHour = theDate.substring(17,19);
                   String strCurrentMinute = theDate.substring(20,22);
                   String strCurrentSecond = theDate.substring(23,25);
                   Serial.println(strCurrentHour);
                   Serial.println(strCurrentMinute);
                   Serial.println(strCurrentSecond);
                   hours = strCurrentHour.toInt();
                   hours = hours - TIMEZONE;
                   if (hours < 0) {
                    hours += 24;
                   }
                   minutes = strCurrentMinute.toInt();
                   seconds = strCurrentSecond.toInt();
                 }
               }
             }
           }
         }
       }
     }
   }
   //if no message was received (an issue with the Wi-Fi connection, for instance)
   else{
     seconds = 0;
     minutes += 1;
     if (minutes > 59) {
       minutes = 0;
       hours += 1;
       if (hours > 11) {
         hours = 0;
       }
     }
   }
   
}

void showTime(){
  display.setTextAlignment(TEXT_ALIGN_CENTER);
  display.setFont(ArialMT_Plain_10);
  display.drawString(64, 0, String(hours) +":"+String(minutes)); 
}


// Read Google Spreadsheet values and update OLED display
void sendToThingspeak(){  
  String stringToSend = "GET https://api.thingspeak.com/update?api_key=" + thingspeakKey + "&field1=" + String(steps);
  Serial.println(stringToSend);
  WiFiClient wificlient;
  wificlient.connect("api.thingspeak.com", 80);
  delay(300);
  wificlient.println(stringToSend); // Send GET to server   
  delay(500);
}

Credits

Igor Fonseca Albuquerque

Igor Fonseca Albuquerque

18 projects • 380 followers
Electrical and Mechanical engineer, master in automation and control. specialist in industrial instrumentation. Mad scientist and inventor.

Comments