serial port write c++

serial port write c++

本文关键字:c++ write port serial      更新时间:2023-10-16

我在C++编程很新,我需要你的帮助。

我想做一个简单的GUI,它将通过serial port和砂字符类型与外部设备通信到设备。我的问题是下一个

  1. 我不明白mySirialPort->Write(array<Char>^, Int32, Int32) --- array<Char>^我需要写哪种类型的variable

因为我得到了下一个错误。

1>Return_NAN.cpp(19): error C2440: 'initializing' : cannot convert from 'const char [2]' to 'char'
1>          There is no context in which this conversion is possible
1>Return_NAN.cpp(30): error C2664: 'void System::IO::Ports::SerialPort::Write(cli::array<Type,dimension> ^,int,int)' : cannot convert parameter 1 from 'char' to 'cli::array<Type,dimension> ^'
1>          with
1>          [
1>              Type=wchar_t,
1>              dimension=1
1>          ]

my code:

char a = "A";        
SerialPort^ mySerialPort = gcnew SerialPort(a);
//mySerialPort->PortName = a;   
mySerialPort->BaudRate = 1200;
mySerialPort->Parity = Parity::None;
mySerialPort->StopBits = StopBits::One;
mySerialPort->DataBits = 8;
mySerialPort->Handshake = Handshake::None;
mySerialPort->Open();
mySerialPort->Write(t,0,1); // problem
mySerialPort->Close();

如果我直接写"A"来写函数,在编译时不会出现错误。

谢谢你的帮助,KB

System::IO::Ports::SerialPort是一个。net类。请记住,您使用的是一种名为c++/CLI的语言扩展,通过阅读基础教程可以节省大量时间。它与c++有足够的不同,有一个学习曲线,一个星期将对学习基本类型和知道何时使用^帽有很大的帮助。

你已经发现写字符串很容易,SerialPort::Write()有一个接受字符串的重载。它将把字符串转换为ASCII,所以你只能写0到127之间的字符值:

String^ example1 = "ABC";
mySerialPort->Write(example1);

写入单个字节最简单的方法是写入BaseStream,不需要进行转换:

Byte example2 = 'A';   // or 0x41
mySerialPort->BaseStream->WriteByte(example2);

如果你想写一个字节数组,就像错误信息告诉你的那样,那么你必须创建一个数组对象:

array<Byte>^ example3 = gcnew array<Byte> { 0x01, 0x02, 0x42 };
mySerialPort->Write(example3, 0, example3->Length);

没有根本的理由支持写入字节数组而不是一次写入一个字节,串行端口无论如何都非常慢。

第一个错误很简单:你应该写:char a = 'A';与单引号,而不是"a"与双引号。

array^是clr引用类型,它可能像这样:array<char>^ t = {1,2,3};看这里:

,但你最好使用write(string^)看这里:

你可以像这样把c字符串转换成

const char* str = "Hello, world!";
String^ clistr = gcnew String(str);//allocate cli string and convert the c string
// no need to delete, garbage collector will do it for you.
mySerialPort->Write(clistr);