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
。