【发布时间】:2017-03-02 12:26:07
【问题描述】:
我必须通过串口向设备发送 6 个字节。端口已打开,但数据未发送。我使用串行端口监视器来了解我的代码(C++ Win32、Visual Studio)发生了什么。
我正在使用 CreateFile
hPort = CreateFile( TEXT("COM3"),
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
0,
NULL );
我要写的代码是:
void uart::write(char data) {
WriteFile(hPort,
(LPCVOID)data,
1,
&byteswritten,
NULL);
}
当我需要在我的设备中执行命令时,我调用函数 sendCommand("000000010000000100000000000000000000000000000000");
void device::sendCommand(std::string command) {
int size = command.length();
char* string = (char*)command.c_str();
std::vector<char> data(command.begin(), command.end()) ;
std::cout <<"[Uart.write]>>\n";
int j=0;
for (int k = 0; k <= size - 1; k++) {
Uart.write(data[k]);
std::cout << data[k];
j++;
if (j % 8 == 0 && j!=0) { std::cout << "__byte " << j / 8 << "send___\n";
}
我用下面的代码如模型来写上面的代码win32 c++。
#using <System.dll>
using namespace System;
using namespace System::IO::Ports;
using namespace System::Threading;
void SendCommand(SerialPort^ port, Byte unit, Byte command, Int32 data);
int _tmain(int argc, _TCHAR* argv[])
{
SerialPort^ port;
Byte unit;
Byte command;
Int32 data;
// Set up serial port
port = gcnew SerialPort();
port->PortName = "COM8";
port->BaudRate = 9600;
port->DataBits = 8;
port->Parity = Parity::None;
port->StopBits = StopBits::One;
port->Handshake = Handshake::None;
// Open port
port->Open();
// Home device 1
SendCommand(port, 1, CMD_HOME, 0);
WaitForReply(port, 1, CMD_HOME, unit, command, data);
// Close port
port->Close();
return 0;
}
void SendCommand(SerialPort^ port, Byte unit, Byte command, Int32 data)
{
array<Byte>^ packet = gcnew array<Byte>(6);
gcnew array<Byte>
packet[0] = unit;
packet[1] = command;
packet[2] = data & 0xFF;
packet[3] = (data >> 8) & 0xFF;
packet[4] = (data >> 16) & 0xFF;
packet[5] = (data >> 24) & 0xFF;
port->Write(packet, 0, 6);
}
我想在 C++ 中找到类似 array<Byte>^ packet = gcnew array<Byte>(6);
gcnew array<Byte>
packet[0] = unit; .......... 的东西。我想我的问题是这样的。
【问题讨论】:
-
您决定放弃所有返回值。生命短暂,无法猜测问题所在,零信息。
-
(LPCVOID)data,- 这当然是错误(访问冲突)需要WriteFile(hPort, &data, sizeof(data), &byteswritten, NULL); -
@IInspectable,你需要什么样的信息?我把我认为有必要的都说了。
-
看起来你决定忽略文档中的细节。你为什么决定这样做?
-
这让我觉得很奇怪。我链接到解释如何做到这一点的文档。点击超链接真的要求太多了吗?
标签: c++ visual-studio winapi serial-port