#!/bin/sh 
prg="adude"
# atmega88:
# avrdude: Device signature = 0x1e930a
# avrdude: safemode: lfuse reads as 62 = 0110 0010
# avrdude: safemode: hfuse reads as DF
# avrdude: safemode: efuse reads as 1
#
# CKSEL3..0 = 0000 (external)  (page 33) ->lfuse=60
# CKSEL3..0 = 0010 (internal)  (page 26)
# CKSEL3..1 110 (external low power) (page 28)
# CKSEL3..0 = 1111-0000 (low power external) (page 26)
# CKDIV
# SUT (page 30 and 32) default is SUT1..0=10
# CLKPS/CLKPR page 35
# fuse bytes pages 282 and 283
help()
{
	echo "prg_fusebit_uc_88 -- read fuse bits of the atmega88"
	echo ""
	echo "Usage: prg_fusebit_uc_88 [-hu] -r|-w lowfuse"
	echo ""
	echo "OPTIONS: -h this help"
	echo "         -r read fuse bytes"
	echo "         -u use uisp instead of avrdude"
	echo "            avrdude can automatically detect dapa or avrusb500."
	echo "            uisp can only be used with the parallel port dapa."
	echo "         -w write the low fuse byte (60=ext clock on xtal1, 62 internal)"
	echo ""
	echo "EXAMPLE: read the fuse bytes"
	echo "         prg_fusebit_uc -r"
	echo ""
	echo "Note: The atmega88 allows you to change clock speeds on the fly in software"
	echo "      This is quite different from atmega8 where it was necessary to modify"
	echo "      the fuses. With the atmega88 there is actually no good reason why"
	echo "      one should change the default factory settings as long as you use"
	echo "      the internal osciallator"
	exit 0
}
while [ -n "$1" ]; do
case $1 in
    -h) help;shift 1;;
    -u) prg="uisp";shift 1;;
    -r) opt_r="1";shift 1;;
    -w) opt_w="1";lf="$2";shift 2;;
    -*) echo "error: no such option $1. -h for help";exit 1;;
    *)  break;;
esac
done

if [ -z "$opt_r" -a -z "$opt_w" ];then
	# one of those options is mandatory
	help
fi
hf=0xdf

if [ "$prg" = "uisp" ]; then
	if [ "$opt_r" = "1" ];then
		set -x
		uisp -dlpt=/dev/parport0 -dprog=dapa --rd_fuses
		set +x
		echo "Explanation: Fuse Low Byte: 0x62 (1MHz intern), 0xe2 (8MHz intern) "
		echo "             Note that CLKPR will finally influence the clock"
		echo "             Fuse High Byte should be 0xdf"
		echo "             Euse High Byte should be 1"
		exit 0
	fi
	if [ "$opt_w" = "1" ]; then
		set -x
		uisp -dlpt=/dev/parport0 -dprog=dapa --wr_fuse_l=$lf
		#uisp -dlpt=/dev/parport0 -dprog=dapa --wr_fuse_h=$hf
		set +x
		exit 0
	fi

fi
if [ "$prg" = "adude" ]; then
	if grep "Vendor=0403 ProdID=6001" /proc/bus/usb/devices > /dev/null ; then
		prg="avrusb500"
	else
		prg="dapa"
	fi
	if [ "$opt_r" = "1" ];then
		set -x
		avrdude -p m88 -c $prg -v -q
		set +x
		echo "Explanation: Fuse Low Byte: 0x62 (1MHz intern), 0xe2 (8MHz intern) "
		echo "             Note that CLKPR will finally influence the clock"
		echo "             Fuse High Byte should be 0xdf"
		echo "             Euse High Byte should be 1"
		exit 0
	fi
	if [ "$opt_w" = "1" ]; then
		set -x
		avrdude -p m88 -c $prg -u -v -U lfuse:w:$lf:m
#		avrdude -p m88 -c $prg -u -v -U hfuse:w:$hf:m
		set +x
		exit 0
	fi
fi
