Published January 21st at 1:12pm - 722 ♥ - 7 min read

DIY Hive Price Ticker part 1

Diyhub Tutorial Esp32 Stem Leofinance Diy Arduino Build-it Electronics

I love to make some DIY stuff and specially in electronic parts. I found a small ESP32-with-a-screen called TTGo. What can I do with this small thing?

And just after this question, I see the Hive price going up! The answer was found, I'll made a HIVE price ticker!

HivePriceTicker.jpg

In this tutorial (in two parts), I'll try to show you how to do your Hive price ticker. Don't be afraid, All the project is open-source and I'll share you the entire code. This post is a tutorial about "How can I do a small Hive price ticker?".

What you need?

To build this price ticker, you will need:

  • A TTGo display board (you can find it for $15 on AliExpress, I have the 4MB CH340K),
  • An USB-C cable to connect your TTGo to your PC.

Also, the Arduino IDE (or alternative) is required to put the code into the board.

This post is only about the code part. We'll see the 3D-printing part in the next one.

Preparation

Prepare the Arduino IDE

First, You need to add ESP32 support into the Arduino IDE. Open Arduino IDE, go to File -> Preferences, and in "Additional Boards Manager URLs" just paste https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json and click OK.

Next, Go to Tools -> Board -> Board Manager and search esp32, and just click the Install button.

Libraries

Now, we need to choose some good libs to make the work easier.

  • The TTGo display lib, based on TFT_eSPI
  • WiFi (included in esp32 libs), for network communication
  • HTTPClient (included in esp32 libs), to get data from a website
  • Arduino_JSON to parse result JSON from the query

To install the TTGo display lib, just download the repo and copy the TFT_eSPI folder into your Arduino folder:

  • For Windows, it's in C:\Users\Your User Name\Documents\Arduino\libraries
  • For MacOS or Linux, it's in ~/Arduino/libraries

About Arduino_JSON, it's easier. In Arduino IDE, go to Tools -> Manage libraries, search Arduino_JSON and click the Install button.

All is ready!

The Code

All this project will use the C language because Arduino and ESP32 must be programmed in C. This time, I'll try to explain my code, but if you don't understand, just install the libs, copy/paste my code (at the end), compile to your TTGo Display, and it will works!

Tl;dr: The entire code is available on this Git repository.

Include libraries headers

To start, the good practice is to include all the libs at the start of your file. Like that, you'll never forget any libs you use:

#include <TFT_eSPI.h>
#include <SPI.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <Arduino_JSON.h>

Prepare your variables

Of course, after that, Try to list each var you can use inside your project. You can modify the vars really easily:

// Replace with your wifi credentials to connect to your home network
const char* ssid = "Your_WiFi_SSID";
const char* password = "Your_WiFi_Passowrd";

// Hostname on network 
String hostname = "HivePriceTicker";

// vars for wifi reconnect
unsigned long previousMillis = 0; // Needed for reconnection
unsigned long interval = 30000; // Interval between two connections (in milliseconds)

// Set CoinGeckoID and URL to API use
String coinId = "hive";
String server = "https://api.coingecko.com/api/v3/simple/price?vs_currencies=usd&include_24hr_change=true&ids=";

Of course, don't forget to change the ssid and password for your connection.

The logo

I need to convert the Hive Logo into Bitmap C code. I use the JavL image2cpp Image converter to do that. The result is just an array with code for every pixel.

I'll not paste this array here because it's just an array of bytes, you can see it in the Git repo but I called the array epd_bitmap_hive.

It's like a dot matrix, each point corresponds to one pixel, and for each point with a value, it's a color.

For TFT_eSPI, I need to create an array with all these "bitmap" matrixes. But in this project, I only use one:

// Array of all bitmaps for convenience. (Total bytes used to store images in PROGMEM = 1824)
const int epd_bitmap_allArray_LEN = 1;
const unsigned char* epd_bitmap_allArray[1] = {
  epd_bitmap_hive
};

Init this thing!

We need to init the screen and the wifi, the screen, create the full URL to fetch data and start the board. I add some debug lines with Serial object to show how the board behaves (and displays some errors).

For the screen, it's really simple, just one line to load the lib into an object:

TFT_eSPI tft = TFT_eSPI();

About WiFi, we need to init the chip in "STA" mode, set the hostname, begin with the good SSID and password and wait for the WL_CONNECTED status:

// Function for Wifi connection
void wifiInit() {
  WiFi.mode(WIFI_STA);
  WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE, INADDR_NONE);
  WiFi.setHostname(hostname.c_str()); //define hostname
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
}

For the Data fetching URL, simply one line to create the full endpoint URL string with server and coinId var (described at the top of the file) :

String endpoint = server + coinId;

OK, now, the esp32 (and most Arduino boards) need to instantiate a setup() function to launch the board. For this price ticker, we need a Serial to debug, init the screen, display something waiting for the WiFi to connect (using the wifiInit() function). Let's go:

void setup(void) {
  // Serial ignition
  Serial.begin(115200);

  // Screen init
  tft.init();
  tft.setRotation(1);
  delay(100);
  Serial.println("Screen Setup done , Width & Height");
  Serial.println(tft.width());
  Serial.println(tft.height());
  
  // Fill screen with Black color
  tft.fillScreen(TFT_BLACK);
  tft.setCursor(0, 0, 2);

  // Display init text
  tft.setTextColor(TFT_RED,TFT_BLACK);
  tft.setTextFont(4);
  tft.println("Hive Price Ticker");
  
  tft.setTextColor(TFT_WHITE,TFT_BLACK);
  tft.setTextFont(2);
  tft.println("By Bambukah");

  tft.setTextColor(TFT_GREEN,TFT_BLACK);
  tft.setTextFont(4);
  tft.println(" ");
  tft.println("Connecting...");

  // Set WiFi to station mode
  wifiInit();
  Serial.println("Wifi Setup done");
}

The main loop

This HIVE price ticker will check the API Endpoint every 30 seconds and display the coin, the coin's price in USD and the 24h change in percent. It will repeat this endlessly. If an error appears, the screen will display it, wait for 30 secs and retry.

Each 30 seconds:

  • The screen goes to black,
  • Draw the logo,
  • Check if Wifi is OK,
  • Init the HTTP lib,
  • Fetch the data parse the data to extract everything we need,
  • Add some styling,
  • Display that,
  • Close the HTTP connection,
  • Wait 30 seconds.

Ready? Here is the code:

void loop() {
  // Fill screen with Black color
  tft.fillScreen(TFT_BLACK);

  // Display Logo
  tft.drawBitmap(120, 5, epd_bitmap_hive, 120, 120, 100);
  
  // Check if Wifi is always connected. If not, try to reconnect
  unsigned long currentMillis = millis();
  if ((WiFi.status() != WL_CONNECTED) && (currentMillis - previousMillis >=interval)) {
    Serial.print(millis());
    Serial.println("Wifi Reconnect...");
    WiFi.disconnect();
    WiFi.reconnect();
    previousMillis = currentMillis;
  }

  // Create HTTP Request Client
  HTTPClient http;

  // Specify endpoint
  http.begin(endpoint);

  // Query the server to get JSON 
  int httpCode = http.GET();
  if (httpCode > 0) { // If request is OK
    String payload = http.getString();
    // Serial.println(payload): // Uncomment for Debug refreshing
    
    // Covert payload to JSON
    JSONVar result = JSON.parse(payload);

    String value = String((double)result[coinId]["usd"]);
    float h24 = (double)result[coinId]["usd_24h_change"] * 100 / 100;
    String change = String(h24);

    // Create new var to Uppercase for display
    String coin = coinId;
    coin.toUpperCase();

    // Display all texts
    tft.setCursor(0, 0, 4);
    tft.setTextColor(TFT_RED,TFT_BLACK);
    tft.println(coin);
    tft.setTextColor(TFT_WHITE,TFT_BLACK);
    tft.println(" ");
    tft.println(value +" USD");
    char sign = change.charAt(0);

    // Check if change is negative to display in red or green if it's positive
    if (sign == '-') {
      tft.setTextColor(TFT_RED,TFT_BLACK);
      tft.println(change +" %");
    } else {
      tft.setTextColor(TFT_GREEN,TFT_BLACK);
      tft.println("+"+change+" %");
    } 
  } else {
    tft.fillScreen(TFT_BLACK);
    tft.setCursor(0, 0, 2);
    tft.setTextColor(TFT_WHITE,TFT_BLACK);
    tft.println("Error from HTTP Request");
    tft.println("Wait 30 sec before retry");
  }

  http.end();
  delay(interval);
}

Configure the board and compile

The code is successfully completed. We must configure the Arduino IDE to have good settings:

  • Connect the board,
  • Tools menu -> Port -> Select the good serial port,
  • Tools menu -> Board -> ESP32 -> ESP32 Dev Module.

It's time to send the code! On Arduino IDE, nothing hard, It's the second icon (with the arrow). Just click on it and wait several seconds. Now, look at your TTGo :)

Mission Successfully completed, we have an HIVE price ticker!

What's next?

It's the end of the Part One of this tutorial. In the next tutorial, we will print a good 3D case and add a battery.

Hope you'll enjoy to follow this tutorial. If you like it, just up-vote and reblog this post. Also, feel free to ask questions or ideas in the comments ;)

Have a nice day!


Vote for this article

50%

Comments :

diyhub :
Thank you for sharing this post in the DIYHUB Community!

Your content got selected by our fellow curator ashikstd & you just received a little thank you upvote from us for your great work! Your post will be featured in one of our recurring compilations which are aiming to offer you a stage to widen your audience within the DIY scene of Hive. Stay creative & HIVE ON!

Please vote for our hive witness <3
spiritsurge :

Oh God!! I can remember the last time I worked with an Arduino board...Back in the university...Major Nostalgia hit...

ecency :

Yay! 🤗
Your content has been boosted with Ecency Points, by @bambukah.
Use Ecency daily to boost your growth on platform!

Support Ecency
Vote for new Proposal
Delegate HP and earn more

naymhapz :

Wow! I learned from your blog. Thank you for sharing.

rajivmarteau :

Thanks for this quality work and amazing learning material :)

Posted Using LeoFinance Beta

fenngen :

Pretty cool, I imagine this could be very useful for trading

stemsocial :

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support. 
 

badbitch :

All of this for a price ticker, God help us 😂🙏

acidyo :

Really cool! :D

nathen007 :

Absolutely brilliant! If I could sit and read posts like this all day, I'd be in heaven. MORE please :-)

Have a great day my friend and thank you !

hivebuzz :

Congratulations @bambukah! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)

You got more than 800 replies.
Your next target is to reach 900 replies.

You can view your badges on your board and compare yourself to others in the Ranking If you no longer want to receive notifications, reply to this comment with the word STOP

Check out our last posts:

The Hive Gamification Proposal