13,005
回編集
279行目: | 279行目: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<br> | <br> | ||
最後に、ホストOSのソフトウェアを作成する。<br> | |||
ここでは、Windowsで利用可能なC#と.NET Frameworkを利用して、上述のプロトコルをサポートするTCPクライアントを作成する。<br> | |||
下図のように、ソフトウェアのUIにおいて、ArduinoのIPアドレスとポート番号を指定できるようにしている。<br> | |||
<br> | |||
以下に、.NET FrameworkのTcpClientクラスを使用したソースコードを記述する。<br> | |||
<syntaxhighlight lang="c#"> | |||
using System; | |||
using System.Collections.Generic; | |||
using System.ComponentModel; | |||
using System.Data; | |||
using System.Drawing; | |||
using System.Linq; | |||
using System.Net.Sockets; | |||
using System.Text; | |||
using System.Windows.Forms; | |||
namespace LightApp | |||
{ | |||
public partial class Form1 : Form | |||
{ | |||
public Form1() | |||
{ | |||
InitializeComponent(); | |||
} | |||
private void button1_Click( object sender, EventArgs e ) | |||
{ | |||
SendCommand( true ); | |||
} | |||
private void button2_Click( object sender, EventArgs e ) | |||
{ | |||
SendCommand( false ); | |||
} | |||
void SendCommand( bool on ) | |||
{ | |||
try | |||
{ | |||
var port = int.Parse( textBox2.Text ); | |||
using(var client = new TcpClient( textBox1.Text, port )) | |||
{ | |||
Byte[] data = System.Text.Encoding.ASCII.GetBytes( string.Format( "S:{0}", on ? "1" : "0" ) ); | |||
using(NetworkStream stream = client.GetStream()) | |||
{ | |||
stream.Write( data, 0, data.Length ); | |||
var data = new Byte[256]; | |||
var responseData = String.Empty; | |||
Int32 bytes = stream.Read( data, 0, data.Length ); | |||
responseData = System.Text.Encoding.ASCII.GetString( data, 0, bytes ); | |||
} | |||
} | |||
} | |||
catch(Exception ex) | |||
{ | |||
MessageBox.Show( ex.Message, "Switch", MessageBoxButtons.OK, MessageBoxIcon.Error ); | |||
} | |||
} | |||
} | |||
} | |||
</syntaxhighlight> | |||
<br><br> | |||
__FORCETOC__ | __FORCETOC__ | ||
[[カテゴリ:Arduino]] | [[カテゴリ:Arduino]] |