{"id":872,"date":"2023-04-08T07:34:37","date_gmt":"2023-04-08T07:34:37","guid":{"rendered":"https:\/\/samndave.org.uk\/ourdoc\/?p=872"},"modified":"2025-07-10T16:11:33","modified_gmt":"2025-07-10T16:11:33","slug":"lego-mindstorms-ev3-and-remote-control","status":"publish","type":"post","link":"https:\/\/samndave.org.uk\/index.php\/2023\/04\/08\/lego-mindstorms-ev3-and-remote-control\/","title":{"rendered":"Lego Mindstorms EV3 and remote control"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">The Lego Mindstorms EV3 is the programmable &#8216;brick&#8217; at the heart of the Lego Mindstorms system. However one thing lacking in Mindstorms is remote control options. There is an infrared controller, but this has a limited range of about 2 meters. You can associate a PS4 game controller, but options for an Xbox controller seem to be limited. Using the menus, we could not get one to pair. It needed some further investigation and it was clear the power of Python (rather than the default graphical language) was going to be needed. Rather pleasingly, when you run Python, it is actually running a small Linux distribution, giving you a great deal of power and control of the EV3 unit.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">With a SD card to provide an image, you can install python by following the instructions at <a href=\"https:\/\/education.lego.com\/en-us\/product-resources\/mindstorms-ev3\/teacher-resources\/python-for-ev3\">Lego Education<\/a>. This will run the <a href=\"https:\/\/pybricks.com\/\">Pybricks<\/a> distribution of MicroPython, a limited version of python designed for microcontrollers. Because of this it does not have all the modules available that you may expect from a full blown version of Python.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To see what we have available, boot the EV3 into the Python image (EV3DEV), start a new blank project and add the line <code>help(\"modules\")<\/code>. You should see a list of modules similar to below:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>__main__          mmap              pybricks\/tools    ufcntl\n_thread           nxtdevices_c      pybricks\/uev3dev\/__init__           uhashlib\narray             parameters_c      pybricks\/uev3dev\/_alsa              uheapq\nbluetooth_c       pybricks\/__init__ pybricks\/uev3dev\/_wand              uio\nbtree             pybricks\/bluetooth                  pybricks\/uev3dev\/display            ujson\nbuiltins          pybricks\/display  pybricks\/uev3dev\/i2c                umachine\ncmath             pybricks\/ev3brick pybricks\/uev3dev\/messaging          uos\ncore              pybricks\/ev3devices                 pybricks\/uev3dev\/sound              urandom\nev3devices_c      pybricks\/ev3devio pybricks\/uev3dev\/util               ure\nexperimental_c    pybricks\/experimental               robotics_c        uselect\nffi               pybricks\/hubs     sys               usignal\nframebuf          pybricks\/iodevices                  termios           usocket\ngc                pybricks\/media\/ev3dev               tools             ussl\nhubs_c            pybricks\/messaging                  ubinascii         ustruct\niodevices_c       pybricks\/nxtdevices                 ucollections      utime\nmath              pybricks\/parameters                 ucryptolib        utimeq\nmedia_ev3dev_c    pybricks\/robotics uctypes           uwebsocket\nmicropython       pybricks\/speaker  uerrno            uzlib<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Using a wireless keyboard<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A wireless keyboard is probably the easiest remote input, as wireless keyboards are very common and follow a well defined input standard. However there is no native support within Pybricks. You can read from stdin, but if you don&#8217;t have a remote console, that is not going to work. But, a wireless keyboard will appear like a standard Linux input device. From Visual Studio Code, open an SSH session to the device and then (once you have plugged the wireless keyboard USB dongle into the USB port), type <code>lsusb<\/code>. If it is listed then keyboard input can be tested with <code>evtest<\/code>. Select the input device that looks like your keyboard (usually event2) and tap a few keys. If you see output, then it can receive input from the keyboard.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">All very well, but how can this be used from python? Hard coding in the device event number, the following code will show keyboard presses in terms of a code number.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#!\/usr\/bin\/env pybricks-micropython\nfrom pybricks.hubs import EV3Brick\nfrom pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,\n                                 InfraredSensor, UltrasonicSensor, GyroSensor)\nfrom pybricks.parameters import Port, Stop, Direction, Button, Color\nfrom pybricks.tools import wait, StopWatch, DataLog\nfrom pybricks.robotics import DriveBase\nfrom pybricks.media.ev3dev import SoundFile, ImageFile\n\nimport struct\nimport time\nimport sys\n\n# Reading raw keyboard input from \/dev\/input, see:\n# https:\/\/stackoverflow.com\/questions\/5060710\/format-of-dev-input-event\n\n\n# Create your objects here.\nev3 = EV3Brick()\n\ndevice=\"\/dev\/input\/event2\"\n\n\"\"\"\nFORMAT represents the format used by linux kernel input event struct\nSee https:\/\/github.com\/torvalds\/linux\/blob\/v5.5-rc5\/include\/uapi\/linux\/input.h#L28\nStands for: long int, long int, unsigned short, unsigned short, unsigned int\n\"\"\"\nFORMAT = 'llHHI'\nEVENT_SIZE = struct.calcsize(FORMAT)\n\n#open file in binary mode\nin_file = open(device, \"rb\")\n\nevent = in_file.read(EVENT_SIZE)\n\nprint(\"Starting keyboard test....\")\nwhile event:\n    (tv_sec, tv_usec, type, code, value) = struct.unpack(FORMAT, event)\n\n    if type != 0 or code != 0 or value != 0:\n        print(\"Event type %u, code %u, value %u at %d.%d\" % \\\n            (type, code, value, tv_sec, tv_usec))\n    else:\n        # Events with code, type and value == 0 are \"separator\" events\n        print(\"===========================================\")\n\n    event = in_file.read(EVENT_SIZE)\n\nin_file.close()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">That is not immediately useful. What key is being pressed? How does the code relate to something useful like &#8216;A&#8217;? All we receive is the raw code number for each key.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There is a lookup table in the linux headers, <code>\/usr\/include\/linux\/input-event-codes.h<\/code>, on most linux systems, but not on pybricks. If you have access to a linux system, a file of &#8216;&lt;key> &lt;code>&#8217; can be created with <code>grep '#define' \/usr\/include\/linux\/input-event-codes.h | grep 'KEY_' | awk '{printf(\"%s %s\\n\", $2, $3)}' > keyMap<\/code>, or my copy can be downloaded from the <a href=\"https:\/\/github.com\/DaveHartburn\/Random-Mindstorms\/tree\/main\/keyboard_test\">github page<\/a>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In addition we don&#8217;t need to print all the event output. A keyboard event is type=1, the key pressed will be returned in the code. A key up event has a value of 0 and a key down has a value of 1. If we only want to look at key down events, we can simply use an if statement to check for type=1, value=1.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To make things a little more interesting, if a B is pressed, it makes the EV3 beep. This can now become a framework for a keyboard controlled program, triggering motors or servos.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#!\/usr\/bin\/env pybricks-micropython\nfrom pybricks.hubs import EV3Brick\nfrom pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,\n                                 InfraredSensor, UltrasonicSensor, GyroSensor)\nfrom pybricks.parameters import Port, Stop, Direction, Button, Color\nfrom pybricks.tools import wait, StopWatch, DataLog\nfrom pybricks.robotics import DriveBase\nfrom pybricks.media.ev3dev import SoundFile, ImageFile\n\nimport struct\nimport time\nimport sys\n\n# Reading raw keyboard input from \/dev\/input, see:\n# https:\/\/stackoverflow.com\/questions\/5060710\/format-of-dev-input-event\n\n\n# Create your objects here.\nev3 = EV3Brick()\n\ndevice=\"\/dev\/input\/event2\"\n\n# Read keyboard event codes from keyMap\nkeysIn=open(\"keyMap\", \"r\")\nkbdCodes={}\nfor line in keysIn:\n    # Split the line on whitespace\n    sp=line.split()\n    \n    # Ensure there are at least 2 things on the line\n    if(len(sp)>=2):\n        if(sp&#91;0].startswith(\"KEY_\")):\n            key=sp&#91;0]\n            # The code may not be valid hex, ignore\n            try:\n                code=int(sp&#91;1],0)\n                #print(\"Keycode {} to {}\".format(code, key))\n                kbdCodes&#91;code]=key\n            except:\n                pass\n\n\n\"\"\"\nFORMAT represents the format used by linux kernel input event struct\nSee https:\/\/github.com\/torvalds\/linux\/blob\/v5.5-rc5\/include\/uapi\/linux\/input.h#L28\nStands for: long int, long int, unsigned short, unsigned short, unsigned int\n\"\"\"\nFORMAT = 'llHHI'\nEVENT_SIZE = struct.calcsize(FORMAT)\n\n#open file in binary mode\nin_file = open(device, \"rb\")\n\nevent = in_file.read(EVENT_SIZE)\n\nprint(\"Starting keyboard test....\")\n\nwhile event:\n    (tv_sec, tv_usec, type, code, value) = struct.unpack(FORMAT, event)\n\n    if type==1 and value==1:\n        # We should have a keycode mapping for this, but use try, just in case\n        try:\n            key=kbdCodes&#91;code]\n        except:\n            key=\"NONE\"\n        print(key,\"pressed\")\n\n    # Lets try something with the brick, beep on a B\n    if(key==\"KEY_B\"):\n        ev3.speaker.beep()\n\n    event = in_file.read(EVENT_SIZE)\n\nin_file.close()<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Controlling with an Xbox controller<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Although documentation is limited, you can pair an Xbox controller to a EV3, but need to add a wireless card and pull in an extra package first. Eventually I discovered <a href=\"https:\/\/github.com\/hugbug\/ev3\/wiki\/Connecting-Xbox-One-Controller-to-EV3-(EV3DEV-or-LEGO-MicroPython)\">this excellent guide<\/a>. Add a wireless card, open a SSH session and:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sudo apt update\nsudo apt upgrade           # This may take a while\nsudo apt install sysfsutils\nsudo sh -c 'echo module\/bluetooth\/parameters\/disable_ertm = 1 >> \/etc\/sysfs.conf'\nsudo service sysfsutils restart \n\nbluetoothctl\n&#91;bluetooth]# power off\n&#91;bluetooth]# power on\n&#91;bluetooth]# scan on\n&#91;bluetooth]# trust &lt;mac>\n&#91;bluetooth]# pair &lt;mac>\n&#91;bluetooth]# connect &lt;mac><\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Once done, the Xbox controller will typically appear as \/dev\/input\/event2 (assuming you have unplugged the wireless keyboard). It can be tested with evtest in the same way as above. Like the keyboard, you can read and process the raw events in the same way. Hugbug has provided a similar program frame work at <a href=\"https:\/\/github.com\/hugbug\/ev3\/blob\/master\/xbox-info\/xbox-info.py\">https:\/\/github.com\/hugbug\/ev3\/blob\/master\/xbox-info\/xbox-info.py<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Network control<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">With a wireless network card, you could use the sockets library, provide a socket to connect to and send commands to the EV3. I will expand on this later, but a rough guide, see the focus client and server on my <a href=\"https:\/\/github.com\/DaveHartburn\/astroberryAddons\">Astroberry repository<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The Lego Mindstorms EV3 is the programmable &#8216;brick&#8217; at the heart of the Lego Mindstorms [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[29],"tags":[53],"class_list":["post-872","post","type-post","status-publish","format-standard","hentry","category-microcontrollers","tag-mindstorms"],"_links":{"self":[{"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/posts\/872","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/comments?post=872"}],"version-history":[{"count":1,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/posts\/872\/revisions"}],"predecessor-version":[{"id":1140,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/posts\/872\/revisions\/1140"}],"wp:attachment":[{"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/media?parent=872"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/categories?post=872"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/tags?post=872"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}