さて、私はあなたが推測したreadSensorと呼ばれる関数を持っています..センサーを読み取ります。
しかし、センサーは通常、応答するのに約 100 ミリ秒かかります。したがって、 readSensor 関数では、基本的にタイマーを開始しています。
時限イベントで、シリアルポートを読み取り、応答を取得します。
ただし、これは、readSensor 関数に入れたいときに、応答が onTimedEvent にあることを意味します。
基本的にメインフォームからこれができるようにしたいです。
値 = readSensor()
現時点で私ができることは readSensor() だけであり、timedEvent が発生すると、応答がメッセージボックスに表示されることで返されていることがわかります。
これが私のコードです。(シリアルポートのセットアップなどをたくさん見逃してしまいましたが、私が抱えている問題を見ていただけると幸いです)
タイマーをポーリングしても、プログラムが遅くなるため、関数で100msだけ待機したくありません..
どうにかして応答を readSensor 関数に戻し、フォームに戻したいと考えています。
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using System.Timers;
namespace readSensor
{
public partial class readSens : UserControl
{
public readSens()
{
InitializeComponent();
}
private System.Timers.Timer rTimer;
SerialPort sp = new SerialPort();
private void setupTimer()
{
// Create a timer with a 100ms response.
rTimer = new System.Timers.Timer(100);
rTimer.SynchronizingObject = this;
// Hook up the Elapsed event for the timer.
rTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
string response = getResponse();
}
public string getResponse()
{
string status = "";
byte[] readBuffer = new byte[255];
if (sp.IsOpen)
{
if (sp.BytesToRead > 0) //there is data to read
{
int length = sp.BytesToRead;
for (int i = 0; i < length; i++)
{
readBuffer[i] = (byte)sp.ReadByte();
status = "pass";
return status;
}
}
}
public void readSensor(byte addr)
{
if (!sp.IsOpen)
{
openPort();
readSensor(addr); // calls itself again once port is opened
}
else if (sp.IsOpen)
{
rTimer.Start();
}
else
{
MessageBox.Show("Port not opened yet");
}
}
}
}
メインフォームでは、基本的に言っているだけです
setupTimer();
readSensor();
ボタンクリックで。