Posted on Leave a comment

BTCmarket ticker using ESP8266

BTCmarket Ticker with ESP8266

With the recent fall of Bitcoin and other crypto currency and my continue interest in learning more about Arduino, after reading several other instruction of using OLED display, I had combine it all to create a BTCmarket ticker using ESP8266. The reason why I use BTCmarket as the sample is because this is the one that I am currently using, but you can adapt that to any market ticker providing they have API to support data exchange.

Step 1: Gather all the materials needed

The materials used in this are:

  • ESP8266
  • 128×64 0.96″ OLED display

Step 2: Connect the ESP8266 to the OLED display using the following :

  • Connect the SCL of OLED display to D2 of ESP8266
  • Connect the SDA of OLED display to D4 of ESP8266
  • Connect the VCC to 3.3V
  • connect the GND to ground

This is shown in the figure below:

ESP8266 connection diagram
ESP8266 Connection

Step 3: Load library to Arduino

The following instruction assume that you are already familiar with Arduino interface and know where the library is located. For Mac users the Arduino library is located in Documents/Arduino/Libraries.

You will need the ESP8266RestClient library, TimeLib library and theĀ ESP8266_and_ESP32_Oled_Driver_for_SSD1306_display library. Credit goes to their respective author for creating such an awesome library.

Step 4: Load the following code in Arduino interface and upload it to the ESP8266

// BTCMarket Crypto currency ticker
//
// 128x64 OLED pinout:
// GND goes to ground
// Vin goes to 3.3V
// Data to I2C SDA (GPIO 4)
// Clk to I2C SCL (GPIO 2)
#include <TimeLib.h>
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include "RestClient.h"
#include <SSD1306.h>
#include <SSD1306Wire.h>


char ssid[] = "INSERT YOUR SSID HERE"; // your network SSID (name)
char pass[] = "INSERT YOUR NETWORK PASSWORD"; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)

int status = WL_IDLE_STATUS;

RestClient restclient = RestClient("api.btcmarkets.net",443,1); 
SSD1306 display(0x3c, 4, 2); //0x3d for the Adafruit 1.3" OLED, 0x3C being the usual address of the OLED


void setup() {
 //Initialize serial and wait for port to open:
 Serial.begin(115200);
 //Setup Rest Client
 WiFi.begin(ssid, pass);

 Wire.pins(4, 2); // Start the OLED with GPIO 4 and 2 on ESP-01
 Wire.begin(4, 2); // 4=sda, 2=scl
 display.init();
 display.flipScreenVertically();
 display.drawString(0, 24, "Connected.");
 display.display();
 delay(1000);
}

void processticker(){
 String response = "";
 //Get the ETH ticker
 int statusCode = restclient.get("/market/ETH/AUD/tick", &response);
 // for some reason sometimes the response is not clean
 String temp = response.substring(response.lastIndexOf("{"), response.lastIndexOf("}")+1);
 //Serial.println("status:" + String(statusCode) + " response:" + temp);
 int rlength = temp.length();
 //Serial.println("Response Length=" + String(rlength));
 char jvar[rlength+1];
 
 temp.toCharArray(jvar, rlength+1);
 //jvar[rlength] = 0;
 StaticJsonBuffer<300> jsonBuffer;
 Serial.println("jvar:" + String(jvar));
 JsonObject& root = jsonBuffer.parseObject(jvar);
if (!root.success()){
 Serial.println(F("Parsing failed!"));
 Serial.println("temp:" + temp);
 } else{
 String Buy = root["bestBid"];
 String Sell = root["bestAsk"];
 String LastTrade = root["lastPrice"];
 time_t tStamp = root["timestamp"];
 tStamp = tStamp + 600 * 60; // GMT + 10
 String TheDate = String(String(day(tStamp)) + "/" + String(month(tStamp)));
 String TheTime = String(String(hour(tStamp)) + ":" + String(minute(tStamp)));
 Serial.println("Buy:"+Buy+"; Sell:"+Sell + "; Last:"+LastTrade );
 display.clear();
 display.drawString(0,0, "ETH/AUD");
 display.drawString(0,13, TheDate +" " + TheTime);
 display.drawString(0,23, "Buy: "+Buy);
 display.drawString(0,33, "Sell: "+Sell);
 display.display();
 }
 
 delay(1000);
}

int timer =0;

void loop() {

if (timer > 5){ // so that we don't call it too frequently we add delay of 5 second
 timer = 0;
 //process ticker
 processticker(); 
 }else{ // handle http client while waiting
 timer++;
 }

delay(1000);
}

You should be able to have the Ethereum ticker now that you can expand to give you an alert they way you want it.

If you like this post, please give a comment or share with your friends. You can also subscribe to my blog for regular updates.

Posted on Leave a comment

IoT Motion Sensor with light

This is the extension of the earlier post IoT Temperature Sensor with ESP8266. The extension is to additional IoT Motion Sensor with light.

Here are the concept picture.

We are going to connect the PIR sensor (motion sensor) to the other free port of the ESP8266. The PIR sensor consist of 3 legs, shown in the following picture:

As you can see, there are tiny marking of +,0,- on the PCB next to the legs. So connect the “+” to 3.3V, “-” to the ground and the middle pin “0” to pin D6 of ESP8266.

To detect the motion we added the following code to our Arduino program:

void handlePIR(){
  DebugLn("handlePIR");
  motion = digitalRead(PIRpin) == HIGH;
  if (motion){
    digitalWrite(LED_BUILTIN, LOW);
    if (locklow){
      // make sure we wait for a transition to LOW before any further output
      locklow = false;
      Serial.print("motion detected at ");
      Serial.print(millis()/1000);
      Serial.println(" sec");
      delay(50);
    }
    takeLowTime = true;
 } else {
   digitalWrite(LED_BUILTIN, HIGH);
   if (takeLowTime){
     lowIn = millis(); // save the time of the transition from high to LOW
     takeLowTime = false; // make sure this is only done at the start of LOW phase
   }
   // if the sensor is low for more than the given pause, assume no more motion is going to happen
   if (!locklow && millis() - lowIn > pause){
   // make sure this block is executed again after new motion sequence had been detected
     locklow = true;
     Serial.print("motion ended at ");
     Serial.print((millis() - pause)/1000);
     Serial.print(" sec");
     delay(50);
   }
 }
 // post to webserver
 data = "pir_sensor=" + String(motion);
 postData(data);
}

The code above will light up the internal LED (Internal LED active LOW) when there is a motion being detected by the sensor.

In the next step we will connect the LED light to the circuit to allow us to control the light from the Internet.

Posted on Leave a comment

Light Activated MP3 player (Part 2/2)

This is the continuation of the Light Activated Mp3 player Part 1.

Once we had tested that our MP3 is fully functional, it is now the time to add the Light sensor. The Light sensor LDR (Light Dependend Resistor) is a passive component that is reactive to light, when the light shine through the LDR, their resistance value decreases. So in order to use this we had to connect the LDR with another Resistor to build a voltage divider. This will provide the feed into the Arduino input.

The updated circuit can be found below:

Arduino Connection

As shown in the circuit above the connection from the voltage divider of LDR and resistor 10K is connected to Arduino input A0. Assuming that you had a working code from Part 1. The following snippet of code allows you to detect the light.

const int LDRpin = A0; // LDR connected to pin A0
 ldrStatus = analogRead(LDRpin);
 //Serial.println(ldrStatus);
 if (ldrStatus >=300){
   digitalWrite(LED_BUILTIN, LOW);
   Serial.print("LED Light");
   mp3.start();
   onStatus = true;
 }

The above code will play the mp3 player when the light is shining on the LDR. The threshold of the brightness in the code is 300, this can be adjusted if you have less light. If you have less light, that means you will need to lower the threshold, a bit of trial and error will give the best result.

And finally instead of using the internal Arduino light, I had added another LED connected to PIN 13 or Arduino. This is shown in the following diagram

Light activated MP3 player

The full source code can be found below:

// this example will play a Track 001 in folder 006
// when light is on the LDR
// it expects the sd card to contain some mp3 files
// LDR is connected with Resistor 10K in series
// Free LDR leg is connected to 5V
// other end of R10K is connected to GND
// joined LDR leg and R10k is connected to pin A0
// LED is connected to pin D13
#include 
#include 
#define DEBUG 0
// implement a notification class,
// its member methods will get called
//
class Mp3Notify
{
public:
 static void OnError(uint16_t errorCode)
 {
 // see DfMp3_Error for code meaning
 Serial.println();
 Serial.print("Com Error ");
 Serial.println(errorCode);
 }
 static void OnPlayFinished(uint16_t track)
 {
 Serial.print("Play finished for #");
 Serial.println(track);
 }
 static void OnCardOnline(uint16_t code)
 {
 Serial.println("Card online ");
 }
 static void OnCardInserted(uint16_t code)
 {
 Serial.println("Card inserted ");
 }
 static void OnCardRemoved(uint16_t code)
 {
 Serial.println("Card removed ");
 }
};
// instance a DFMiniMp3 object,
// defined with the above notification class and the hardware serial class
//
//DFMiniMp3<HardwareSerial, Mp3Notify> mp3(Serial1);
// Some arduino boards only have one hardware serial port,
//so a software serial port is needed instead.
// comment out the above definition and uncomment these lines
SoftwareSerial secondarySerial(10, 11); // RX, TX
DFMiniMp3<SoftwareSerial, Mp3Notify> mp3(secondarySerial);
const int LDRpin = A0; // LDR connected to pin A0
const int LEDpin = 13; // LED pin D13
int Song=1; //sd:/06/001.mp3
int ldrStatus;
boolean onStatus = true;
boolean takeLowTime;
//the timer to reset song
long unsigned int timeoutTimer = 0, resetCount = 0;
//the amount of milliseconds the sensor has to be low
//before we assume all motion has stopped
long unsigned int pause = 2000;
void setup()
{

 Serial.begin(115200);
 if (DEBUG) Serial.println("initializing...");
 pinMode(LDRpin, INPUT); // setup LDR
 pinMode(LEDpin, OUTPUT);
mp3.begin();
 mp3.reset();

 // show some properties and set the volume
 uint16_t volume = mp3.getVolume();
 Serial.print("volume ");
 Serial.println(volume);
 mp3.setVolume(20);

 uint16_t count = mp3.getTotalTrackCount();
 Serial.print("files ");
 Serial.println(count);
uint16_t mode = mp3.getPlaybackMode();
 Serial.print("playback mode ");
 Serial.println(mode);

 if (DEBUG) Serial.println("starting...");
 mp3.playFolderTrack(6, Song);
}
void loop()
{
 ldrStatus = analogRead(LDRpin);
 if (ldrStatus >=300){
  digitalWrite(LEDpin, HIGH);
  mp3.start();
  onStatus = true;
 }
 } else {
 digitalWrite(LEDpin, LOW);
 mp3.pause();
 }
 // calling mp3.loop() periodically allows for notifications
 // to be handled without interrupts
 mp3.loop();
}

I hope you had enjoyed the process of building the Light Activated Mp3 player, and hopefully you are well rewarded by giving this gift. Enjoy the final video of the gift that I had made. If you like this please leave me a comment.

https://www.youtube.com/watch?v=UQk4YPjXWLA