LEGO IoT Train

This post is part 1 of 3 of  LEGO IoT Train

This recente release of LEGO EV3 MicroPyhton using ev3dev keeps amazing me. I think that most people didn’t realize the truly meaning of having a full modern operating system under the hood. And also the great work that David Lechner and all others (sorry, too many to name here) have been doing with and around ev3dev.

A few months ago I’ve been playing with the 4DBrix WiFi Train Controller. I already had bought some 4DBrix custom monorail parts including some small RC Servos that they sell in a LEGO-compatible form factor. When ordering a few more extra parts for my Conveyex project I noticed an interesting thing about their WiFi Train Controller – it used MQTT. Well, well, well… a LEGO-compatible RC controller that uses a non proprietary protocol and even better over WiFi, something I’ve been doing with NodeMCU but ‘out of the box’ and not too expensive.

[long dissertation]

Bluetooth and Bluetooth Low Energy (BLE) are great for gadgets but I’m still not convinced. Yes, been a beta tester of SBrick, had reverse engineered part of WeDo2, BOOST and Powered Up… but still think that BLE is not for robotics or even large IoT.

Bluetooth (standard or BLE) requires “a session”. Once a master device connects to a slave, no additional session can be created to that slave. So it’s great to keep reading data from a sensor but not to so great when you need to ‘time share’ to several masters – you need to release the session, that’s OK with SBrick because it keeps working and waiting for further sessions but it’s not OK with LEGO smart hubs because they shut off after a few seconds to save energy.

BLE beacons like iBeacon and Estimote announce all the needed data so a session isn’t needed but to save energy the frequency of the announcement is kept low. Ideally BLE devices should reduce energy consumption while waiting for a session to be stablished but that would increase latency so not so good for robotics and automation: most of the times, if you need to take a decisiona based on remote data or even worst stop a motor you cannot afford to wait.

Also Bluetooth is ‘point-to-point’, like Infra Red RC. Yes, since it’s radio it works through walls and is resiliant to room light conditions… but you cannot route it. If you have many devices to access/control you will find that there is a limit in the number of simultaneous sessions that you BLE controller can sustain (BLED112 states 8, Cambridge CSR just 5). So if you reach that limit on your smartphone or your limited tablet… you’re done. On a laptop or desktop computer you can add extra BLE dongles but then you start dwelling with your operating system idiosyncrasies (Windows guys, I feel your pain).

Now I am not saying that WiFi is the best solution as there are other very interesting wireless technologies like Zigbee and LoRa… but they are not wide spread as WiFi: my smartphone has WiFi, my laptop has WiFi, my SmartTV has WiFi… even my EV3 has WiFi!

[end of dissertation]

So I ordered one of this little fellows and it worked fine:

But I forgot to talk about it here, only wrote a post on Eurobricks forum about it. So now that I have MQTT working out of the box with this LEGO EV3 MicroPython it’s time to get back to the 4DBrix WiFi Train Controller.

4DBrix has a nice tool nControl to design train/monorail track layouts and also control them with their own controllers. It’s available for free download, you just need to give our e-mail and agree with their terms (essentially some fair use conditions including not redistributing it). There are versions for several platforms including Raspberry Pi’s Raspbian and Ubuntu. This tool is needed to configure the WiFi Controller through the USB port and also to eventually upgrade it’s firmware.

On linux, nControl looks for a connected WiFi Controller on ‘/dev/ttyUSB###’. Last year I had a problem with having more than one of this devices already defined so I needed to remove all before connect it:

sudo rm /dev/ttyUSB*

Not sure if this is still needed (4DBrix keeps upgrading the tool, it’s now in version 2019-0-409) but it doesn’t hurt.

After nControl finds the connected WiFi Train Controller (‘/dev/ttyUSB3’) we can configure it to work with our WiFi network and also chose an Alias and a MQTT Broker:

Alias: 4DB2
WiFi Network: SSID
WiFi Password: ****
MQTT Broker: -> use this system => 192.168.1.87

The Alias is important because the internal MQTT client will subscribe to the topic ‘nControl/Alias’. So in my case ‘nControl/4DB2’ (I also have a 4DB1, the first Controller I received had an internal thermal problem with the power regulator so they sent me a second one).

We can specify any MQTT Broker like ‘test.mosquitto.org’ but there is also a ‘Use this system’ option where it finds the IP address of our computer and use it. That’s also usefull because nControl has its own MQTT Broker (based on ‘hbmqtt’ instead of ‘mosquitto’ and requiring authentication so not useful for open IoT projects

Although nControl as an option to verify that the applied configuration is working properly I found no way to know the IP address that the WiFi Train Controller gets so I had to go to my WiFi router and check for connected devices:

ESP_093471 192.168.1.112

The hostname starts with ‘ESP_’ (the device uses a ESP8266 chipset like the NodeMCU board I’ve been using) and got IP ‘192.168.1.112’… not that I need it’s IP address but might be useful for debugging eventual problems later

So I can now control a LEGO motor with it – disconnect USB cable, connect a LEGO battery and motor, power the device on and test it:

mosquitto_pub -h localhost -t "nControl/4DB2" -m "mot,f,1023"

the motor should spin at maximum speed in one direction. To make it spin in the opposite direction:

mosquitto_pub -h localhost -t "nControl/4DB2" -m "mot,b,1023"

And to stop it:

mosquitto_pub -h localhost -t "nControl/4DB2" -m "mot,f,1023"

or just:

mosquitto_pub -h localhost -t "nControl/4DB2" -m "mot,s"

There are a few other commands available but these are enough for what I want

So controlling a LEGO motor with EV3 through WiFi is just a matter of writing opening Visual Studio Code and write a short MicroPython script that publishes the proper messages to ‘nControl/4DB2’ topic.

Since MQTT is not ‘session’ based like Bluetooth we can use multiple Ev3 to control it. So a LEGO train can run over a long track and place several EV3 pBricks in proper places to control it, like this:

Next post I will explain how to do it and show a slightly more useful demo.


Módulo MFL em Tomar

Os meus primeiros 3 módulos MFL (Módulo Ferrovia LEGO) junto dos restantes módulos da PLUG no Tomar BRInCKa 2015:

O  módulo ao centro tem dois desvios motorizados, bem como um «desengatador» no troço de recta entre as duas agulhas. Toda a electrónica está disfarçada por baixo das linhas.

O módulo da direita consiste numa plataforma rotativa motorizada e controlada por um LEGO Mindstorms EV3 correndo ev3dev (uma variante de Debian para o EV3). Sobre o carril um pequeno comboio controlado por SBrick (bluetooth).

O módulo da esquerda, quase 100% da minha marida, começou com uma pequena cascata no nosso presépio do Natal anterior.

A montagem no BRInCKa 2015 não ficou completa por isso todas as demonstrações são manuais, controladas por mim. Neste video gravado em casa é o computador (LEGO Mindstorms EV3) a fazer tudo sozinho:

O que faltou montar e que permite a automação plena? As componentes RFID – por baixo do pequeno comboio há um identificador RFID do tamanho de uma moeda que permite identificá-lo e em certa medida seguir-lhe a posição. Na montagem do video existem dois leitores RFID (USB) por baixo da linha (um no extremo direito e outro junto ao sistema de desengate). O EV3 utiliza esses sensores para perceber se o comboio está nos sítios certos antes de passar à acção seguinte.

ev3dev com USB Hub e USB Audio

Depois de ter Wi-Fi decidi testar mais alguns dispositivos USB que uso com o Raspberry Pi.

Para começar, uma vez que o EV3 apenas tem uma porta USB, imprescindível um hub, de preferência pequeno:

Hub KUNFT 4 Portas USB 2.0 H-088 (na Worten por €6,99)

Com o EV3 ainda desligado liguei-o e a ele o dongle Wi-Fi (ThePiHut).

Da primeira vez não obteve rede, não sei se não esperei tempo suficiente. Retirei o hub, liguei novamente (sem o dongle Wi-Fi) esperei um pouco e depois liguei o dongle e desta vez obtive rede. E a partir daqui cada boot/reboot com tudo ligado funcionou sempre bem.

root@ev3dev:~# lsusb
(...)
Bus 001 Device 002: ID 05e3:0608 Genesys Logic, Inc. USB-2.0 4-Port HUB

Agora o audio:

[Nota: o EV3 já tem uma placa de audio interna, suportada pelo ALSA, e um altifalante interno também. Mas tanto quanto percebi funciona de modo semelhante ao jack audio do Raspberry Pi, por PWM, consumindo CPU… além de ser mono e não permitir ligação externa a um amplificador]

DIY USB to Audio Module for Raspberry PI / Arduino / MAC / PC + More – Green (SKU 315287 na DX – DealExtreme, US$10.88)

root@ev3dev:~# dmesg
(...)
input: Burr-Brown from TI               USB Audio DAC    as /devices/platform/ohci.0/usb1/1-1/1-1.4/1-1.4:1.2/0003:08BB:2704.0001/input/input2
hid-generic 0003:08BB:2704.0001: input: USB HID v1.00 Device [Burr-Brown from TI USB Audio DAC   ] on usb-ohci.0-1.4/input2
(...)
root@ev3dev:~# lsusb
(...)
Bus 001 Device 004: ID 08bb:2704 Texas Instruments Audio Codec
(...)

O ALSA reconhece de imediato a nova placa de som:

root@ev3dev:~# aplay -l
**** List of PLAYBACK Hardware Devices ****
card 0: legoev3 [LEGO Mindstorms EV3 speaker], device 0: LEGO Mindstorms EV3 [LEGO Mindstorms EV3]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 1: DAC [USB Audio DAC], device 0: USB Audio [USB Audio]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
root@ev3dev:~# alsamixer
┌───────────────────────────── AlsaMixer v1.0.28 ──────────────────────────────┐
│ Card: LEGO Mindstorms EV3 speaker                    F1:  Help               │
│ Chip:                                                F2:  System information │
│ View: F3:[Playback] F4: Capture  F5: All             F6:  Select sound card  │
│ Item: Playback                                       Esc: Exit               │
│                                                                              │
│                                     ┌──┐                                     │
│                                     │  │                                     │
│                                     │  │                                     │
│                       ┌───────── Sound Card ─────────┐                       │
│                       │-  (default)                  │                       │
│                       │0  LEGO Mindstorms EV3 speaker│                       │
│                       │1  USB Audio DAC              │                       │
│                       │   enter device name...       │                       │
│                       └──────────────────────────────┘                       │
│                                     │▒▒│                                     │
│                                     │▒▒│                                     │
│                                     │▒▒│                                     │
│                                     │▒▒│                                     │
│                                     └──┘                                     │
│                                      75                                      │
│                                  <Playback>                                  │
│                                                                              │
└──────────────────────────────────────────────────────────────────────────────┘

E para tocar um ficheiro mp3 (previamente trasnferido por ssh):

root@ev3dev:~# apt-get install mpg321
root@ev3dev:~# mpg321 -a hw:1,0 Thunderstruck.mp3

Rock’n Roll!!!

Durante a execução o mpg321 consome entre 22 a 25% de CPU. É um bocado alto (quando se utiliza a rede em simultâneo, por exemplo um update, ocorrem soluços) e como dizem que o SoX consome menos CPU…

root@ev3dev:~# apt-get install sox libsox-fmt-all
root@ev3dev:~# export AUDIODEV=hw:1,0
root@ev3dev:~# play Thunderstruck.mp3

Durante a execução o play consome  20 a 22% de CPU, apenas marginalmente melhor.
Mas como SoX permite vários formatos (wav, ogg…) permite o redireccionamento (pipe) de outros comandos como o espeak:

root@ev3dev:~# espeak -v pt-pt “olá” –stdout | play -t wav –

E temos o nosso EV3 a falar português 🙂

EV3MP3 – Um MP3 Player em LEGO

Encontrei quase por total acaso um projecto muito interessante: ev3dev.

Trata-se de uma versão de Debian para o LEGO Mindstorms EV3. Não há qualquer alteração ao firmware do EV3 – o bootloader do EV3 arranca a imagem do ev3dev instalada num cartão micro-SD.

Alguras horas depois de começar (a maior parte delas apenas a fazer actualizações de sistema já que o EV3 é cerca de 4x mais lento que um Raspberry Pi e como a versão do chipset USB é apenas 1.1 por a ligação Wi-Fi nunca fará mais que 11 mbps) descobri que o ev3dev se dá muito bem com muito do hardware que utilizo com o Raspberry Pi, nomeadamente:

  • Hub USB
  • ThePiHut Wi-Fi USB card
  • Audio USB card

Com meia duzia de linhas temos um shell script que nos saúda num português macarrónico e toca uma música em formato MP3 após ser premido um touch sensor:

#!/bin/bash

# play deve usar USB sound card
export AUDIODEV=hw:1,0

# saudar utilizador

tput clear > /dev/tty0
figlet -f small "Carregue" > /dev/tty0
figlet -f small "para" > /dev/tty0
figlet -f small "ouvir" > /dev/tty0
figlet -f small "musica" > /dev/tty0

espeak -v pt-pt "olá  queres ouvir uma música?" --stdout | play -t wav -

BOTAO=0
while [ $BOTAO -ne "1" ]; do
  BOTAO=$(cat /sys/class/msensor/sensor0/value0)
done

tput clear > /dev/tty0
figlet -f small "No ar:" > /dev/tty0
figlet -f mini "Highway To Hell" > /dev/tty0
figlet -f small "(AC/DC)" > /dev/tty0

mpg321 -a hw:1,0 HighwayToHell.mp3 -g 20

tput clear > /dev/tty0

Para quem tmabém possa estar interessado, após os updates de sistema a versão do kernel é a 3.14.7:

root@ev3dev:~# uname -a
Linux ev3dev 3.14.7-2-ev3dev-pre1 #2 PREEMPT Tue Jul 15 22:29:55 CDT 2014 armv5tejl GNU/Linux

e o htop diz que estou a usar 25 dos 57 MB de RAM disponíveis além de 7 dos 63 MB de swap.

O processador é reconhecido como um ARM926EJ-S rev 5 (v5l):

root@ev3dev:~# cat /proc/cpuinfo
processor    : 0
model name    : ARM926EJ-S rev 5 (v5l)
Features    : swp half thumb fastmult edsp java
CPU implementer    : 0x41
CPU architecture: 5TEJ
CPU variant    : 0x0
CPU part    : 0x926
CPU revision    : 5

Hardware    : LEGO MINDSTORMS EV3 Programmable Brick
Revision    : 0000
Serial        : 0000000000000000

 

Mindstorms EV3 – data de lançamento

«É amanhã dia 1 de Agosto

e tudo em mim é um fogo posto (…)»

Xutos&Pontapés, 1º de Agosto

A 1 de Agosto estará disponível o conjunto educativo via LEGO Education portanto apenas para professores e afins nos EUA, possívelmente um sub-conjunto do que depois estará disponível ao público em geral algures no Outono, segundo a FAQ da LEGO.