求下面微机原理程序的说明解释,就是各个语句的功能文字说明?

2025-03-15 12:39:45
推荐回答(1个)
回答1:

#include
#include
#include
static HANDLE hPort = INVALID_HANDLE_VALUE;
unsigned char lpBuffer[100];
BOOL OpenPort(const int portNum) { 打开串口
DCB dcb;
COMMTIMEOUTS commtimeouts;

TCHAR tszPort[10] = {0};
_stprintf(tszPort, _T("COM%d:"), portNum);
//hPort = CreateFile("COM1", 创建文件
hPort = CreateFile(tszPort,
GENERIC_READ | GENERIC_WRITE,
0, // comm devices must be opened w/exclusive-access
NULL, // no security attrs
OPEN_EXISTING, // comm devices must use OPEN_EXISTING
0, // overlapped I/O
NULL // hTemplate must be NULL for comm devices
);

if (hPort == INVALID_HANDLE_VALUE) return FALSE;

//fills in a device-control block with the current control settings //加入设备控制模块当前设置参数
if (!GetCommState(hPort, &dcb))
{
CloseHandle(hPort);
hPort = INVALID_HANDLE_VALUE;
return FALSE; //error
}

//fills in a device-control block //加入设备控制模块
dcb.BaudRate = CBR_19200;
dcb.ByteSize = 8;
dcb.Parity = EVENPARITY;
dcb.StopBits = ONESTOPBIT;
dcb.fRtsControl = TRUE;
dcb.fDtrControl = TRUE;

if (!SetCommState(hPort, &dcb))
{
CloseHandle(hPort);
hPort = INVALID_HANDLE_VALUE;
return FALSE;
}

if(!GetCommTimeouts(hPort, &commtimeouts))
{
CloseHandle(hPort);
hPort = INVALID_HANDLE_VALUE;
return FALSE;
}
commtimeouts.ReadIntervalTimeout = 30;
commtimeouts.ReadTotalTimeoutMultiplier = 0;
commtimeouts.ReadTotalTimeoutConstant = 10;
commtimeouts.WriteTotalTimeoutMultiplier = 1;
commtimeouts.WriteTotalTimeoutConstant = 50;

if(!SetCommTimeouts(hPort, &commtimeouts))
{
CloseHandle(hPort);
hPort = INVALID_HANDLE_VALUE;
return FALSE;
}

PurgeComm(hPort, PURGE_TXCLEAR | PURGE_TXCLEAR);

return TRUE;
}

void V2BFClosePort() { //关闭串口
if (hPort != INVALID_HANDLE_VALUE) {

CloseHandle(hPort);
hPort = INVALID_HANDLE_VALUE;
}
}

void RecvStream(void) {
int nRecvedBytes = 0;
DWORD dwRead = 0;

if (ReadFile(hPort, lpBuffer, strlen(lpBuffer), &dwRead, NULL)) {

nRecvedBytes = dwRead;
}

}

BOOL SendStream(IN unsigned char *sendStream, IN int sendLength) {
BOOL fRet = FALSE;

if (hPort != INVALID_HANDLE_VALUE) {
DWORD dwWritten = 0;
fRet = WriteFile(hPort, sendStream, sendLength, &dwWritten, NULL);
FlushFileBuffers(hPort);
fRet = fRet && ((unsigned long)sendLength == dwWritten);
}

return fRet;
}