Thursday, March 13, 2014

How to run an script/command when a USB is connected to the port with udev in a Raspberry Pi

How to run an script/command when a USB is connected to the port.

Well, first we have to discover some information about the USB device and then we will be able to define rules to indicate the system which script we want to run.

Connect the USB device and enter the next commands

1) Get the serial number of the device

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

    ATTRS{serial}=="1234567890"
    

2) Get the Id Vendor

$ udevadm info -a -n /dev/ttyUSB0 | grep idVendor | head -n1

    ATTRS{idVendor}=="0403"


3) Get the Product Id

$ udevadm info -a -n /dev/ttyUSB0 | grep idProduct | head -n1
 
    ATTRS{idProduct}=="6001"


Now with this information we can write the UDEV rule:

4) Create a new file /etc/udev/rules.d/99-usbserial.rules and insert the line (one line):

$ sudo vi /etc/udev/rules.d/99-usbserial.rules

ACTION=="add", SUBSYSTEM=="usb", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6001", RUN+="YOURSCRIPT_FULLPATH"


5) Save the file and reset the udev service

$ sudo /etc/init.d/udev restart

Ready, now when the USB device is connected the script YOURSCRIPT_FULLPATH will be launch. You also can see the log details of udev in /var/log/daemon.log.

(Note: In my rule I didn't use the serial number :))

Hope help!

No comments:

Post a Comment