A smart Raspberry Pi Zero DIY Text Clock

So this is the project I had in mind when I was experimenting with a NeoPixel strip on a Raspberry Pi Zero. The original text clock was invented a couple of years ago. With its elegant and timeless (yes, literally) design the QLOCKTWO is simultaneously a beautiful and useful piece of art.
It is not that I exactly needed yet another clock – but I got intrigued and wanted to create my own, smart version of a text clock.

Numerous examples of DIY versions and manuals on how to build a text clock are available on the internet. Some manuals involve soldering a lot of LEDs. I wanted to skip this step and went for a NeoPixel strip. In total I calculated 92 NeoPixels: one for each letter that can be alighted.

My version of the text clock should not only display the time in a unique way but should also indicate something more, it should be smart! This is why I chose a Raspberry Pi Zero instead of a microcontroller as a base. This way I’m able to easily get more information using a Python script along with some ready-made libraries.

My smart text clock indicates whether I have unread emails in my inbox by changing the colour of the LEDs. If desired the smart text clock is also able to indicate the weather developments depending on the outside temperature or any other criteria. The weather data is taken from openweathermap.org as in former projects.

One could also try to indicate whether a train one needs to catch regularly is on time. Or the smart text clock could be used as a traffic monitor for commuters (similar to this project idea).

Updating the smart text clock every 5 minutes should be precise enough for me. It is definitely more precise than a fuzzy clock which indicates bright and dark only.


The hardware list of the last blog entry can be extended by the picture frame which is often used for DIY text clocks. A suitable one is sold by a well-known swedish furniture store.
Additionally some paper is useful for dispersing the light from the LEDs behind the letters.

Adhesive foil with precisely cut letters can be put on the glass to match the LEDs from the strip. Here I had professional help by friends owning a cutting plotter.

The LED strip is cut and soldered together appropriately to match the letters positions. The strip is glued with its adhesive back to the picture frame’s back plate.

The LEDs are separated by a grid behind the glass. It is printed with a 3D printer. This grid helps to avoid interferences between the different letters.

A piece of transparent paper between the glass and the grid is the possibility to make the letters look smooth. If it was missing the LEDs were directly visible. A bit of diffusion makes it look better…


A straightforward python script is run automatically every five minutes. First the current time is determined. The time is translated into words with a five minute precision.

The words are mapped to the LED indices from the NeoPixel strip. These are the ones to alight to display the time.

Colour Definition

To determine which colour to use for the alighted LEDs some (optional) checks are built-in:

  • Approximately every hour the weather data is fetched from openweathermap.org using the python owm library. The temperature is extracted along with the weather code. The results are used for defining the colour of the LEDs. Other parameters can be taken into account as well.
  • The number of unread emails is checked using the Python imap library. If the number is greater than zero the LED color is changed.

During night time the brightness of the LEDs is lowered. That way the smart text clock serves as a convenient night light as well.

Source Code

# -*- coding: cp1252 -*-

import time

import imaplib

import pyowm
import json
import pprint

from neopixel import *


OWM_APYKEY='get one from openweathermap.org'
OWM_ID = an ID number

# file to store weather state

EMAIL_NAME = "user@googlemail.com"
EMAIL_PASS = "password"

# LED strip configuration:
LED_COUNT = 92 # Number of LED pixels.
LED_PIN = 18 # GPIO pin connected to the pixels (must support PWM!).
LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz)
LED_DMA = 5 # DMA channel to use for generating signal (try 5)
LED_BRIGHTNESS = 128 # Set to 0 for darkest and 255 for brightest
LED_INVERT = False # True to invert the signal (when using NPN transistor level shift)


_start = "IT IS "
_end = " O\'CLOCK"
_numbers = ('ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE', 'TEN', 'ELEVEN', 'TWELVE')
_past = ' PAST '
_to = ' TO '
_fivepast = 'FIVE PAST '
_tenpast = 'TEN PAST '
_aquarter = 'A QUARTER '
_twenty = ' TWENTY'
_twentyfive = ' TWENTYFIVE'
_half = ' HALF'
_fiveto = 'FIVE TO '
_tento = 'TEN TO '

I T L I S A S T I M E 0,1, 2,3
A C Q U A R T E R D C 4, 5,6,7,8,9,10,11
T W E N T Y F I V E X 12,13,14,15,16,17, 18,19,20,21
H A L F B T E N F T O 22,23,24,25, 26,27,28, 29,30
P A S T E R U N I N E 31,32,33,34, 35,36,37,38
O N E S I X T H R E E 39,40,41, 42,43,44, 45,46,47,48,49
F O U R F I V E T W O 50,51,52,53, 54,55,56,57, 58,59,60
E I G H T E L E V E N 61,62,63,64,65, 66,67,68,69,70,71
S E V E N T W E L V E 72,73,74,75,76, 77,78,79,80,81,82
T E N S E O C L O C K 83,84,85
# map time to precise LED indices
_timeLightMap = {
'IT IS ' : (0,1,2,3),
' HALF' : (22,23,24,25),
' PAST ' : (31,32,33,34),
' TO ' : (29,30),
'FIVE PAST ' : (18,19,20,21, 31,32,33,34),
'TEN PAST ' : (26,27,28, 31,32,33,34),
'A QUARTER ' : (4, 5,6,7,8,9,10,11),
' TWENTY' : (12,13,14,15,16,17),
' TWENTYFIVE' : (12,13,14,15,16,17, 18,19,20,21),
' HALF PAST ' : (22,23,24,25, 31,32,33,34),
' TWENTYFIVE TO ' : (12,13,14,15,16,17, 18,19,20,21, 29,30),
' TWENTY TO ' : (12,13,14,15,16,17, 29,30),
'TEN TO ' : (26,27,28, 29,30),
'FIVE TO ' : (18,19,20,21, 29,30),
'ONE' : (39,40,41),
'TWO' : (58,59,60),
'THREE' : (45,46,47,48,49),
'FOUR' : (50,51,52,53),
'FIVE' : (54,55,56,57),
'SIX' : (42,43,44),
'SEVEN' : (72,73,74,75,76),
'EIGHT' : (61,62,63,64,65),
'NINE' : (35,36,37,38),
'TEN' : (83,84,85),
'ELEVEN' : (66,67,68,69,70,71),
'TWELVE' : (77,78,79,80,81,82),
' O\'CLOCK' : (0,1,2,3)

class SmartTextClock():

def run(self):

def check_googlemail(self, login, password):
# if new mail return # emails
obj = imaplib.IMAP4_SSL('imap.gmail.com','993')
obj.login(login, password)
nofUnreadMessages = len(obj.search(None, 'UnSeen')[1][0].split())
print "Unread emails: " + str(nofUnreadMessages)
return nofUnreadMessages

def clock(self):
t = time.strftime("%H:%M")
print t
return t

def translateHour(self, hour, offset):
if hour == '00' or hour == '12':
if offset == True:
return _numbers[0]
return _numbers[11]
if hour == '1' or hour == '13':
if offset == True:
return _numbers[1]
return _numbers[0]
if hour == '2' or hour == '14':
if offset == True:
return _numbers[2]
return _numbers[1]
if hour == '3' or hour == '15':
if offset == True:
return _numbers[3]
return _numbers[2]
if hour == '4' or hour == '16':
if offset == True:
return _numbers[4]
return _numbers[3]
if hour == '5' or hour == '17':
if offset == True:
return _numbers[5]
return _numbers[4]
if hour == '6' or hour == '18':
if offset == True:
return _numbers[6]
return _numbers[5]
if hour == '7' or hour == '19':
if offset == True:
return _numbers[7]
return _numbers[6]
if hour == '8' or hour == '20':
if offset == True:
return _numbers[8]
return _numbers[7]
if hour == '9' or hour == '21':
if offset == True:
return _numbers[9]
return _numbers[8]
if hour == '10' or hour == '22':
if offset == True:
return _numbers[10]
return _numbers[9]
if hour == '11' or hour == '23':
if offset == True:
return _numbers[11]
return _numbers[10]
return ''

# time format: HH:mm
def translateTime(self, time):
t = time.split(':', 1)
print t
h = str(t[0])
m = str(t[1])
print h + ":" + m

indices = (1,2)

if float(m) >= 0.0 and float(m) <= 2.5:
indices = _timeLightMap[_start] + _timeLightMap[self.translateHour(h, False)] + _timeLightMap[_end]
if float(m) > 2.5 and float(m) <= 7.5:
indices = _timeLightMap[_start] + _timeLightMap[_fivepast] + _timeLightMap[self.translateHour(h, False)] + _timeLightMap[_end]
if float(m) > 7.5 and float(m) <= 12.5:
indices = _timeLightMap[_start] + _timeLightMap[_tenpast] + _timeLightMap[self.translateHour(h, False)] + _timeLightMap[_end]
if float(m) > 12.5 and float(m) <= 17.5:
indices = _timeLightMap[_start] + _timeLightMap[_aquarter] + _timeLightMap[_past] + _timeLightMap[self.translateHour(h, False)] + _timeLightMap[_end]
if float(m) > 17.5 and float(m) <= 22.5:
indices = _timeLightMap[_start] + _timeLightMap[_twenty] + _timeLightMap[_past] + _timeLightMap[self.translateHour(h, False)] + _timeLightMap[_end]
if float(m) > 22.5 and float(m) <= 27.5:
indices = _timeLightMap[_start] + _timeLightMap[_twentyfive] + _timeLightMap[_past] + _timeLightMap[self.translateHour(h, False)] + _timeLightMap[_end]
if float(m) > 27.5 and float(m) <= 32.5:
indices = _timeLightMap[_start] + _timeLightMap[_half] + _timeLightMap[_past] + _timeLightMap[self.translateHour(h, False)] + _timeLightMap[_end]
if float(m) > 32.5 and float(m) <= 37.5:
indices = _timeLightMap[_start] + _timeLightMap[_twentyfive] + _timeLightMap[_to] + _timeLightMap[self.translateHour(h, True)] + _timeLightMap[_end]
if float(m) > 37.5 and float(m) <= 42.5:
indices = _timeLightMap[_start] + _timeLightMap[_twenty] + _timeLightMap[_to] + _timeLightMap[self.translateHour(h, True)] +_timeLightMap[_end]
if float(m) > 42.5 and float(m) <= 47.5:
indices = _timeLightMap[_start] + _timeLightMap[_aquarter] + _timeLightMap[_to] + _timeLightMap[self.translateHour(h, True)] + _timeLightMap[_end]
if float(m) > 47.5 and float(m) <= 52.5:
indices = _timeLightMap[_start] + _timeLightMap[_tento] + _timeLightMap[self.translateHour(h, True)] + _timeLightMap[_end]
if float(m) > 52.5 and float(m) <= 57.5:
indices = _timeLightMap[_start] + _timeLightMap[_fiveto] + _timeLightMap[self.translateHour(h, True)] + _timeLightMap[_end]
if float(m) > 57.5 and float(m) <= 59.9:
indices = _timeLightMap[_start] + _timeLightMap[self.translateHour(h, True)] + _timeLightMap[_end]
return indices

def selectColor(self, weatherCondition):
# Email: Lime Green 50-205-50
# http://www.tayloredmktg.com/rgb/
color = Color(255, 222, 173)
# weatherCondition = 'fair' # 'good', 'fair, 'bad'
if weatherCondition == 'fair':
color = Color(255, 222, 173) # Navajo White 255-222-173 # Lemon Chiffon 255-250-205
if weatherCondition == 'good':
color = Color(255, 127, 80) # Coral 255-127-80 # Light Salmon 255-160-122
if weatherCondition == 'bad':
color = Color(70, 130, 180) # Steel Blue 70-130-180
return color

def getWeatherFromOWM(self):
owm = pyowm.OWM(OWM_APYKEY, version='2.5')
# Search for current weather
print "Weather @ID"
obs = owm.weather_at_id(OWM_ID)
w1 = obs.get_weather()
print w1.get_status()

weatherCondition = 'fair' # 'good', 'fair, 'bad'

# get general meaning for weather codes https://openweathermap.org/weather-conditions
weatherCode = w1.get_weather_code()
print weatherCode
print w1.get_sunset_time('iso')
temperature = w1.get_temperature('celsius')['temp']
print str(temperature) + " C"

# simple: judge weather on temperature
if temperature<=10.0:
weatherCondition = 'bad'
if temperature>10.0 and temperature<20.0:
weatherCondition = 'fair'
if temperature>=20.0 and temperature<35.0:
weatherCondition = 'good'
if temperature>=35.0:
weatherCondition = 'bad'

return weatherCondition

def readSavedWeatherCondition(self):
weatherCondition = 'fair' # default
print 'Read file ' + fileName
target = open(fileName, 'r')
weatherCondition = target.read()
print weatherCondition
except IOError:
print fileName + " does not exist yet. Creating a default file."
return weatherCondition

def saveWeatherConditionToFile(self, weatherCondition):
print 'Write file ' + fileName
target = open(fileName, 'w')
print 'File ' + fileName + ' could not be written.'

#strip.setPixelColor(i, Color(0,0,120)) # B
#strip.setPixelColor(i, Color(0,120,0)) # R
#strip.setPixelColor(i, Color(120,0,0)) # G
def alight(self, LEDindices, color):
print 'Alight indices ' + str(LEDindices)
for i in LEDindices:
strip.setPixelColor(i, color)

if __name__ == "__main__":
app = SmartTextClock()

# check for unread emails
unreadEmails = app.check_googlemail(EMAIL_NAME, EMAIL_PASS)

# get time and determine LED indices
time = app.clock()
indices = app.translateTime(time)
print "Indices " + str(indices)

# investigate weather data
weatherCondition = app.readSavedWeatherCondition()

# update weather data every hour
theTime = time.split(":")
# this range should be met from time to time
if int(theTime[1])>=0 and int(theTime[1])<=7:
weatherCondition = app.getWeatherFromOWM()

# create NeoPixel object with appropriate configuration
# intialize the library (must be called once before other functions)

# low light during 19-8 o'clock
if(8 < int(theTime[0]) > 19):

stripColor = Color(120,120,120)

# select color depending on weather condition
if weatherCondition == 'bad':
stripColor = Color(0, 120, 0)
if weatherCondition == 'fair':
stripColor = Color(120, 120, 120)
if weatherCondition == 'good':
stripColor = Color(0,0,120)

if unreadEmails > 0:
stripColor = Color(205,50,50)

app.alight(indices, stripColor)


Solar powered outdoor weather sensor

To be independent of a plug socket for an outdoor weather sensor solar power looks a lot more promising than wind or water for power generation. 😉 Especially since simple solar panels for tinkering are available for little money in the meantime. Only shipping from China usually takes a couple of weeks.

Earlier this year I launched my personal outdoor weather sensor to collect weather data such as temperature, humidity and air pressure. So far this required a plug socket and a 5V power supply. For the future I plan to use a solar panel to load a rechargeable battery which will alternatively power the outdoor weather sensor. Well, at least, when outside temperatures allow. During wintertime the cold temperatures might shorten the life of the rechargeable battery. Therefore, in the cold season the 5V power supply can be used alternatively.

Components used

Outdoor weather sensor
5V solar panel
Lithium battery 3,7 V, 2500 mAh
Lithium battery charger
Step up power supply


Starting from the solar panel the wires go to the input of the charger module. The charger is connected to the battery and the step up power supply. The output lines of the step up power supply are soldered to the outdoor weather sensor. The battery should be removable to switch easily to a conventional 5V power supply.

The following sketch roughly illustrates the setup:


Adjusting the Step Up power supply

The desired output voltage of the step up power supply is 5V in this case. It can be adjusted by turning the small screw while the outgoing lines of the charger modules are connected to a multimeter measuring the voltage.


To fully charge the rechargeable battery it should be very sunny! Charging takes a couple of hours depending on the size of the battery. Since it is a lithium battery the memory effect known from NiMh or NiCd rechargeable batteries can be neglected.

As soon as the outdoor weather sensor is powered by an electric 5V power supply the battery should be removed! (Mentioned just in case.)


Summers sunlight is optimal for charging a lithium battery and driving the outdoor weather sensor. This works in parallel. Since the outdoor weather sensor will spend most of the time in deep sleep mode the battery should last a while! So far I did not measure how mich power is drawn by awaking the outdoor weather sensor from deep sleep, doing the measurements, sending the measured values via WiFi to the server and going back to sleep. Perhaps later…

Well, now it is time to find a weather-proof box for all of this!



ESP8266: Uploading Weather Data to openweathermap.org

A couple of months ago I designed a small weather station to measure weather data such as temperature,  humidity and barometric pressure using an ESP8266 module and a couple of sensors. How this outdoor weather sensor is constructed is described in an older blog post.

openweathermap.org allows to connect a home made weather station to its network of weather stations around the world (currently >40.000). This may help to improve the data which is provided by openweathermap.org.

Uploading measured weather data is easily accomplished by performing an HTTP POST to http://openweathermap.org/data/post using basic authentication.

This manual describes how to upload weather data. Which weather details may be submitted in the post is illustrated in the table of the manual.


An account for openweathermap.org is required. The username and password must be translatedinto BASE64 encoding. This online tool helps to transfer username:password for openweathermap.org into the required format.

The location of the weather station is required as GPS coordinates. The latitude and the longitude of the location of the weather station can be determined with google maps for example. All it needs is to click on the location on the map. The coordinates will be displayed in a small window below the adress.

Components used

Outdoor weather sensor

Source Code

The Arduino sketch for the outdoor weather sensor may be enhanced. For brevity I concentrate in this example on the additional functionality required to upload the weather data, not on their measurement.

#include <ESP8266WiFi.h>  // http://esp8266.github.io/Arduino/versions/2.0.0/doc/libraries.html
#include <WiFiClient.h>   // https://www.arduino.cc/en/Reference/WiFiClient

boolean debug=true;
// WiFi connection data
const char* ssid = "SSID";
const char* password = "PASSWORD";

const char* server = "openweathermap.org";
const int serverPort = 80;

const unsigned long BAUD_RATE = 115200; // serial connection speed
const unsigned long HTTP_TIMEOUT = 10000;   // max respone time from server

void initSerial();
void connectWiFi();
bool connect(const char* hostName, const int port);
bool sendPost(const char* hostName, float temperature, float humidity, float pressure);
void displayResponse();
void disconnect();
WiFiClient client;

unsigned long previousMillis = 0;
#define INTERVAL_MS 60000

#define CredentialsBase64 "sOmECRYPticStRiNggg" // enter here the BASE64 encoded credentials in the form &amp;amp;amp;lt;username&amp;amp;amp;gt;:&amp;amp;amp;lt;password&amp;amp;amp;gt;
// https://www.base64encode.org/enc/credential/
const String stationName = "MyOwnWeatherStation"; // enter the station name (it will be displayed on openweathermap.org)
// use coordinates from google maps
const String lat = "xx.xxxxx"; // latitude
const String lng = "yy.yyyyy"; // longitude
const String alt = "5"; // altitude of the location in meters without decimals

void setup() {

void loop() {
  unsigned long currentMillis = millis();
  // run every minute
  if (currentMillis - previousMillis >= INTERVAL_MS) {
    previousMillis = currentMillis;
    if( debug ) Serial.println("loop: measure weather data");
    float temperature=14.6;
    float humidity=89.1;
    float pressure=1004.6;
    // TODO use measured data from sensors!

    if( connect(server, serverPort) ) {
      if( sendPost(server, temperature, humidity, pressure) ) {

// send the HTTP POST request to the server
bool sendPost(const char* hostName, float temperature, float humidity, float pressure) {
  if( debug ) {
    Serial.print("POST weather data to");
    Serial.print("t = ");
    Serial.print("h = ");
    Serial.print("p = ");

  // construct packet
  String packet = "";
  packet += "temp=";
  packet += (int)temperature;
  packet += "&humidity=";
  packet += (int)humidity;
  packet += "&pressure=";
  packet += (int)pressure;
  packet += "&lat=";
  packet += lat;
  packet += "&long=";
  packet += lng;
  packet += "&alt=";
  packet += alt;
  packet += "&name=";
  packet += stationName;

  // construct POST request
  String cmd = "POST /data/post HTTP/1.1\n";
  cmd += "Host: ";
  cmd += hostName;
  cmd += "\n";
  cmd += "Content-Type: application/x-www-form-urlencoded\n";
  cmd += "Authorization: Basic ";
  cmd += CredentialsBase64;
  cmd += "\n";
  cmd += "Content-Length: ";
  cmd += packet.length();
  cmd += "\n";
  cmd += "Connection: close\n\n";
  cmd += packet;
  cmd += "\r\n\r\n";

  if( debug ) {
    Serial.print("packet: ");
    Serial.print("cmd: ");
  return true;

void displayResponse() {
  char reply[400];
  size_t length = client.readBytes(reply, 400);
  reply[length] = 0;
  String replyString = String(reply);

  if( debug ) {
    Serial.print("HTTP response ");

// initialize serial port
void initSerial() {
  while (!Serial) {
    ;  // wait for serial port to initialize
  if( debug ) Serial.println("Serial ready");

// attempt to connect to WiFi
void connectWiFi() {
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    if( debug ) Serial.print(".");
  if( debug ) {
    Serial.println("WiFi connected");
    Serial.print("IP address: ");

// open connection to the HTTP server
bool connect(const char* hostName, const int port) {
  if( debug ) {
    Serial.print("Connect to ");
  bool ok = client.connect(hostName, port);
  if( debug ) Serial.println(ok ? "Connected" : "Connection Failed!");
  return ok;

// close the connection with the HTTP server
void disconnect() {
  if( debug ) Serial.println("Disconnect from HTTP server");


The HTTP POST to upload weather data boils down to

POST /data/post HTTP/1.1
Host: openweathermap.org
Content-Type: application/x-www-form-urlencoded
Authorization: Basic sOmECRYPticStRiNggg
Content-Length: 80
Connection: close


The content length is the length of the string containing the measured weather data, the coordinates etc. . More weather parameters may be added – everything that is measurable can be interesting for the upload.

How to find the own Weather Station

Finding the data from the own weather station after the upload was a bit tricky. It looks like openweathermap.org is working on improvements for uploading weather data as I conclude from this support answer. At least the documentation for upploading data needs improvements.

The station ID is returned in the HTTP response to the post. This is easy to miss. If the upload of weather data was successful the response should look similar to this:

HTTP response header HTTP/1.1 200 OK
Server: nginx/1.6.2
Date: Sat, 20 Aug 2016 11:37:00 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: close
X-Powered-By: Fat-Free Framework (http://fatfree.sourceforge.net)
Pragma: no-cache
Cache-Control: no-cache, must-revalidate


The ID can be used to observe the station using the URL http://openweathermap.org/station/987654321 .

To retrieve the weather data from this station in JSON format an HTTP GET request can be performed using this URL in a browser:

http://api.openweathermap.org/data/2.5/station?id=987654321&APPID=<YOURAPPID&gt; .

With some delay the uploaded data becomes visible in JSON format:


Inspirational Links



REST asleep – how to construct an HTTP server in Java

REST? What? An HTTP server to „communicate“ with via URLs? Yes, why not. In certain use cases a valid solution for various different tasks. Especially for the idea of displaying more or less ’static‘ information on a display.

In my case such a server handles tasks such as

  • fetching the next x entries in a (google) calendar
  • retrieving and preprocessing actual weather data from openweathermap
  • retrieving and preprocessing the weather forecast for the upcoming hours/days from openweathermap

Other examples of useful information could be financial data such as

  • exchange rates of different currencies or
  • stock market information.

Interesting could also be the information which dustbin should be standing outside next for garbage disposal in the morning.
Perhaps flight information for frequent flyers, train times (and delays) for rail travellers, even momentary fuel prices in the region (if only they were not changing so quickly as in Germany) is helpul.

For sure there are more ideas which data could be retrieved and prepared by a server for display! But back to the server itself.

HTTP Server Construction

An HTTP server in Java is basically a runnable jar file that is launched on a machine within a (local) network. The required libraries include http, httpclient, httpcore, … .


When a GET request is received from a client the appropriate routine is launched. For each ‚digestible‘ URL a different Java class handles the request.
In case of fetching the next x entries from a Google calendar the specific Java class handles the authentication, the retrieval and the processing of the calendar entries into the JSON format. In Java this is more simple and faster than computing directly on an Arduino.

The entry point of the server may be constructed like this:

import com.sun.net.httpserver.HttpServer;
public static void main(String[] args) {
	try {
	    HttpServer server = HttpServer.create(new InetSocketAddress(12345), 0);
	    server.createContext("/calendar", new RequestCalendarHandler());
	    server.createContext("/weather", new RequestOWMWeatherHandler());
	    server.createContext("/forecast", new RequestOWMWeatherForecastHandler());
	    server.setExecutor(null); // creates a default executor
	    System.out.println("Server running on host " + server.getAddress().getHostString());
	} catch (IOException e) {


For weather data/weather forecast retrieval from openweathermap it is not necessary to reimplement the wheel. An excellent Java library already exists: owm-japis. It can be used in a different Java class to process appropriate HTTP GET requests.

The handler for fetching weather data by openweathermap may look similar to this:

import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpExchange;

import net.aksingh.owmjapis.CurrentWeather;
import net.aksingh.owmjapis.OpenWeatherMap;
import net.aksingh.owmjapis.OpenWeatherMap.Units;
static class RequestOWMWeatherHandler implements HttpHandler {
	public void handle(HttpExchange http) throws IOException {
		System.out.println("URI received: " + http.getRequestURI().toString());

	String[] request = http.getRequestURI().toString().split("/");
	if( request.length&gt;1 ) {
		// Handle read requests
		if( request[1].equals("weather") ) {
			OpenWeatherMap owm = new OpenWeatherMap("APIKEY");

			// getting current weather data for the location
			CurrentWeather cwd = owm.currentWeatherByCityCode(CITYCODE_OWM);

			// checking data retrieval was successful or not
			if (cwd.isValid()) {
				DateFormat dateFormatter = new SimpleDateFormat("dd.MM.yyyy");
				Date now = cwd.getDateTime();
				String dateNow = dateFormatter.format(now);
				DateFormat timeFormatter = new SimpleDateFormat("HH:mm");
				String timeNow = timeFormatter.format(now);

				System.out.println("Post weather result in JSON format (raw)");
				// wrap parcels of byte size 4096
				int BUFFER_SIZE = 4096;
				http.sendResponseHeaders(200, 0);
				try (BufferedOutputStream out = new BufferedOutputStream(http.getResponseBody())) {
					try (ByteArrayInputStream bis = new ByteArrayInputStream(response.getBytes())) {
						byte [] buffer = new byte [BUFFER_SIZE];
						int count ;
						while ((count = bis.read(buffer)) != -1) {
							out.write(buffer, 0, count);
		} catch (Exception e) {

Client to Server

A client requests data from the HTTP server by a GET request. An example URL to fetch the weather data looks like this:
Such an URL consisting of hostname:port can be tested in a browser on the machine where the server is running. Otherwise an IP or hostname must replace localhost.

Server to Clients

As soon as the HTTP server received a request it analyses the URL and launches the appropriate handler. In the example above the weather data will be retrieved from openweathermap (API key and location ID required).

How to read from a google calendar in Java is explained on google’s developer pages. Authentication for the desired calendar must be set up in advance following the manual.

The results can be preprocessed into a desired format to be posted for the client.
A common format is the JSON format. Data in this format can be read and processed further by a client.

Example Client: Arduino / ESP8266

The client I use is an Adafruit Huzzah microcontroller with an ESP8266 WiFi chip.
(Just in case: the hardware setup, the pin changes in the epd library and the code to parse weather data are described in previous blog posts) .
The source code in this blog post illustrates how to act as an HTTP client. To decode a reply in JSON format the library ArduinoJson is used.
Any display can be attached to the microcontroller to show the results from the HTTP GET request to the HTTP server. At the moment I strongly prefer an e-Ink display. 😉









E-Ink Weather Display

An E-Ink display is perfect for displaying information that does not change quickly. Displaying weather data and perhaps even a weather forecast is something that usually does not require an update every second.

Where to find weather data

Weather data can be retrieved by openweathermap for example. All it needs is an account. The retrieval of current weather data and a five day / three hour forecast is for free within certain limits. Limit means that the calls per minute of the service may not exceed 60.

Openweathermap provides an API that can be used in various programming languages. In the end an URL is used to fetch the desired data. The format of the result can be selected. The default is the JSON format which can be relatively simple parsed on Arduino using libraries such as ArduinoJson. Still I found the summary of the typical pitfalls helpful.

The same principle can be used with a tailor made outdoor weather sensor in combination with a custom HTTP web server that delivers the requested data in the desired format. But that is a different blog post.

Example URL

To retrieve the weather data from openweathermap a simple URL is required. This URL may contain the city ID which can be found here, the desired unit system and the API key that can be generated after sign up on openweathermap. Other parameters to adjust the resulting weather data can be added optionally.

The weather data for the desired location can be accessed in several ways: by city name, by zip code, by geographic location, … . However, openweathermap recommends to use the ID of the location. This list contains the IDs for the available locations.

This example of an URL will work in a browser as well (using a valid API key!):


Example Result in JSON format

Below is an exemplary result string:

"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03n"}],
"base":"cmc stations",

How to retrieve the current weather data is explained in more detail on openweathermap/current.

Components used & Wiring

The hardware setup is the same as in the previous blog post.


The Arduino sketch to retrieve and process weather data from openweathermap is based on an example from the ArduinoJson library. This example was extended to retrieve and process the weather data from openweathermap and to display the information on the E-Ink display.

// based on: https://github.com/bblanchon/ArduinoJson/blob/master/examples/JsonHttpClient/JsonHttpClient.ino

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ArduinoJson.h>
#include <epd.h>

const char* ssid = "SSID";
const char* password = "WIFIPASSWORD";

const char* server = "api.openweathermap.org"; // server's address
const int port = 80;
const char* resource = "/data/2.5/weather?id=2643743&units=metric&APPID=YourAPIKey"; // http resource

const unsigned long BAUD_RATE = 115200; // serial connection speed
const unsigned long HTTP_TIMEOUT = 10000; // max respone time from server
const size_t MAX_CONTENT_SIZE = 1024; // max size of the HTTP response

/* example URL
example result in JSON format:
"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03n"}],
"base":"cmc stations",

// weather data type
struct WeatherData {
char cityName[20];
char nowDescription[50];
char temperature[6];
char humidity[3];
char pressure[5];
char iconCode[4];

WiFiClient client;
boolean debug=true;

void initSerial();
void initializeEInkDisplay();
void connectWiFi();
bool connect(const char* hostName);
void disconnect();
void wait();
bool sendRequest(const char* host, const char* resource);
bool skipResponseHeaders();
void readReponseContent(char* content, size_t maxSize);
void printWeatherData(const struct WeatherData* weatherData);
bool parseWeatherData(char* content, struct WeatherData* weatherData);

void setSmallText(String text, int x, int y);
void setMediumText(String text, int x, int y);
void setLargeText(String text, int x, int y);

void updateDisplay(struct WeatherData* weatherData);
String selectWeatherIcon(struct WeatherData* weatherData);

void setup() {

void loop() {
if( connect(server) ) {
if( sendRequest(server, resource) && skipResponseHeaders() ) {

char jsonResult[MAX_CONTENT_SIZE];
readReponseContent(jsonResult, sizeof(jsonResult));

WeatherData weatherData;
if( parseWeatherData(jsonResult, &weatherData) ) {

void initSerial() {
while (!Serial) {
; // wait for serial port to initialize
if( debug ) Serial.println("Serial ready");

void initializeEInkDisplay() {
epd_set_memory(MEM_TF); // MEM_NAND=internal memory; MEM_TF=sd card
epd_set_color(BLACK, WHITE);

void connectWiFi() {
// connect to the WiFi network
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
if( debug ) Serial.print(".");
if( debug ) {
Serial.println("WiFi connected");
Serial.print("IP address: ");

bool connect(const char* hostName) {
if( debug ) {
Serial.print("Connect to ");
bool ok = client.connect(hostName, port);
if( debug ) Serial.println(ok ? "Connected" : "Connection Failed!");
return ok;

bool sendRequest(const char* host, const char* resource) {
if( debug ) {
Serial.print("GET ");
client.print("GET ");
client.println(" HTTP/1.1");
client.print("Host: ");
client.println("Connection: close");
return true;

bool skipResponseHeaders() {
// HTTP headers end with an empty line
char endOfHeaders[] = "\r\n\r\n";
bool ok = client.find(endOfHeaders);
if (!ok) {
if( debug ) Serial.println("No response or invalid response!");
return ok;

void readReponseContent(char* content, size_t maxSize) {
size_t length = client.readBytes(content, maxSize);
content[length] = 0;
if( debug ) {

bool parseWeatherData(char* content, struct WeatherData* weatherData) {
// find first and last curly bracket of JSON result
String cStr = String(content);
int firstCurlyBracket = cStr.indexOf('{');
int lastCurlyBracket = cStr.lastIndexOf('}');
String c = cStr.substring(firstCurlyBracket,lastCurlyBracket+1);

/*if( debug ) {
Serial.println("parseWeatherData: ");
Serial.print("content length: ");

c.toCharArray(content, MAX_CONTENT_SIZE);

/*if( debug ) {
Serial.println("parseWeatherData: ");

StaticJsonBuffer<MAX_CONTENT_SIZE> jsonBuffer;

// find fields in JSON object
JsonObject& root = jsonBuffer.parseObject(content);
if (!root.success()) {
if( debug ) Serial.println("parsing JSON Object() failed");
return false;

strcpy(weatherData->cityName, root["name"]);
strcpy(weatherData->nowDescription, root["weather"][0]["description"]);
strcpy(weatherData->temperature, root["main"]["temp"]);
strcpy(weatherData->humidity, root["main"]["humidity"]);
strcpy(weatherData->pressure, root["main"]["pressure"]);
strcpy(weatherData->iconCode, root["weather"][0]["icon"]);
return true;

void printWeatherData(const struct WeatherData* weatherData) {
if( debug ) {
Serial.print("city name = ");
Serial.print("temperature = ");
Serial.println(" *C");
Serial.print("humidity = ");
Serial.println(" %");
Serial.print("pressure = ");
Serial.println(" hPa");

void disconnect() {
if( debug ) Serial.println("Disconnect from HTTP server");

void wait() {
if( debug ) Serial.println("Wait 30 seconds");

//-------- e-ink display code ----------
void setSmallText(String text, int x, int y) {
epd_disp_string(text.c_str(), x, y);

void setMediumText(String text, int x, int y) {
epd_disp_string(text.c_str(), x, y);

void setLargeText(String text, int x, int y) {
epd_disp_string(text.c_str(), x, y);

void updateDisplay(struct WeatherData* weatherData) {
int distStart=50;
setLargeText(String(weatherData->cityName), 50, distStart);
distStart += 100;
epd_draw_line(10, distStart, 500, distStart); // horizontal line
distStart += 20;
setMediumText(String(weatherData->nowDescription), 50, distStart);
distStart += 60;
epd_draw_line(10, distStart, 500, distStart); // horizontal line

distStart += 50;
setMediumText(String("temperature: ") + String(weatherData->temperature) + String(" *C"), 50, distStart);
distStart += 60;
setMediumText(String("humidity: ") + String(weatherData->humidity) + String(" %"), 50, distStart);
distStart += 60;
setMediumText(String("pressure: ") + String(weatherData->pressure) + String(" hPa"), 50, distStart);
distStart += 60;

epd_draw_line(10, distStart, 500, distStart); // horizontal line

epd_draw_line(510, 10, 510, 590); // vertical line

// display weather icon
String weatherIcon = selectWeatherIcon(weatherData);
epd_disp_bitmap(weatherIcon.c_str(), 560, 100);


String selectWeatherIcon(struct WeatherData* weatherData) {
String iconCode = String(weatherData->iconCode);
if( debug ) {
Serial.print("selectWeatherIcon: ");
if( iconCode.startsWith("01") ){
if( debug ) Serial.println("SUN.BMP");
return String("SUN.BMP");
} else if( iconCode.startsWith("02") ){
if( debug ) Serial.println("CLOUDY.BMP");
return String("CLOUDY.BMP");
} else if( iconCode.startsWith("03") ){
if( debug ) Serial.println("CLOUD.BMP");
return String("CLOUD.BMP");
} else if( iconCode.startsWith("04") ){
if( debug ) Serial.println("CLOUD.BMP");
return String("CLOUD.BMP");
} else if( iconCode.startsWith("09") ){
if( debug ) Serial.println("RAIN.BMP");
return String("RAIN.BMP");
} else if( iconCode.startsWith("10") ){
if( debug ) Serial.println("UNSETTLED.BMP");
return String("UNSET.BMP");
} else if( iconCode.startsWith("11") ){
if( debug ) Serial.println("THUNDER.BMP");
return String("THUND.BMP");
} else if( iconCode.startsWith("23") ){
if( debug ) Serial.println("SNOW.BMP");
return String("SNOW.BMP");
} else {
if( debug ) Serial.println("UNSETTLED.BMP");
return String("UNSET.BMP");


To get a quick overview off the weather or the forecast an icon does the trick better than pure text. One can design own weather icons or search thenounproject for beautiful examples. The icons have to be uploaded first to the micro SD card of the E-Ink display in the appropriate format. The manufacturer of the display explains in his wiki how to prepare the images and how to upload them on the micro SD card.

The weather icon codes returned by openweathermap are listed in this table. To display the appropriate image the codes only need to be translated.

The result can look like this:

e-ink weather display

e-ink weather display

In the end this weather display hack is a prototype which can be easily extended.








IoT: Collecting Weather Data

Collecting data from temperature, humidity and barometric sensors with an
Arduino is compelling when observing the weather. The idea is to create an outdoor sensor module. This outdoor module sends the measured data via WiFi to a server which stores the measurement data in a local database.

Components used

ESP-ADC DIL 18 with ESP8266 module
BMP085 Barometric Pressure & Temp Sensor
DHT22 Temperature and Humidity Sensor
220 uF 16V capacitor
Single color LED
220; 4,7k, 10k resistors
wires, switches, breadboard, breadboard power supply, 3,3 V FTDI programmer

Make it happen


wiring of esp8266, dht22, bmp085


ESP8266 Parts Notes
GND GND DHT22 / GND BMP085 / GND ESP-ADC / LED – via 220 resistor
VCC 3,3 V VCC DHT22 / VCC BMP085 / VCC ESP8266
Reset switch 1 / GPIO_16 Connection to GPIO_16 required for deep sleep mode of ESP8266
GPIO_0 switch 2
GPIO_4 SDA BMP085 On ESP8266 I2C is implemented in software, could be soft-wired to any other GPIO, default for I2C clock is GPIO_4
GPIO_5 SDL BMP085 On ESP8266 I2C is implemented in software, could be soft-wired to any other GPIO, default for I2C data is GPIO_5
GPIO_7 Pin 2 DHT22, pull to 3,3 V VCC via 4,7 k resistor
CHPD 3,3 V VCC via 10k resistor

The capacitor is used to stabilize the electric power supply for the two sensors and the ESP8266. This is especially useful when the ESP8266 sets up a WiFi connection and its power consumption increases.

Uploading an Arduino Sketch to the ESP8266


  • Adjust the FTDI programmer for 3,3 V logic
  • Connect the FTDI programmer’s RX and TX lines to the ESP8266.
  • Connect the FTDI programmer’s GND line to GND of the breadboard power supply.

Arduino IDE settings

Adjust the upload settings in the Arduino IDE:

Arduino IDE upload settings


To upload an Arduino sketch to the ESP8266 module push the two buttons. Release the switch connected to Reset approx. a second before the switch connected to GPIO_0 and trigger the upload in the Arduino IDE. The timing is relevant. It may happen that this procedure has to be repeated several times until the upload succeeds.

After the successful upload of the sketch the output in the Arduino IDE looks similar to this:

upload message on success:
setting serial port timeouts to 1000 ms
 espcomm_send_command: receiving 2 bytes of data
 writing flash
starting app without reboot
 espcomm_send_command: sending command header
 espcomm_send_command: sending command payload
 espcomm_send_command: receiving 2 bytes of data
closing bootloader
 flush start
 setting serial port timeouts to 1 ms
 setting serial port timeouts to 1000 ms
 flush complete


Installing Adafruit Libraries

The Arduino sketch based on the examples for the unified BMP085 and DHT libraries.
The required libraries for Adafruid BMP085 Unified, Sensor and DHT Unified can be installed for the Arduino IDE via Sketch > Libraries > Manage Libraries… .

Some Code

#include <ESP8266WiFi.h> // http://esp8266.github.io/Arduino/versions/2.0.0/doc/libraries.html
#include <WiFiClient.h>

#include <Adafruit_Sensor.h>
#include <Adafruit_BMP085_U.h> // https://github.com/adafruit/Adafruit_BMP085_Unified

#include <DHT.h>
#include <DHT_U.h> // https://github.com/adafruit/Adafruit_DHT_Unified
#define DHTTYPE DHT22
#define DHTPIN 7

// WiFi network credentials
const char* ssid = "<SSID>";
const char* password = "<PASSWD>";

// IP / port weather station server
#define IPWS ""
#define PORT 20016

// times for deep sleep mode
unsigned long MIN_1 = 60000000;
unsigned long MIN_15 = 900000000;
unsigned long MIN_30 = 1800000000;
unsigned long S_30 = 30000000;
unsigned long DEEP_SLEEP = MIN_30;

// Initialize DHT sensor 
// NOTE: For working with a faster than ATmega328p 16 MHz Arduino chip, like an ESP8266,
// you need to increase the threshold for cycle counts considered a 1 or 0.
// You can do this by passing a 3rd parameter for this threshold. It's a bit
// of fiddling to find the right value, but in general the faster the CPU the
// higher the value. The default for a 16mhz AVR is a value of 6. For an
// Arduino Due that runs at 84mhz a value of 30 works.
// This is for the ESP8266 processor on ESP-01 
DHT_Unified dht(DHTPIN, DHTTYPE, 11); // 11 works fine for ESP8266

Adafruit_BMP085_Unified bmp;

#define STATUSLED 13

boolean debugging = false; // enable / disable debug output

String float2String(float value) {
  char v[10];
  return String(v);

String readSensors() {
  if( debugging ) Serial.println("Read sensor data...");
  String str = "";
  String str2Send = "wData;";

  if( debugging ) Serial.println("DHT22");
  sensors_event_t event;
  float temperature = 0.0;
  temperature = event.temperature;
  if( isnan(temperature) ) {
    if( debugging ) Serial.println("Error reading temperature!");
  } else {
    if( debugging ) {
      Serial.print("Temperature: ");
      Serial.println(" *C");
 // Get humidity event and print its value.
 float humidity = 0.0;
 humidity = event.relative_humidity;
 if( isnan(humidity) ) {
   if( debugging ) Serial.println("Error reading humidity!");
 } else {
   if( debugging ) {
     Serial.print("Humidity: ");

 float temperature2 = 0.0;
 str = "Temperature: " + float2String(temperature2) + " *C\n";
 str += "Humidity: " + float2String(humidity) +" %\n";

 float pressure = 0.0;
 pressure = pressure/100.0;
 if( debugging ) {
   Serial.print("Pressure: ");
   Serial.println(" hPa");
 str += "Pressure: " + float2String(pressure) + " hPa\n";

 if( debugging ) {
   Serial.print("Collected sensor data: ");
 str2Send += temperature;
 str2Send += ";";
 str2Send += humidity;
 str2Send += ";";
 str2Send += pressure;
 str2Send += "\0";

 if( debugging ) {
   Serial.print("Sensor data for sending to server: ");
 return str2Send;

// expected string: e.g. weatherdata;14.3;60.7;1018.0
void sendSensorData(String str2Send) {
 WiFiClient client;
 client.connect(IPWS, PORT);
 if( debugging ) {
   Serial.print("Sending: ");
 client.write(str2Send.c_str(), str2Send.length());
 if( client.connected() ) {

void setup(void) {
 // You can open the Arduino IDE Serial Monitor window to see what the code is doing
 Serial.begin(115200); // Serial connection from ESP-01 via 3.3v console cable

 dht.begin(); // initialize temperature sensor

 if (!bmp.begin()) {
   if( debugging ) Serial.println("Could not find a valid BMP085 sensor, check wiring!");
   while (1) {}
 // set as station
 // connect to WiFi network
 WiFi.begin(ssid, password);
 if( debugging ) Serial.print("\n\r \n\rWorking to connect");

 // wait for connection
 while (WiFi.status() != WL_CONNECTED) {
   if( debugging ) Serial.print(".");

 digitalWrite(STATUSLED, LOW);
} // setup()

void loop(void) {

 // read data from sensors
 String str = readSensors();

 if( debugging ) {
   Serial.print("Sending sensor data to server: ");

 // indicate data acquisition and sending
 digitalWrite(STATUSLED, HIGH);

 // enter deep sleep mode for x minutes
 // GPIO16 needs to be tied to RST to wake ESP8266 from deep sleep mode
 // http://russ.russmathis.com/esp8266-power-modes/
 //ESP.deepSleep(DEEP_SLEEP, MODE);
 // 30000000 ms = 30 s
 ESP.deepSleep(MIN_30, WAKE_RF_DEFAULT);


In debug mode the output on the serial console is similar to this:

Working to connect….
Read sensor data…
Temperature: 22.10 *C
Humidity: 53.60%
Temperature: 22.10 *C
Pressure: 1009.2 hPa
Collected sensor data:
Temperature: 22.10 *C
Humidity: 53.60%
Pressure: 1009.2 hPa
Sending sensor data to server: …


After measurement the ESP8266 establishes a WiFi connection. The collected data is sent as a string to a dedicated server of the desired IP within the local network.
Another possibility would be to send the data to thingspeak.com for quick visualization.

Deep sleep – saving power

After having sent the measurement data the ESP8266 enters „deep sleep“ mode until it is woken up again after the desired time. For this feature GPIO_16 has to be wired with Reset on the ESP8266.


The ESP8266 module should be configured as a a station, not as an accesspoint (WIFI_AP). In this setup the module is used for sending data only.

Barometric sensor

Usually the barometric pressure is the ‚raw‘ value. It is calculated to match the barometric pressure at sea level. Depending on the actual level the measured value differs from the barometric values close to the location. In this case the measured barometric pressure needs to be adapted.

Temperature sensor data

Small deviations of the measured temperature are possible between the two sensors. The causes for such deviations are usually production tolerances of the sensor’s chips or even a close local heat source.