こんにちは。私は USB 接続でハードウェアを制御する初心者です。Arduino UNO マイクロコントローラを持っていて、始めるためのリソースを探していました。私は C# (Visual Studio 2010) でプログラミングしていますが、接続の設定やテストに使用できる基本的なものがあるかどうか疑問に思っています。Arduino のデジタル I/O ピンをハイとローの間で切り替える WinForm のチェック ボックスのようなシンプルなものを探しています。始めるための情報があまり見つかりません。
前もって感謝します。
ベストアンサー1
PC から Arduino にコマンドを送信する方法は多数あります。Sandeep Bansil は、シリアル ポートの接続と読み取りの優れた例を示しています。
以下は、Windows フォームのチェックボックスの状態に基づいてシリアル ポートに書き込む方法と、Arduino で PC からの要求を処理する方法の実例です。
これは冗長な例です。より簡潔な解決策もありますが、これはより明確です。
この例では、Arduino は PC からの「a」または「b」を待機します。PC は、チェックボックスがオンになっている場合は「a」を送信し、チェックボックスがオフになっている場合は「b」を送信します。例では、Arduino のデジタル ピン 4 を想定しています。
Arduinoコード
#define DIGI_PIN_SOMETHING 4
unit8_t commandIn;
void setup()
{
//create a serial connection at 57500 baud
Serial.begin(57600);
}
void loop()
{
//if we have some incomming serial data then..
if (Serial.available() > 0)
{
//read 1 byte from the data sent by the pc
commandIn = serial.read();
//test if the pc sent an 'a' or 'b'
switch (commandIn)
{
case 'a':
{
//we got an 'a' from the pc so turn on the digital pin
digitalWrite(DIGI_PIN_SOMETHING,HIGH);
break;
}
case 'b':
{
//we got an 'b' from the pc so turn off the digital pin
digitalWrite(DIGI_PIN_SOMETHING,LOW);
break;
}
}
}
}
Windows C#
このコードはフォームの .cs ファイルにあります。 この例では、チェックボックスに OnOpenForm、OnCloseForm、および OnClick イベントのフォーム イベントが添付されていることを前提としています。 各イベントから、以下のそれぞれのメソッドを呼び出すことができます。
using System;
using System.IO.Ports;
class fooForm and normal stuff
{
SerialPort port;
private myFormClose()
{
if (port != null)
port.close();
}
private myFormOpen()
{
port = new SerialPort("COM4", 57600);
try
{
//un-comment this line to cause the arduino to re-boot when the serial connects
//port.DtrEnabled = true;
port.Open();
}
catch (Exception ex)
{
//alert the user that we could not connect to the serial port
}
}
private void myCheckboxClicked()
{
if (myCheckbox.checked)
{
port.Write("a");
}
else
{
port.Write("b");
}
}
}
ヒント:
Arduino からメッセージを読み取る場合は、50
または100
ミリ秒間隔のタイマーをフォームに追加します。
OnTick
タイマーの場合は、次のコードを使用してデータをチェックする必要があります。
//this test is used to see if the arduino has sent any data
if ( port.BytesToRead > 0 )
//On the arduino you can send data like this
Serial.println("Hellow World")
//Then in C# you can use
String myVar = port.ReadLine();
の結果readLine()
は をmyVar
含みますHello World
。