C++ 串口写入c++;
我对C++ 串口写入c++;,c++,visual-studio-2010,serial-port,C++,Visual Studio 2010,Serial Port,我对C++编程相当陌生,我需要你的帮助 我想制作一个简单的GUI,它将通过串行端口与外部设备进行通信,并将字符类型打磨到设备上。接下来是我的问题 我不明白我需要写什么类型的变量 因为我得到下一个错误 1>Return_NAN.cpp(19): error C2440: 'initializing' : cannot convert from 'const char [2]' to 'char' 1> There is no context in which this
C++
编程相当陌生,我需要你的帮助
我想制作一个简单的GUI
,它将通过串行端口与外部设备进行通信,并将字符类型打磨到设备上。接下来是我的问题
我不明白我需要写什么类型的变量李>
因为我得到下一个错误
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> ]
如果我直接写“A”来写函数,编译时就不会有错误
谢谢你的帮助,
KB第一个错误很简单:您应该写:chara='a'代码>带有单引号,而不是带有双引号的“a”
array^
是clr引用类型,它可能是这样的:array^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);
System::IO::Ports::SerialPort是一个.NET类。请记住,您使用的是一个名为C++/CLI的语言扩展,阅读基本教程可以节省大量时间。从C++到学习曲线的不同,一个星期学习基本类型和知道何时使用^ HID会有很大的好处。
您已经发现编写字符串很容易,SerialPort::Write()具有接受字符串的重载。它将字符串转换为ASCII,因此您只能写入介于0和127之间的字符值:
String^ example1 = "ABC";
mySerialPort->Write(example1);
写入单个字节最简单的方法是写入基流,不进行任何转换:
Byte example2 = 'A'; // or 0x41
mySerialPort->BaseStream->WriteByte(example2);
如果要写入字节数组,如错误消息所述,则必须创建数组对象:
array<Byte>^ example3 = gcnew array<Byte> { 0x01, 0x02, 0x42 };
mySerialPort->Write(example3, 0, example3->Length);
array^example3=gcnewarray{0x01、0x02、0x42};
mySerialPort->Write(示例3,0,示例3->Length);
没有根本的理由支持一次写入一个字节数组而不是一个字节写入一个字节,不管怎样,串行端口都非常慢。char a='a'代码>实际的串行端口函数(<代码> CREATFEFILE <代码> >代码> SETCOSTATEON//COD> >代码> <代码> >代码> CloseHandle <代码>,比.NET包装器好,C++也容易调用(可能更简单)。
array<Byte>^ example3 = gcnew array<Byte> { 0x01, 0x02, 0x42 };
mySerialPort->Write(example3, 0, example3->Length);