Skip to content

Instantly share code, notes, and snippets.

@jgonet
Created January 11, 2018 09:47
Show Gist options
  • Save jgonet/325fa8e19c3eb00d245f05961991fffd to your computer and use it in GitHub Desktop.
Save jgonet/325fa8e19c3eb00d245f05961991fffd to your computer and use it in GitHub Desktop.
Simple compile/flash script for AVR
#!/bin/bash -e
# Author: Jakub Gonet, 2018
#
# This program is used to compile all *.c/*.cpp files
# present in passed directory to .hex file. Also, generated
# .hex file can be automatically flashed into uC using avrdude.
OPTIND=1 #POSIX var, resets when getopts was used in shell
#---> variables <---#
mcu="atmega8"
avrDudeMcu="m8"
optimalizationFlag="-Os"
#---> functions <---#
#$1 - input
#$2 - output
#$3 - flags
function compile {
local input=$1
local output=$2
local flags=$3
avr-gcc -mmcu=$mcu $optimalizationFlag $flags $input -o $output
}
#$1 - name of .elf file
#$2 - name of output .hex file
function elfFileToHex {
local input=$1
local output=$2
avr-objcopy -O ihex -j .text -j .data $input $output
rm $input
}
#$1 - .hex file to be flashed
function flash {
local hexFile=$1
avrdude -c usbasp -p $avrDudeMcu -U flash:w:$hexFile
}
#---> entry point <---#
input=""
output=""
flash=1
flags=""
while getopts "h?i:o:f:n" opt; do
case "$opt" in
h) echo "Flags:"
echo "-h - help"
echo "-i - a path to project root directory"
echo "-o - name of a output file (.hex)"
echo "-f - additional flags for avr-gcc"
echo "-n - prevents .hex file from flashing"
exit 0
;;
\?)echo "Bad argument. Maybe try -h ?" >&2
exit 1
;;
i) input=$OPTARG
;;
n) flash=0
;;
f) flags=$OPTARG
;;
o) output=$OPTARG
;;
:) echo "Option -$OPTARG requires an argument." >&2
exit 1
;;
esac
done
if [[ -z $input || -z $output ]]
then
echo "-i and -o flag are absent"
exit 1
fi
processedFiles=$(find -regextype posix-extended -regex '.*\.(c|cpp)')
compile "$processedFiles" "${output%%.*}.elf" "$flags"
elfFileToHex "${output%%.*}.elf" "${output%%.*}.hex"
if ((flash))
then
flash "${output%%.*}.hex"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment