Skip to content

Instantly share code, notes, and snippets.

@duckythescientist
Last active September 4, 2019 01:42
Show Gist options
  • Save duckythescientist/3386798f60b7f48694372ebbc86b5a28 to your computer and use it in GitHub Desktop.
Save duckythescientist/3386798f60b7f48694372ebbc86b5a28 to your computer and use it in GitHub Desktop.
Blink text as morse code to the Raspberry Pi built-in LED
#!/usr/bin/env bash
# Blink out text using the Pi's built-in status LED
# Example usage: ./morse_echo.sh hello world
# Requires root for the Raspberry Pi
DIT_SPACE="0.2"
INTER_CHARACTER_SPACE="0.4" # 2xDIT_SPACE for normal timing (3 total)
INTER_WORD_SPACE="0.8" # 4xDIT_SPACE for normal timing (7 total)
# Increase INTER_WORD_SPACE and INTER_CHARACTER_SPACE more than "normal" for Farnsworth timing
# This may break in the future:
# Check if we are a Pi by the OUI
ifconfig eth0 | grep -q 'b8:27:eb' || ifconfig eth0 | grep -q 'dc:a6:32'
IS_RASPBERRY=$?
ifconfig eth0 | grep -q 'dc:a6:32'
IS_PI4=$?
if [ $IS_PI4 -eq 0 ]; then
ON=1
OFF=0
else
ON=0
OFF=1
fi
if [ $IS_RASPBERRY -eq 0 ]; then
echo none > /sys/class/leds/led0/trigger
fi
signal_on() {
if [ $IS_RASPBERRY -eq 0 ]; then
echo $ON >/sys/class/leds/led0/brightness
else
echo -n "******"
fi
}
signal_off() {
if [ $IS_RASPBERRY -eq 0 ]; then
echo $OFF >/sys/class/leds/led0/brightness
else
echo -ne "\b\b\b\b\b\b \b\b\b\b\b\b"
fi
}
finish() {
if [ $IS_RASPBERRY -eq 0 ]; then
echo "mmc0" >/sys/class/leds/led0/trigger # Default configuration
else
echo "finishing"
fi
}
trap finish EXIT
encode() {
declare -A morse
morse[A]=".-";
morse[B]="-...";
morse[C]="-.-.";
morse[D]="-..";
morse[E]=".";
morse[F]="..-.";
morse[G]="--.";
morse[H]="....";
morse[I]="..";
morse[J]=".---";
morse[K]="-.-";
morse[L]=".-..";
morse[M]="--";
morse[N]="-.";
morse[O]="---";
morse[P]=".--.";
morse[Q]="--.-";
morse[R]=".-.";
morse[S]="...";
morse[T]="-";
morse[U]="..-";
morse[V]="...-";
morse[W]=".--";
morse[X]="-..-";
morse[Y]="-.--";
morse[Z]="--..";
morse[1]=".----";
morse[2]="..---";
morse[3]="...--";
morse[4]="....-";
morse[5]=".....";
morse[6]="-....";
morse[7]="--...";
morse[8]="---..";
morse[9]="----.";
morse[0]="-----";
morse[" "]=" ";
text="$*" # All arguments as a single string separated by $IFS (space)
text="${text^^}" # Capitalize all letters
# Loop through the characters by index
for (( k = 0; k < ${#text}; k=k + 1 )); do
char="${text:$k:1}"
mchar="${morse[$char]}" # Morse lookup
# echo "$mchar"
# Loop through morse characters
for (( i = 0; i < ${#mchar}; i=i + 1)); do
case "${mchar:$i:1}" in
"-")
signal_on
sleep "$DIT_SPACE"
sleep "$DIT_SPACE"
sleep "$DIT_SPACE"
signal_off
sleep "$DIT_SPACE"
;;
".")
signal_on
sleep "$DIT_SPACE"
signal_off
sleep "$DIT_SPACE"
;;
" ")
sleep "$INTER_WORD_SPACE"
;;
*)
sleep "$INTER_WORD_SPACE"
;;
esac
done
sleep "$INTER_CHARACTER_SPACE"
done
}
encode "$*"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment