DeaD_EyE

elobau can bus joystick

Apr 15th, 2021 (edited)
736
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # https://www.amazon.de/gp/product/B07Q812QK8
  2. # https://www.fischl.de/usbtin/
  3. # https://python-can.readthedocs.io/en/master/
  4.  
  5.  
  6. from subprocess import run
  7. from can.interfaces.socketcan import SocketcanBus
  8.  
  9.  
  10. def set_baudrate(interface, bitrate):
  11.     run(["sudo", "ip", "link", "set", interface, "type", "can", "bitrate", str(bitrate)])
  12.  
  13.  
  14. def _set(interface, up_down):
  15.     run(["sudo", "ip", "link", "set", up_down, "dev", "can0"])
  16.  
  17.  
  18. def set_up(interface):
  19.     _set(interface, "up")
  20.  
  21.  
  22. def set_down(interface):
  23.     _set(interface, "down")
  24.  
  25.  
  26. def can_joystick(data):
  27.     D1, D2, D3 = data
  28.     if 0 < D1 <= 0x64:
  29.         direction_x = "right"
  30.         x = D1
  31.     elif 0x9c <= D1 <= 0xFF:
  32.         direction_x = "left"
  33.         x = 0x100 - D1
  34.     elif D1 == 0:
  35.         direction_x = "middle"
  36.         x = 0
  37.  
  38.     if D2 == 0:
  39.         y = 0
  40.         direction_y = "middle"
  41.     else:
  42.         y = 0x100 - D2
  43.         direction_y = "down"
  44.  
  45.     return f"{x:03d}: {direction_x} | {y:03d}: {direction_y} | Button: {bool(D3 & 0x01)}"
  46.  
  47.  
  48.  
  49. if __name__ == "__main__":
  50.     interface = "can0"
  51.     bitrate = 125_000
  52.     node_id = 0x1a4
  53.     set_down(interface)
  54.     set_baudrate(interface, bitrate)
  55.     set_up(interface)
  56.     bus = SocketcanBus(interface)
  57.     while True:
  58.         if (msg := bus.recv()).arbitration_id == node_id:
  59.             print(" "*80, end="")
  60.             print("\r", end="")
  61.             print(can_joystick(msg.data), end="", flush=True)
  62.  
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×