次にWiiRemoteのLED制御についてプログラミングを行っていきます。
ここでは、Formボタンをクリックする毎にWiiRemoteのLEDを変化させます。
1.WiimoteLibの宣言と接続
Form.csに以下の部分を追加する。 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WiimoteLib;
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
Wiimote wm = new Wiimote(); //Wiimoteの宣言
int count=0; //カウントの宣言
public Form1() {
InitializeComponent();
wm.Connect(); //Wiimoteの接続
}
}
}
2.ボタン1の作成
1.フォームにボタンを貼り付けてください。 ※ボタンは少し大き目に配置してください。
2.貼り付けたbutton1をダブルリックして、以下のように追加する。 private void button1_Click(object sender, EventArgs e) {
this.button1.Text ="wm.SetLEDs("+ count+") を表示中";
this.wm.SetLEDs(count);
count++;
}
以上で終了です。たったこれだけのプログラムでWiiRemoteのLED制御が可能になります。
Form1.csのソース
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WiimoteLib;
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
Wiimote wm = new Wiimote(); //Wiimoteの宣言
int count=0; //カウントの宣言
public Form1() {
InitializeComponent();
wm.Connect(); //Wiimoteの接続
}
private void button1_Click(object sender, EventArgs e) {
this.button1.Text = "wm.SetLEDs(" + count + ") を表示中";
this.wm.SetLEDs(count);
count++;
}
}
}
実行
1.WiiRemoteを接続してください。
2.F5キーを押して実行してください。
実行すると下図のようなアプリケーションが起動します。
※もし下図のようなエラーが発生する場合はWiiRemoteが正しく接続されているか確認してください。
3.button1ボタンをクリックしてください。
4.wm.SetLEDs(0)ボタンをクリックしてください。
5.wm.SetLEDs(1)を表示中ボタンをクリックしてください。
6.wm.SetLEDs(2)を表示中ボタンをクリックしてください。
7.wm.SetLEDs(3)を表示中ボタンをクリックしてください。
8.wm.SetLEDs(4)を表示中ボタンをクリックしてください。
9.wm.SetLEDs(5)を表示中ボタンをクリックしてください。
10.wm.SetLEDs(6)を表示中ボタンをクリックしてください。
11.wm.SetLEDs(7)を表示中ボタンをクリックしてください。
12.wm.SetLEDs(8)を表示中ボタンをクリックしてください。
13.wm.SetLEDs(9)を表示中ボタンをクリックしてください。
14.wm.SetLEDs(10)を表示中ボタンをクリックしてください。
15.wm.SetLEDs(12)を表示中ボタンをクリックしてください。
16.wm.SetLEDs(13)を表示中ボタンをクリックしてください。
17.wm.SetLEDs(14)を表示中ボタンをクリックしてください。
18.wm.SetLEDs(15)を表示中ボタンをクリックしてください。
解説
SetLEDs(int32 leds);
引数に数値をれることで、対応するLEDが変化します。
このプログラムではcountの値を入れ SetLEDs(count); としています。 そしてFormに配置されたボタンをクリックすると、count値が+1されます。
引数の数値は二進数になってWiiRemoteを逆さまにした状態のLEDに対応しています。
| 10進数 |
二進数 |
| LED4 |
LED3 |
LED2 |
LED1 |
| 0 |
0 |
0 |
0 |
0 |
| 1 |
0 |
0 |
0 |
1 |
| 2 |
0 |
0 |
1 |
0 |
| 3 |
0 |
0 |
1 |
1 |
| 4 |
0 |
1 |
0 |
0 |
| 5 |
0 |
1 |
0 |
1 |
| 6 |
0 |
1 |
1 |
0 |
| 7 |
0 |
1 |
1 |
1 |
| 8 |
1 |
0 |
0 |
0 |
| 9 |
1 |
0 |
0 |
1 |
| 10 |
1 |
0 |
1 |
0 |
| 11 |
1 |
0 |
1 |
1 |
| 12 |
1 |
1 |
0 |
0 |
| 13 |
1 |
1 |
0 |
1 |
| 14 |
1 |
1 |
1 |
0 |
| 15 |
1 |
1 |
1 |
1 |
|
0:LED OFF
1:LED ON
10進数の16になるとLED0~LED4桁目は0になるのでLEDは全て消える。
また、引数を4つ指定してLEDを制御することが可能である。
SetLEDs(bool led1 ,bool led2 ,bool led3,bool led4);
引数には、bool型を用いる。boll型はtrue,flaseしかなく、必ずどちらかの値を入れる。
true:LED ON
false:LED OFF
例えば、図のようにLEDを1011と点灯させる場合は
this.wm.SetLEDs(true,true,false,false); とすればよい。