Script that writes text to OLED display

I wrote a small bash script that writes text to the OLED display. It’s just a simple wrapper that pads the text correctly before sending it to /dev/hidraw0 with an “xOLED” command.

It can treat each argument as a separate line or join them together, and it can either clip or wrap each input line. If you run it without any text parameters, it will clear the OLED display.

I wrote it just for fun, and I’m posting it here in case anyone finds it useful or educational.

#!/bin/bash

# In order to run this script, a user needs to have permission to write to /dev/hidraw0. One way
# to do this is to create a udev rule to set the device's group to a group that the user belongs
# to. For example, this command will create a udev rule that sets the group on all hidraw devices
# to 'dialout' and sets their permissions to 660.
#
# $ sudo echo SUBSYSTEM=="hidraw", GROUP="dialout", MODE="0660" > /etc/udev/rules.d/50-hidraw.rules
#
# After creating the rule, restart the machine to reload the device with the new properties.
#
# Make sure to add the user to the group you used, if they aren't already a member of that group.
# See /etc/group for current group membership and the adduser command for assigning a user to a group.


help()
{
	echo "Write some text to the OLED display on MNT Reform."
	echo "Usage: oledmsg [OPTIONS] [TEXT]"
	echo
	echo "The OLED display is 4 lines tall. Each line is 21 characters long."
	echo "If TEXT is omitted, oledmsg will clear the OLED display."
	echo
	echo "Options:"
	echo "	-h	Print this help."
	echo "	-j	Print all text arguments without line breaks. This is the default."
	echo "	-l	Start a new line between each text argument. Long lines will wrap."
	echo "	-c	Start a new line between each text argument. Long lines will be clipped."
	exit
}

JOIN_MODE=0
BREAK_MODE=1
CLIP_MODE=2
MODE=$JOIN_MODE

while getopts :cjl FLAG; do
	case $FLAG in
		c) # line break between args and clip long lines
			MODE=$CLIP_MODE
			;;
		l) # line break between args and wrap long lines
			MODE=$BREAK_MODE
			;;
		\?) # unknown option
			help
			;;
	esac
done

# Shift argument pointer to the end of option arguments (start of text arguments).
shift $((OPTIND-1))

# Build a string according to the chosen mode.
if [ $MODE -eq $BREAK_MODE ]; then
	for ARG in "$@"; do
		for (( i=0; i < ${#ARG}; i+=21 )); do
			MSG+=$(printf "%-21s" "${ARG:(i):21}")
		done
	done
	MSG=$(printf "%-84s" "${MSG}")
elif [ $MODE -eq $CLIP_MODE ]; then
	for ARG in "$@"; do
		MSG+=$(printf "%-21s" "${ARG:0:21}")
	done
	MSG=$(printf "%-84s" "${MSG}")
elif [ $MODE -eq $JOIN_MODE ]; then
	ARGJOIN="$@"
	MSG=$(printf "%-84s" "${ARGJOIN}")
else
	help
fi

# Write the formatted message to the OLED display.
echo "xOLED${MSG:0:84}" > /dev/hidraw0

11 Likes

let’s do a demo compo? :slight_smile: