Javascript Flasher Clock 
Sunday, March 25, 2018, 08:12
Posted by Administrator
I have been using my minimalistic Pi Zero W flasher clock for a while now and have found it to be an exceptionally soothing way to check on the current time. I recently ported the code over to work on the Pi 3 B+ and have edited my previous post about it to include both versions.

The only trouble with this clock has been that the code for it is very specifically for a Raspberry Pi, and I have found myself wanting to have a flashing clock indicator like this on other devices like phones, televisions, etc. Clearly, the flasher clock I designed was in need of another port, so set of to re-create it in Javascript.

It was a much more interesting challenge to get this working in Javascript than I expected it to be since Javascript is non-blocking and there is no built-in way to pause execution and sleep as you can with bash scripting. However, with some new features that most modern browsers take advantage of, Javascript is now capable of handling asynchronous functions natively and can use the async/await keywords to sort of hold off on execution until a promise for the await returns.

With async/await and promises, I was able to create a helper function to simulate a similar sleep behavior that my original script had without having to re-design everything to work as a weird sort of state machine using setTimeouts. This new code could have certainly be re-written to not use async/await but I believe it would be a lot less straightforward to make sense of that way. I was also able to take advantage of another ES6 addition, arrow functions, to streamline this custom wait function into the following one-liner:

var wait = t => new Promise(resolve => setTimeout(() => resolve(), t));

This function, wait, takes a variable t which is the time in milliseconds that the setTimeout should wait until returning a promise. With this component in place I had everything I needed to finish up converting my original design into something that could run in any modern browser:

<html>
<head>
<title>Javascript Flasher Clock</title>

<script>

// Set up our colors array
const colors = [
'#FFFFFF',
'#FF0000',
'#FF8000',
'#FFFF00',
'#80FF00',
'#00FF00',
'#00FF80',
'#00FFFF',
'#0080FF',
'#0000FF',
'#7F00FF',
'#FF00FF',
'#FF007F'
];

// Set up our default color index
var c = 0;

// Set up our base wait time
var w = 50;

// Define the wait function, a promise that waits for a setTimeout of length t before returning
var wait = t => new Promise(resolve => setTimeout(() => resolve(), t));

// A function to change the color
function changeColor() {

// If we are at the end of the colors array set c back to the first value
if ( c === colors.length - 1) {

// Set c back to the first color
c = 0;

}

// Else we just need to increment our color value c
else {

// Increment c
c++;

}

}

// Define our clock function using async so that we can use await
async function clock() {

// Set the default background color to black at the beginning of each cycle
document.body.style.background = '#000000';

// Wait for a long while so that we separate our flasher clock cycles
await wait(w * 40);

// Get the current date
let date = new Date();

// Get the current number of hours
let hours = ((date.getHours() + 11) % 12 + 1);

// Get the current number of tens digits
let tensDigits = (date.getMinutes() < 10 ? '0' : '' + date.getMinutes()).substring(1,0);

// Flash the current number of hours
for (let h = 0; h < hours; h++) {

// Wait a while
await wait(w*8);

// Set the screen to the colors c value
document.body.style.background = colors[c];

// Wait another while
await wait(w*8);

// Set the screen back to black
document.body.style.background = '#000000';

}

// Wait a medium while between the hours and tens digits flashes
await wait(w*20);

// Flash for the current number of tens digits
for (let t = 0; t < tensDigits; t++) {

// Wait a little while
await wait(w*5);

// Set the screen to the colors c value
document.body.style.background = colors[c];

// Wait another little while
await wait(w*5);

// Set the screen back to black
document.body.style.background = '#000000';

}

// Call this clock function again to start a new cycle
clock();

}
</script>

</head>
<body onload='clock()' onclick='changeColor()'>
</body>
</html>

I also added the capability to click anywhere on the screen to cycle through many different color codes so that the one can switch up the display color of the flash easily even if using a phone.

As with the original design, the clock flashes for the current number of hours ( in 12-hour format ) and then flashes a little more quickly once for every current tens digit of minutes. For example, if the time is 6:38 the clock will flash 6 times somewhat slowly, and then three times somewhat faster. I decided that the clock should be in 12-hour format in order to cut down on the number of flashes one would potentially have to watch in each cycle. Similarly, I have foregone the full number of minutes to cut down on the number of flashes one would have to count. Staying within ten minutes of accuracy seems like a good compromise between the time necessary to read the clock and precision to me.

The Javascript Flasher Clock can be experienced here.

I'm very happy with the results. It was great to finally make use some of the newest additions to Javascript. These new features made it possible for me to rewrite my original script much more easily than I had originally imagined.

My plan is to shine a phone running this clock at a wall so that the whole wall is a time indicator, but I'm also interested in lighting up translucent objects so that the object itself can be the time indicator. A milk jug should work great for that, although it may look classier inside of a paper lantern.

-- Addendum, March 26 2018

I have found a nice opaque white container that diffuses a phones display well and have placed it in the middle of my indoor sand garden. The phone is able to remain charged by keeping it plugged in with a hole for the cord I made in the back of the container. It then struck me that I had no way to change the light color or intensity once everything was assembled in the jar, but this was easily solved by adding Teamviewer Host to the phone and the remotely controlling phone from another device to change the display brightness or cycle through color options.
add comment ( 2621 views )   |  permalink   |  $star_image$star_image$star_image$star_image$star_image ( 2.9 / 4453 )
Easy Raspberry Pi GPIO Pin Control with Bash 
Saturday, July 8, 2017, 13:37
Posted by Administrator
I have been experimenting a bit with home automation lately by hooking up some small electrical relays to my Raspberry Pis. So far I have my bedroom fan and a small lamp fully under remote control and connected to my home network. I even have them under voice control now by using an app called Tasker on Android, as well as two helper plugin apps for Tasker called Autovoice and an associated SSH Plugin. I feel an undeniable sense of power whenever I verbally tell my phone to turn my lamp or fan on or off, and it has quickly become a much more natural and pleasant feature of my bedroom over the last few days.

In the past, I have always used Python and a GPIO control library to control the output pins on a Raspberry Pi. This method requires installing both Python and the pin control library on a fresh Raspbian or Retropie install, which can be a bit of a nuisance.

Since the release of the first Raspberry Pi I've been wanting a simple solution to just turn Raspberry Pi pins on or off without having to install any additional software or remember any commands. I've also loved bash scripting for a long time now, and while putting together my last minimal Pi Zero clock project I realized that a pi's output pins can be fully controlled by writing to system files without the need of installing Python or anything else. For example, to turn on pin 26 on a Raspberry Pi one can simply enter these three short commands:

sudo echo "26" > /sys/class/gpio/export
sudo echo "out" > /sys/class/gpio/gpio26/direction
sudo echo "1" > /sys/class/gpio/gpio26/value

Turning the pin off is as easy as echoing a value of 0 to the pin's value in the same location as the last line.

I first created a number of small scripts to turn certain pins on, and another script to turn the same pin off and was using that with my home automation system. After a couple of days, I decided that I'd like to have a script to toggle the state of any arbitrary pin. This is so that I can issue the same command to turn my lamp on or off without having to be specific about what I want when I yell at the phone. I also wanted this script to be able to specifically turn a pin on or off in the case that I'm not at home and want to make sure something is turned on or off even if I don't recall whether I left it on or not. I quickly came up with the following bash code that accomplishes just that:

#!/bin/bash
# A utility script to toggle a raspberry pi gpio pin on or off
# Spike Snell - July 2017

# If there are command line options to use
if [ $# != 0 ]
then

# Set up our argument variables
arg1="$1"
arg2="$2"

# If the gpio pin was not previously set up
if [ ! -e /sys/class/gpio/gpio"$arg1" ];
then
# Make sure that gpio pin $arg1 is initialized
echo "Initializing gpio pin" $arg1
echo "$arg1" > /sys/class/gpio/export
echo "out" > /sys/class/gpio/gpio"$arg1"/direction
fi

# Check to see if there was a second command line argument
if [ -z "$2" ]
# Argument 2 for the on/off value was not set
# We should just toggle the current state of gpio pin $arg1
then
# If the current value is 1 set it to 0 and vice versa
if grep -q 1 /sys/class/gpio/gpio$arg1/value
then
echo "Toggling gpio pin" $arg1 "to 0"
echo "0" > /sys/class/gpio/gpio"$arg1"/value
else
echo "Toggling gpio pin" $arg1 "to 1"
echo "1" > /sys/class/gpio/gpio"$arg1"/value
fi
# Argument 2 for the on/off value was set
# We should set gpio pin $arg1 to the value of $arg2
else
echo "Setting gpio pin" $arg1 "to" $arg2
echo "$arg2" > /sys/class/gpio/gpio"$arg1"/value
fi

# Else there were no options passed in, let the user know about them
else
echo "Please enter what pin to toggle, ex: sudo ./pin.sh 11"
echo "Optionally enter if the pin should be 1 or 0, ex: sudo ./pin.sh 11 0"
echo " * Make sure to run as super user "
fi

I included some helpful information near the bottom that gets displayed if the script is called without any parameters. To use it the script should be saved as pin.sh and set to be executable with the command sudo chmod +x pin.sh.

I plan to use this script quite a lot in the future and this seems a good place to keep a copy of it. Hopefully this can be helpful to others as well. Feel free to leave any comments or suggestions that you may have.
add comment ( 3581 views )   |  permalink   |  $star_image$star_image$star_image$star_image$star_image ( 3 / 1013 )
Minimalist Single LED Clock ( Pi Zero and No Extra Parts ) 
Saturday, June 3, 2017, 10:08
Posted by Administrator


I was inspired by this post on Hackaday where Setvir created an elegant single LED clock using an Arduino Pro Micro. I'm more of a fan of Raspberry Pi's and have been wanting to come up with a simple single LED clock design of my own ever since reading that article.

It occurred to me today that the Pi Zero's status light could be commandeered for this purpose which would eliminate the need for any other additional parts. I considered using Python for this but eventually decided upon using bash scripting as it is already baked in to most common Pi Zero images such as Raspbian or Retropie.

The heavily commented code below is what I came up with to bring this clock design to life:

#!/bin/bash
# A minimalist led clock for the Pi Zero ( And Pi Zero W )
# Uses only the onboard led to blink the current hour
# And then to quickly blink the the tens place of minutes
#
# Spike Snell - June 2017

# First set the trigger for the onboard green led to none so that we have control of it
echo none | sudo tee /sys/class/leds/led0/trigger

# Turn off the led so that we have a known state to start
echo 1 | sudo tee /sys/class/leds/led0/brightness

# Loop endlessly
while true
do

# Wait for a full second to seperate our visual count
sleep 1

# Loop for the current number of hours
# Trim leading 0's so that 08 and 09 aren't interpreted as an octal base
for ((n=0;n<$(date +"%I" | sed 's/^0*//');n++))

do

# Wait a bit
sleep .25

# Turn the led on
echo 0 | sudo tee /sys/class/leds/led0/brightness

# Wait a bit
sleep .25

# Turn the led off
echo 1 | sudo tee /sys/class/leds/led0/brightness

done

# Wait for a half second
sleep .5

# Now loop very quickly for the current first tens digit of minutes
for ((n=0;n<$(date +"%M" | head -c 1);n++))

do

# Wait for a small bit
sleep .1

# Turn the led on
echo 0 | sudo tee /sys/class/leds/led0/brightness

# Wait for a small bit
sleep .1

# Turn the led off
echo 1 | sudo tee /sys/class/leds/led0/brightness

done

done

I saved the script in my home directory as minimalistClock.sh and made it executable with the command chmod +x minimalClock.sh. It is then run under its own screen with the command screen ./minimalClock.sh since it can be somewhat distracting if running on your main session due to all the echo commands. Screen is also a very handy way to make the clock persist and keep running even after logging out of your current session. Use the command sudo apt-get install screen if you don't already have it installed. After getting the clock up and running in screen you can press ctrl+a then ctrl+d to detach the screen and have it keep running in the background.

The clock is read by counting the number of long blinks to get the hours, and then the number of short blinks to get the tenth place of minutes. For example, 4 longer blinks followed by 3 shorter blinks indicates that the current time is about 4:30. I decided not to use a 24 hour military format for this because that would end up being far too many blinks when late in the day.

This script can be easily added to /etc/rc.local so that it will begin running when the Pi starts up.

This is exactly the minimalistic clock that I have been desiring for so long and it looks great running in my translucent Pi Zero Tic Tac Case which I have attached to the wall. Let me know what you all think of this basic clock design. If it could be made even simpler in some way I would love to experiment with that.

-- Edit March 2018

I have edited the code slighty in order for it to work on a Raspberry Pi 3 B+ ( Probably the non-plus version as well ).

Same idea as before, but this time using the onboard status led on the back of the bigger Pi. For some reason the light/dark values all had to be reversed, but other than that the code is the same. I found that putting a piece of electrical tape over the red led ( Which is always on when the Pi is receiving power ) makes the clock a lot more pleasant to leave on.

#!/bin/bash
# A minimalist led clock for the Pi 3 B+
# Uses only the onboard green led to blink the current hour
# And then to quickly blink the the tens place of minutes
#
# Spike Snell - March 2018

# First set the trigger for the onboard green led to none so that we have control of it
echo none | sudo tee /sys/class/leds/led0/trigger

# Turn off the led so that we have a known state to start
echo 0 | sudo tee /sys/class/leds/led0/brightness

# Loop endlessly
while true
do

# Wait for a full second to seperate our visual count
sleep 1

# Loop for the current number of hours
# Trim leading 0's so that 08 and 09 aren't interpreted as an octal base
for ((n=0;n<$(date +"%I" | sed 's/^0*//');n++))

do

# Wait a bit
sleep .25

# Turn the led on
echo 1 | sudo tee /sys/class/leds/led0/brightness

# Wait a bit
sleep .25

# Turn the led off
echo 0 | sudo tee /sys/class/leds/led0/brightness

done

# Wait for a half second
sleep .5

# Now loop very quickly for the current first tens digit of minutes
for ((n=0;n<$(date +"%M" | head -c 1);n++))

do

# Wait for a small bit
sleep .2

# Turn the led on
echo 1 | sudo tee /sys/class/leds/led0/brightness

# Wait for a small bit
sleep .2

# Turn the led off
echo 0 | sudo tee /sys/class/leds/led0/brightness

done

done

2 comments ( 39849 views )   |  permalink   |  $star_image$star_image$star_image$star_image$star_image ( 3 / 5934 )

<<First <Back | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Next> Last>>