C ++/CLI从串行端口读取二进制 [英] C++/CLI reading Binary From a Serial port
本文介绍了C ++/CLI从串行端口读取二进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经编写了通过串行端口读取字符串的代码,但是现在我需要对其进行更改以读取二进制输入.
这是我目前所拥有的
I have written code to read strings via the serial port, But now i need to alter it to read binary inputs.
Here is what I have at the moment
private: System::Void serialPort1_DataReceived(System::Object^ sender, System::IO::Ports::SerialDataReceivedEventArgs^ e) {
if (_continue == true)
{
String^ data = serialPort1->ReadExisting(); //Reading all exsisting data in serialport buffer
StreamWriter^ sw= File::AppendText(fileloc->Text); //Seting stream wirter up and pointing to selected file
sw->Write(data); //write data to same line
this->databox->AppendText(data); //write data to rich text box
sw->Flush();
sw->Close();
}
}
这是我所做的一些更改
This is some of the changes that I have made
private: System::Void serialPort1_DataReceived(System::Object^ sender, System::IO::Ports::SerialDataReceivedEventArgs^ e) {
if (_continue == true)
{
int data= serialPort1->ReadByte();
BinaryWriter^ bw = gcnew BinaryWriter( File::Open(fileloc->Text,FileMode::Append));
bw->Write(data);
//this->databox->AppendText(data); Not started on writing binary to the Rich text box
bw->Flush();
bw->Close();
}
}
感谢您的帮助!
Thanks for any help!
推荐答案
您需要循环调用ReadByte
,直到返回-1.然后,您可能可以使用File::WriteAllBytes
将其写入文件.如果要追加到文件,则需要编写更多代码(类似于您现在已有的代码.
而且我认为在富文本框中显示二进制数据没有意义.
[更新]
--------
示例Read
用法:
为了示例,
You need to callReadByte
in a loop until it returns -1. And then you can probably useFile::WriteAllBytes
to write it to a file. If you want to append to the file, you''d need to write more code (something similar to what you already have now.
And I don''t think it makes sense to display binary data in a rich text box.
[Update]
--------
ExampleRead
usage:
// 100 and 75 are arbitrary values for the sake of the example.
// Do not hardcode this in your code.
array<byte>^ bytes = gcnew array<byte>(100);
serialPort->Read(bytes, 0, 75);
这篇关于C ++/CLI从串行端口读取二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文