好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