#!/bin/bash

# The GPIO that controls the sound volume
pin=17

# Configure the GPIO as input
echo $pin > /sys/class/gpio/export
echo in > /sys/class/gpio/gpio$pin/direction

# Read the state of the input
previous=$(cat /sys/class/gpio/gpio$pin/value)

# Loop forever
while true
do
  # Read the input
  state=$(cat /sys/class/gpio/gpio$pin/value)

  # If the state is not the same as the previous state
  if [ $state -ne $previous ]
  then
    # Determine the control character
    if [ $state -eq "1" ]
    then
      ch='+'
    else
      ch='-'
    fi
    
    # Turn the volume up or down in five steps
    for i in {1..5}
    do
      echo -n $ch
      sleep 0.5
    done
  fi

  # Wait a bit to keep the system load low
  sleep 0.5

  # Update the previous state for the next round
  previous=$state

done | omxplayer --loop  '/usr/share/scratch/Media/Sounds/Music Loops/Garden.mp3'
