LoginSignup
2
3

More than 3 years have passed since last update.

EV3とRaspberryPi間のシリアル通信方法_2

Posted at

ここでは、EV3とRaspberryPiの間でシリアル通信する方法を紹介します。
この方法を応用することで、RaspberryPiでEV3のセンサーを扱うことができたり、RaspberyPiのカメラを用いることで、カメラを使った制御をEV3で行うことができます。

使用するもの

  • RaspberryPi3 Model B+
  • SDカード:RaspberyPi用
  • EV3Console
  • データ通信が可能なUSBケーブル (TypeA to MicroB USB2.0)
  • 教育版レゴ マインドストーム EV3
  • SDカード:EV3RT用

1. pyserialのインストール

RaspberryPiでシリアル通信を行う準備をします。
まずは、DNS設定を確認します。
RaspberryPiのコンソールを開き、以下のコマンドを入力します。

User@linux:~$ cat /etc/network/interfaces

表示される文字列に、以下のような記載が含まれるか確認します。
「nameserver 0.0.0.0」 ※実際には0ではありません。
なければ、DNSの設定をする必要があります。

以下のコマンドを入力して、設定を確認します。

User@linux:~$ cat /etc/resolv.conf

以下のような記載部分の数値を確認します。
「nameserver 0.0.0.0」 ※実際には0ではありません。
「/etc/network/interfaces」をviエディタで編集し、先ほど確認した確認した文字列を書き込みます。

User@linux:~$ sudo vi /etc/network/interfaces

DNS設定が完了したら、以下のコマンドを入力し、pyserialをインストールします。

User@linux:~$ sudo apt install python3-pip
User@linux:~$ pip3 install pyserial

2. EV3RTの準備

EV3をC言語で動かすための、EV3RT環境を導入します。
※ここでは詳細は省きます。
以下のリンクを参照ください。
開発環境構築手順
プラットフォームのインストール

また、SDカード(Raspbery Pi用と別のもの)に上記でダウンロードしたパッケージ内の「sdcard」フォルダの中身をコピーします。
シリアル通信に使用するポートでは、設定を無効かする必要があります。
「ev3rt/etc/rc.conf.ini」に以下の内容を追記します。※シリアル通信に使うポート番号を指定します。

ev3rt/etc/rc.conf.ini
[Sensors]
DisablePort1=1

シリアル通信プログラム Raspbery Pi → EV3

EV3 → Raspbery Piの順に実行します。
EV3側では、以下のプログラムを実行します。

app.c
#include <string.h>
#include <stdio.h>

#include "ev3api.h"
#include "app.h"

#if defined(BUILD_MODULE)
#include "module_cfg.h"
#else
#include "kernel_cfg.h"
#endif

static FILE *serial = NULL;  

void main_task(intptr_t unused) {
    ev3_sensor_config (touch_sensor,TOUCH_SENSOR);
    char lcdstr[100];

    // Open serial port
    serial = ev3_serial_open_file(EV3_SERIAL_UART);  
    assert(serial != NULL);
    // read string
    fgets(lcdstr, 6, serial);
    ev3_lcd_draw_string(lcdstr, 0, 10);
}

Raspberry Pi側では以下のプログラムを実行します。

serialTest.py
import serial
import time

# serial communication(Raspi-> EV3)
ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=None)
ser.reset_input_buffer()


def write(msg):
    ser.write(bytes(msg,'UTF-8'))


def read():
    while True:
        r = ser.read(1)
        if r == b'xfe':
            break
    r = ser.read(1)
    return int(r[0])

def close():
    ser.close()

msg = 'Hello'
write(msg)
close()

EV3のLCDに「Hello」の文字列が表示されれば成功です。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3