Digital Desk Clock

Digital Desk Clock

How do IoT clocks work? In this lesson you will learn how to build an digital clock that gets its time from the Internet. This can run on BrainPad Pulse.

Prerequisite

You must have basic understanding of coding and have completed the Drawing lesson.

The API

This program use the timeapi.io API. It is a free service that returns a JSON file containing time related data based on the URL you send it. You can find the correct URL for the time zone or region you would like to use on their site. Our example below uses the America/Detroit time zone.

import {SerialUSB} from './serialusb.js';
import * as due from './duelink.js';

let BrainPad = new due.DUELinkController(new SerialUSB());
await BrainPad.Connect();

let url = 'https://www.timeapi.io/api/Time/current/zone?timeZone=America/Detroit';

const response = await fetch(url);
const data = await response.json();

console.log(data.hour);
console.log(data.minute);
console.log(data.seconds);

var hour = data.hour;
var min = data.minute;
var sec = data.seconds;

await BrainPad.Display.Clear(0);
await BrainPad.Display.Show();

if (hour > 0 && hour < 10)
    await BrainPad.Display.DrawTextScale(hour, 1, 18, 20, 3, 3);
else
    await BrainPad.Display.DrawTextScale(hour, 1, 0, 20, 3, 3);

BrainPad.Display.DrawTextScale(":", 1, 36, 20, 3, 3);

if (min < 10){
    await BrainPad.Display.DrawTextScale("0", 1, 48, 20, 3, 3);
    await BrainPad.Display.DrawTextScale(min, 1, 66, 20, 3, 3);
}else{
    await BrainPad.Display.DrawTextScale(min, 1, 48, 20, 3, 3);
}
BrainPad.Display.DrawTextScale(":", 1, 83, 20, 3, 3);

if (sec < 10){
    await BrainPad.Display.DrawTextScale("0", 1, 95, 20, 3, 3);
    await BrainPad.Display.DrawTextScale(sec, 1, 113, 20, 3, 3);
}else{
    await BrainPad.Display.DrawTextScale(sec, 1, 95, 20, 3, 3);
}
await BrainPad.Display.Show();

What’s Next?

The Timeapi.io website used in our code returns additional JSON data not used in our example. Look at the JSON file it returns and modify the program to display the additional content available on the screen.

Now that we understand how we collect data from a website for the Time, could we do the same thing for the weather? Try using Open-meteo.com, it’s free JSON API is similar to the one used in the example and returns weather based on specific latitude & longitude values in the URL.


BrainStorm

The example uses the Internet to collect Time data, can you think of other types of data you might collect in similar way?

Content Licensing
Newsletter

Twitter Feed
Hot off the press!