Skip to content

Instantly share code, notes, and snippets.

@monorkin
Last active January 12, 2017 13:37
Show Gist options
  • Save monorkin/9bf6168e355e5c7c1bdb638f54508d09 to your computer and use it in GitHub Desktop.
Save monorkin/9bf6168e355e5c7c1bdb638f54508d09 to your computer and use it in GitHub Desktop.
Simple script for sending and reading serial data from your Arduino on *nix systems
#!/bin/bash
# Configuration
DEVICE=/dev/ttyACM0
BAUD=9600
SEND=""
FOLLOW=0
RECEIVE=0
HELP=0
# Utility functions
function print_instructions {
echo "Usage:"
echo " $0 [-d|--device DEVICE] [-b|--baud BAUD] [-f|--follow] [receive|send data]"
echo " Note: If no device is specified '$DEVICE' is used as the default."
echo " If no BAUD rate is specified '$BAUD' is used as the default."
echo "Examples:"
echo " Sending data:"
echo " $0 -d /dev/ttyACM1 send \"Hello world!\""
echo " Receiving data:"
echo " $0 -b 11600 receive"
echo ""
}
# Read options
while [[ $# -gt 0 ]]
do
key="$1"
case $key in
-b|--baud)
BAUD="$2"
shift
;;
-d|--device)
DEVICE="$2"
shift
;;
send)
SEND="$2"
shift
;;
receive)
RECEIVE=1
shift
;;
-f|--follow)
FOLLOW=1
;;
--help)
HELP=1
;;
*)
# unknown option
;;
esac
shift # past argument or value
done
# Check inputs
if [ "$HELP" -eq 1 ]; then
print_instructions
exit 0
fi
if [ "$SEND" == "" ] && [ "$RECEIVE" -eq 0 ]; then
echo "A data transfer method has to be specified!"
echo "Data has to be eather sent or received."
echo "Use the 'send' or 'receive' commands to specify data flow."
echo ""
print_instructions
exit 1
fi
# Initialization
echo "Initializing device..."
stty -F $DEVICE cs8 $BAUD ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts
# Execution
if [ "$SEND" != "" ]; then
echo "Sending data..."
echo "$SEND" > $DEVICE
if [ "$FOLLOW" -eq 1 ]; then
echo "Following output"
echo "-------------------------------------"
cat < $DEVICE
fi
fi
if [ "$RECEIVE" -eq 1 ]; then
echo "Receiving data..."
echo "-------------------------------------"
cat < $DEVICE
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment