serial port write c++
serial port write c++
我在C++
编程很新,我需要你的帮助。
我想做一个简单的GUI
,它将通过serial port
和砂字符类型与外部设备通信到设备。我的问题是下一个
- 我不明白
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);
相关文章:
- 尝试链接我的着色器时,我收到错误代码"error c5145 must write to gl_position"
- 当客户端在 write() 期间终止连接时,由对等套接字错误重置连接
- Qt 写入 xml: QIODevice::write (QFile, "D:/logs.xml" ): 设备未打开
- write() 和 read() 中几乎没有混淆
- OpenCV-contrib/Python/Windows:Tracker.write() 在 matrix_wrap.
- asio::read() 需要很长时间,使用 asio::write 没有问题
- 封送指向结构异常"cannot Read or Write protected memory"的指针数组的指针数组
- BLE gattServer.write()重载函数
- C++ write(); 反向写入给定的字节值
- 使用 QFile::write 的正确方法?
- C++ UDP 广播使用 ::write
- 是否可以从从 QPrintPreviewDialog 调用的 QPrinter 对话框中删除"Write to PDF"?
- 为什么 fstream.read 和 fstream.write 使用 char 而不是无符号字符?
- 使用 insertion(<<) 运算符和 "write" 函数在 C++ 中显示数据有什么区别?
- 一次读取一个字符的文件,直到使用 read(2) 和 write(2) 换行符
- char* 如何读取十六进制的这个整数?它在 ostream::write() 中是如何工作的
- 在 boost::asio::write 之后使用 TCP
- 如何使用write()函数将结构写入文件
- 没有匹配函数来调用"std::basic_ofstream<char>::write(std::string*, long long unsigned int)"
- QNetwork回复 "unable to write"