我必須發送6個字節到串口設備。端口已打開但數據未發送。我使用串口監視器來了解我的代碼發生了什麼(C++ Win32,Visual Studio)。是WriteFile的工作? C++
我使用的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; ..........
的東西。我認爲我的問題是這樣的。
你決定丟棄所有返回值。生命太短,無法猜測問題是什麼,零信息不足。 – IInspectable
'(LPCVOID)數據,' - 這當然是錯誤(訪問衝突)需要'的WriteFile(hPort, 和數據, 的sizeof(數據), &byteswritten, NULL);' – RbMm
@IInspectable,什麼樣的信息做你需要?我告訴我所有我認爲是必要的。 – Th3venin