VC ++ / CLI和串行端口 [英] VC++/CLI and Serial Port
本文介绍了VC ++ / CLI和串行端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码工作得非常好,除非我认为它不是最佳的,并且能够可靠地快速响应或处理有意义的延迟。
有没有更好的方法吗?我希望它只是等待缓冲区中前8字节数据的到达并读取并继续下一个任务?
睡眠( 2000 跨度>); // 延迟
serialPort1-> ;; DiscardInBuffer(); // 清除缓冲区中的串行端口
serialPort1-> ;; DiscardOutBuffer(); // clear serial port out buffer
auto Power = gcnew array< System :: Byte> {0x52,0x0C,0x01,0x00,0x00};
serialPort1->写入(电源, 0 ,电源 - >长度);
睡眠( 500 );
auto Power1 = gcnew 数组< System :: Byte> {0x00,0x00,0x00,0x00,0x00};
serialPort1-> Read(Power1, 0 ,Power1-> ;; Length);
字符串 ^ str2 = 字符串 ::格式( {0:X2} {1:X2} {2:X2} {3:X2} {4:X2} ,Power1 [ 0 ],Power1 [ 1 ],Power1 [ 2 ],Power1 [ 3 ],Power1 [ 4 ]);
字符串 ^ str3 = 字符串 ::格式( {2:N0},Power1 [ 0 ], Power1 [ 1 ]);
richTextBox1-& gt; Text + = Power Level - >跨度>;
richTextBox1-& gt; Text + = str3 + Watts \\\\ n;
解决方案
更好的方法是用户重叠通信,因为睡眠会阻塞线程。
在本文中: Windows中的串行通信是很好地解释了。
为端口创建写入和读取线程也很有意义。
文章,其中包含背景信息,但在C#中。
你应该摆脱所有的Sleep
调用并与串口异步工作:编写你的数据,然后处理DataReceived
事件,由SerialPort
类轻轻提供(参见 SerialPort :: DataReceived Event [ ^ ])。
My code is working perfectly fine except I don't believe it is optimal and is going work reliably for fast response or handle significan delays.
Is there a better way of doing this? I would like it to just only wait for the arrival of the first 8 byte data on the buffer and read and continue on to the next task?
Sleep (2000); //delay
serialPort1->;DiscardInBuffer(); //clear serial port in buffer
serialPort1->;DiscardOutBuffer(); //clear serial port out buffer
auto Power = gcnew array<System::Byte> {0x52, 0x0C, 0x01, 0x00, 0x00};
serialPort1->Write(Power, 0, Power->Length);
Sleep(500);
auto Power1 = gcnew array<System::Byte> {0x00, 0x00, 0x00, 0x00, 0x00};
serialPort1->Read(Power1, 0, Power1->;Length);
String^ str2 = String::Format("{0:X2} {1:X2} {2:X2} {3:X2} {4:X2}", Power1[0], Power1[1], Power1[2], Power1[3], Power1[4]);
String^ str3 = String::Format("{2:N0}", Power1[0], Power1[1]);
richTextBox1->Text += "Power Level -> ";
richTextBox1->Text += str3 + "Watts" "\r\n";
解决方案
A better way is to user overlapped communication, because sleep blocks the thread.
In this articel: Serial Communication in Windows is it well explained.
It makes also sense to create a write and a read thread for the port.
An article with background information but in C#.
You should get rid of all theSleep
calls and work asynchronously with the serial port: write your data and then and then handle theDataReceived
event, gently provided by theSerialPort
class (see SerialPort::DataReceived Event[^]).
这篇关于VC ++ / CLI和串行端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文