好evenig,使用C#
MS Visual Community 2015
有沒有更好的方法來實現以下問題?我很確定,但我是C#的新手,所以纔是問題所在。「事件處理」的效率
private void button6_Click(object sender, EventArgs e)
{
byte[] a = new byte[9]; // this is just command for motor
a[0] = 1; // to start rotating
a[1] = 1; //
a[2] = 0; //
a[3] = 0; //
a[4] = 0; //
a[5] = 0; //
a[6] = 0; //
a[7] = 63; //
a[8] = 65; //
serialPort3.Write(a, 0, a.Length);
string b = serialPort2.ReadLine();
decimal caliber = decimal.Parse(Regex.Split(b, "SR,00,002,")[1]);
decimal b1 = 0;
do
{
serialPort2.WriteLine("SR,00,002\r\n");
string z = serialPort2.ReadLine();
b1 = decimal.Parse(Regex.Split(z, "SR,00,002,")[1]);
}
while (b1 <= caliber);
byte[] c = new byte[9]; // this is command to stop rotating
c[0] = 1; //
c[1] = 3; //
c[2] = 0; //
c[3] = 0; //
c[4] = 0; //
c[5] = 0; //
c[6] = 0; //
c[7] = 0; //
c[8] = 04; //
serialPort3.Write(c, 0, c.Length);
}
我有運動指令作爲額外的功能,這只是用於測試。我的目標是旋轉電機,直到SerialPort
返回值的變化。 serialPort2
是一個傳感器,默認值約爲-3500(總是稍微改變一下,因此我把它設置爲口徑)。電機移動傳感器。我希望電動機一旦從口徑發生變化就停止(並且機動車將被保存)。
我的代碼按計劃運行,並且在我的機器上運行得相當快,但我不確定它是否有效,因爲它必須經常檢查串行端口2超級。
我還會創建一個額外的函數來從串口讀取和返回數據。在我的理解中,它不會改變代碼的運行方式,除了看起來更短。
我的程序中的這部分內容僅用於一次開始校準,並沒有經常使用,但如果出現類似的情況,比如「直到發生特定事件才執行事件A」,應該稍後需要,並且出於興趣對於C#的工作方式,我會很感激你對此的看法/幫助。
你有沒有考慮過使用['SerialPort.DataReceived event'](https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived(v = vs.110)。 ASPX)? – stuartd
@stuartd還沒有。至於說到目前爲止沒有做太多的C#,會讀到這裏。謝謝 –
有關使用示例,請參閱例如[串口輪詢和數據處理](http://stackoverflow.com/questions/15124132/serial-port-polling-and-data-handling) – stuartd