HANDLE hCommHndl; // 通信ポートハンドル
DCB com_setting; // 通信設定
int port; // ポート番号
char port_name[64]; // ポート名
char data[64]; // 送信データ
DWORD nByte = 1; // 送信データバイト
DWORD nSentData; // 送信済データバイト
// ハンドル取得
printf("port番号:");
scanf("%d",&port);
sprintf(port_name,"COM%d",port);
hCommHndl = CreateFile( port_name, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
if (hCommHndl == INVALID_HANDLE_VALUE) {
printf("ポートをオープンできませんでした\n");
return 0;
}
// 通信設定
GetCommState( hCommHndl, &com_setting );
com_setting.BaudRate = 19200; // 通信速度[bps]
com_setting.ByteSize = 8; // データサイズ
com_setting.Parity = NOPARITY; // パリティなし
com_setting.StopBits = ONESTOPBIT; // ストップビット 1
com_setting.fBinary = TRUE; // バイナリモードON
com_setting.fParity = FALSE; // パリティチェックOFF
com_setting.fOutX = FALSE; // 送信Xフロー制御OFF
com_setting.fInX = FALSE; // 受信Xフロー制御OFF
SetCommState( hCommHndl, &com_setting );
printf("qを入力して終了\n");
while (1) {
printf("send character = ");
scanf("%s",&data);
if (data[0]=='q') break;
WriteFile( hCommHndl, data, nByte, &nSentData, NULL );
Sleep(500);
}
CloseHandle( hCommHndl ); // ポートを閉じる
return 0;