问题描述
我试图实现串口通信,SetCommState函数返回错误(0)。
我尝试过以下代码。
I was trying to implement a serial port communication, the SetCommState function returns error(0).
I have tried with the following code.
COMMPROP commprop = {0};
COMMTIMEOUTS timeouts = {0};
m_hComm = CreateFile(_T("COM1"), // communication port string (COMX)
GENERIC_READ | GENERIC_WRITE, // read/write types
0, // comm devices must be opened with exclusive access
NULL, // no security attributes
OPEN_EXISTING, // comm devices must use OPEN_EXISTING
0, // Async I/O
NULL);
if (0 == GetCommProperties(m_hComm,&commprop)) {
MessageBox(_T("Error in setting params"), _T("Error"),
MB_ICONERROR | MB_OK);
}
if (m_hComm == INVALID_HANDLE_VALUE)
{
// port not found
MessageBox(_T("Cannot open port"), _T("Error"),
MB_ICONERROR | MB_OK);
}
else
{
MessageBox(_T("Port open"), _T("Info"),
MB_ICONINFORMATION | MB_OK);
}
DWORD size =1;
char readBuf[5];
char sendBuf[10];
DCB dcb;
memset(readBuf,0,5);
memset(sendBuf,0,10);
memset(&dcb,0,sizeof(dcb));
dcb.DCBlength=sizeof(dcb);
GetCommState(m_hComm,&dcb);
dcb.BaudRate=5;
dcb.ByteSize = 8;
dcb.StopBits = ONESTOPBIT;
dcb.Parity = NOPARITY;
if (0 == SetCommState(m_hComm,&dcb))
{
AfxMessageBox(_T("error on setting baud rate"));
}
while(size ==0)
{
if(!ReadFile(m_hComm, &readBuf[0], 1, &size, NULL))
{
MessageBox(_T("Read Error"), _T("Error"),
MB_ICONERROR | MB_OK);
}
}
调用 CreateFile时使用FILE_FLAG_OVERLAPPED是否有效 方法?我无法确定为什么会出现这个问题,请帮我找一下这段代码的麻烦。
Is it valid to use FILE_FLAG_OVERLAPPED when calling the CreateFile method? I cannot identify why this issue happens, Please help me to find the trouble with this code.
推荐答案
dcb.BaudRate = 5;
dcb.BaudRate=5;
什么样的设备在波特发送数据? :omg:
顺便说一句:好奇的是你在<$ c $中使用它之后检查m_hComm值c> GetCommProperties call。
What kind of device sends data at baud? :omg:
By the way: it is curious you are checking the m_hComm value after having used it in the GetCommProperties
call.
这篇关于读取串行端口通信中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!