Monday, January 5, 2015

Garmin SL40 ATC VHF Radio Serial Protocol in Bash

The Garmin SL30 and SL40 protocols are used by most aircraft and marine VHF radios.  These radios are very simple AM devices and basically one only needs to set the frequency.

The Emergency/Setup channel is 121.5 MHz.  Don't use it for testing...

Here is a Bash script that will compute a SL40 frequency message complete with its arithmetic checksum, using the bc calculator:

#! /bin/bash
echo Garmin SL40 ATC Radio Protocol

# Set Active Frequency Message
HDR='$PMRRC'    # Header
IDH='0'        # ID
MHZ='119'    # 118 to 136 MHz
KHZ='100'    # multiples of 25 kHz
MOD='N'        # N=normal

SUM=0    # Arithmetic Checksum
MD=0    # MHZ scaled to ASCII decimal value
MA=""    # MHZ in ASCII character
KD=0    # KHZ scaled to ASCII decimal value
KA=""    # KHZ in ASCII character
MODD="" # MOD in ASCII decimal value
IDHD="" # ID high ASCII decimal value
IDLD="" # ID low ASCII decimal value
SUMH="" # Checksum as two digit Hex

# Example: "Set ATC radio to 119.100 MHz Normal"
# '$PMRRC00G4N29\r\n'

if [ -n "$1" ]; then
MHZ=$(echo "$1" | cut -d "." -f 1)   
KHZ=$(echo "$1" | cut -d "." -f 2)
echo "Frequency=$MHZ.$KHZ"

echo "Set serial port USB0 to 9600N81"
stty -F /dev/ttyUSB0 raw
stty -F /dev/ttyUSB0 9600

echo Calculate frequency characters
MD=$(echo "$MHZ - 48" | bc)
MA=$(printf \\$(printf "%o" $MD))
KD=$(echo "$KHZ - 48" | bc)
KA=$(printf \\$(printf "%o" $KD))
echo m=$MA
echo k=$KA

echo Calculate checksum
IDHD=$(printf "%d" "'$IDH")
IDLD=$(printf "%d" "'$IDL")
MODD=$(printf "%d" "'$MOD")
SUM=$(echo "$IDHD + $IDLD + $MD + $KD + $MODD" | bc)
SUM=$(echo "$SUM % 256" | bc)
SUMH=$(printf "%02x" "$SUM")

echo "Frequency Message = $HDR$IDH$IDL$MA$KA$MOD$SUMH"
echo "$HDR$IDH$IDL$MA$KA$MOD$SUMH" > /dev/ttyUSB0

echo "La Voila!"
exit 1

echo Example: atcfreq 123.450
exit 0

The above script will take 119.100 MHz and output the message '$PMRRC00G4N29' to the screen and to the serial port.

Why on earth do I use Bash for this?  Because I'm a masochist and love to fight the Bash automatic type conversions...  

All Linux/UNIX machines have Bash (and Windows has Cygwin), therefore this is an easy way to debug and test any and all black boxes in a lab setting.

Modify at your peril!

No comments:

Post a Comment

On topic comments are welcome. Junk will be deleted.