PCからarduinoにコマンドを送信する方法はたくさんあります。 Sandeep Bansilは、シリアルポートの接続と読み取りの良い例を示しています。
以下は、Windowsフォーム上のチェックボックスの状態に基づいてシリアルポートに書き込む方法の実例です。arduinoのPCからの要求をどのように処理するかを示しています。
これは冗長な例ですが、クリーナーソリューションがありますが、これは明確です。
この例では、arduinoはpcから 'a'または 'b'のいずれかを待ちます。チェックボックスをオンにするとPCは 'a'を送信し、チェックボックスをオフにすると 'b'を送信します。この例では、arduinoのデジタルピン4を想定しています。このコードは、フォームは.csファイルに存在します
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#
。この例では、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
イベントでは、次のコードを使用してデータを確認する必要があります:readLine()
の結果はmyVar
がHello World
が含まれていることになります
//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();
。
何らかの理由で、私の検索は私にそのページをやったことがなかったです。ありがとう。 – ikathegreat