LoginSignup
4
4

More than 5 years have passed since last update.

UnityでCONTECの産業用リレーボードを制御する

Posted at

1. 概要

I/Oで外部機器とやりとりする際に、Arduinoなどではなく産業用の機器を使いたいことってありますよね。そんなときに頼りになるのがCONTEC。ここではCONTECのリレーボードをUnityから使う方法を説明します。

2. 環境

3. 参考サイト

4. 手順

4.1 ドライバライブラリのダウンロード、インストール

  • ドライバライブラリ API-USBP(WDM) デジタル入出力ドライバ 開発環境(フルセット) Ver. 6.30をダウンロード
    • ダウンロードには会員登録が必要です。
  • INF - WDM - DioForWin10に入っているSetup.exeを実行
    • ダイアログに従ってインストール
  • APIUSBP - DIO - Disk1に入っているsetup.exeを実行
    • ダイアログに従ってインストールする
    • インストールが終了するとヘルプが立ち上がる

4.2 テスト

  • この辺りはマニュアルに沿って実行します。
  • リレーボードに付属の電源を挿し、Mini USBでPCに接続します
  • デバイスマネージャーを開きデバイスのプロパティを開きます

  • 共通設定タブの診断を押します

  • 12個ある緑のボタンを押すと機器からリレーが切り替わる音が聞こえると思います。

4.3 Unityから制御する

  • Unityで空のプロジェクトを立ち上げます。

  • 先程インストールしたAPI-USBPの以下のフォルダ(例:C:\Program Files (x86)\CONTEC\API-USBP(WDM)\Dio\Samples\Inc)に入っているCdioCs.csをAssetフォルダにコピーします。

  • コンソールを見ると以下のようなエラーが沢山出ています。

error CS0227: Unsafe code requires the `unsafe` command line option to be specified. Enable "Allow 'unsafe' code" in Player Settings to fix this error.
  • エラー通りにメニューのEdit - Project Setting - Playerを選びOther Setting - ConfigrationAllow 'unsafe' settingにチェックを入れる。

  • エラーが消えたことを確認

  • HierarchyのCreate - UI - Buttonでボタンを配置する

  • 以下のスクリプトを作成しボタンのOnClickイベントに紐付ける

button.cs
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using CdioCs;

    public class ButtonTest : MonoBehaviour {

      int Ret;
      short Id;
      bool isState0 = false;

      Cdio  dio = new Cdio();

      void Start () {
        Ret = dio.Init ( "DIO000" , out Id );
        Ret = dio.ResetDevice ( Id );

        Debug.Log("State 0");
        Ret = dio.OutBit(Id, 0, 0);
        Ret = dio.OutBit(Id, 1, 1);
        isState0 = true;
      }

      public void OnClick() {
        isState0 = !isState0;

        short[] BitNo = new short[2];
        byte[] Data = new byte[2];        

        if(isState0){
          Debug.Log ("State 0");
          Ret = dio.OutBit ( Id , 0 , 0 );
          Ret = dio.OutBit ( Id , 1 , 1 );
        }
        else {
          Debug.Log ("State 1");
          Ret = dio.OutBit ( Id , 0 , 1 );
          Ret = dio.OutBit ( Id , 1 , 0 );
        }   
      }
    }
  • 実行するとカチっという音が鳴り以下の状態になる。

  • ボタンを押すと再度音が鳴り以下の状態になる。以降ボタンを押すたびに上と下の状態を繰り返す。

  • あとはお好きなように使ってください。

4
4
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
4
4