WuerfelDev
WuerfelDev

Reputation: 140

How to programmatically send data to arduino from bash

i like to send some data through the serial from my Raspberry Pi to the arduino. My problem is sending it, i read something like sudo echo "8933" > /dev/ttyUSB0 but it is not working. Sending though the Serial Monitor in the Arduino-IDE works fine and sudo screen /dev/ttyUSB0 too.

How can i do that programmatically?
It would be nice if it were a bash-script because i want to run it via ssh.

Upvotes: 1

Views: 2108

Answers (2)

sam
sam

Reputation: 506

If you already have some script generating data you'd like to send to your Arduino serial monitor you could try a simple python wrapper to send your data. Something like:

#!/usr/bin/python2
import sys
import serial

def main():
    data = sys.argv

    if data[1:]:
        ser = serial.Serial('/dev/ttyUSB0', 19200, timeout=1)
        for d in data[1:]:
            print d
            ser.write(str(d))                            
        ser.close()

    else:
        print "No Input given!\n"

if __name__ == "__main__":
    main()

This script will take whatever is passed in as an argument, and send it over serial (i.e. to your Arduino serial monitor).

./[this_script] `[your_script]`

This is just something I just whipped together, it should probably be cleaned up. I'd consider getting familiar with Python as its perfectly suited for one-off scriptable tasks such as this.

Upvotes: 1

chepner
chepner

Reputation: 530960

I see two problems with sudo echo "8933" > /dev/ttyUSB0.

  1. echo appends a newline to whatever it outputs. Try printf "8933" instead.

  2. The sudo command only applies to the actual echo. The output file is still opened by "you" (not root) before sudo runs. Try printf "8933" | sudo tee /dev/ttyUSB0 > /dev/null.

Upvotes: 0

Related Questions