Blogue de Guillaume DALLAIRE's Blog

August 3, 2012

Using udev rules to run a python script when inserting USB to serial dongle

Filed under: Uncategorized — gdallaire @ 11:22 am

  1. plug your USB to serial cable in the SBC’s USB port.
  2. Check the device’s name:

$ dmesg | tail


Usb 1-2.1: FTDI USB Serial Device converter now attached to ttyUSB0

  1. We need more information about this device:

$ udevadm info -a -n /dev/ttyUSB0 | grep ‘{serial}’ | head -n1

ATTRS{serial}==”A40111OG”
$ udevadm info -a -n /dev/ttyUSB0 | grep ‘{idVendor}’ | head -n1
ATTRS{idVendor}==”0403″
$ udevadm info -a -n /dev/ttyUSB0 | grep ‘{idProduct}’ | head -n1
ATTRS{idProduct}==”6001″

  1. Create the udev rules file :

$ echo ‘SUBSYSTEM==”tty”, ATTRS{serial}==”A40111OG”, ATTRS{idVendor}==”0403″, ATTRS{idProduct}==”6001″, RUN+=”/opt/hello.py %k”’ > /etc/udev/rules.d/99-usbserial.rules

  1. Reload udev:

$ /etc/init.d/udev reload

  1. Create the python script :
$ cat <<EOF > /opt/hello.py

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

serial_port = sys.argv[1]

ser = serial.Serial(port="/dev/"+serial_port, baudrate=115200)
ser.open()
try:
  while 1:
    ser.read()
    ser.write("hello\n\r")
except:
  ser.close()
EOF

(make sure indentation is respected)

  1. Install python-serial package

$ apt-get install python-serial

  1. Connect a null modem cable between the usb2serial cable and a PC, then open a terminal emulator (picocom under linux / putty or hyper terminal under windows) and press enter, you should receive “hello”)

Note: If more than one identical USB to serial cable are in use, the ATTRS{serial} attribute ensures that the right application is ran for the right cable.

No Comments

No comments yet.

RSS feed for comments on this post. TrackBack URL

Sorry, the comment form is closed at this time.

Powered by WordPress