【程序2】
#include <iostream>
#include <Windows.h>
#include <strsafe.h>
using namespace std;
#define DEBCD(n) ((((n) & 0xf0) >> 4) * 10 + ((n) & 0x0f))
#ifdef _UNICODE
ostream &operator << (ostream &os, const wchar_t *wstr)
{
if (os == cout)
WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), wstr, wcslen(wstr), NULL, NULL);
return os;
}
#endif
int main(void)
{
HANDLE hComm = CreateFile(TEXT("\\\\.\\COM10"), GENERIC_READ | GENERIC_WRITE, NULL, NULL, OPEN_EXISTING, NULL, NULL);
if (hComm == INVALID_HANDLE_VALUE)
{
cout << TEXT("打开串口失败") << endl;
return 0;
}
try
{
DCB dcb;
ZeroMemory(&dcb, sizeof(dcb));
dcb.DCBlength = sizeof(DCB);
GetCommState(hComm, &dcb);
dcb.BaudRate = CBR_9600; // 注意是CBR_不是BAUD_
dcb.ByteSize = 8;
dcb.fParity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
if (!SetCommState(hComm, &dcb))
throw 0;
COMMTIMEOUTS tmout;
ZeroMemory(&tmout, sizeof(tmout));
tmout.ReadTotalTimeoutConstant = 1000;
if (!SetCommTimeouts(hComm, &tmout))
throw 2;
BYTE buf[100];
DWORD dwSize;
buf[0] = 0x05;
WriteFile(hComm, buf, 1, &dwSize, NULL);
ReadFile(hComm, buf, _countof(buf), &dwSize, NULL);
if (buf[0] == 0x20)
{
int hour, wday;
TCHAR h[4];
LPTSTR list = TEXT("日一二三四五六");
TCHAR str[100];
if (buf[3] & 0x80)
{
if (buf[3] & 0x20)
h[0] = 'P';
else
h[0] = 'A';
h[1] = 'M';
h[2] = ' ';
h[3] = '\0';
hour = buf[3] & 0x1f;
hour = DEBCD(hour);
}
else
{
h[0] = '\0';
hour = DEBCD(buf[3]);
}
wday = buf[6] & 0x07;
if (wday == 7)
wday = 0;
cout << TEXT("时间为: ") << endl;
StringCbPrintf(str, sizeof(str), TEXT("20%02d年%02d月%02d日\n%02d:%02d:%02d %s星期%c"), DEBCD(buf[7]), DEBCD(buf[5]), DEBCD(buf[4]), hour, DEBCD(buf[2]), DEBCD(buf[1]), h, list[wday]);
cout << str << endl;
}
else
throw 1;
}
catch (const int iErrId)
{
DWORD dwErr = GetLastError();
switch (iErrId)
{
case 0:
cout << TEXT("设置波特率失败, 错误码: ") << dwErr << endl;
if (dwErr == ERROR_INVALID_PARAMETER)
cout << TEXT("参数不正确") << endl;
break;
case 1:
cout << TEXT("读取时间失败") << endl;
break;
case 2:
cout << TEXT("设置超时时间失败") << endl;
}
}
if (hComm != INVALID_HANDLE_VALUE)
CloseHandle(hComm);
return 0;
}
【运行结果】
时间为:
2016年07月17日
19:04:25 星期日