2017年4月20日 星期四

基礎的rs232控制

先從確認Port開始,開啟Port是第一個要件

int UART::openUart(AnsiString &Com) {
   DWORD dwBytesRead, ByteCount;
   COMMTIMEOUTS ctmoNew = {0}, ctmoOld;
   DCB dcb;
   ZeroMemory(&dcb, sizeof(dcb));
   dcb.DCBlength = sizeof(dcb);
   dcb.BaudRate = 9600;
   dcb.ByteSize = 8;
   dcb.Parity = NOPARITY;
   dcb.StopBits = ONESTOPBIT;
 
   // ------copy to dcbCommPort------
   // dcbCommPort = dcb;
 
   Com.Insert("\\\\.\\", 1);
   char *a = Com.c_str();
   // wchar_t *Wch = (wchar_t*)std::malloc(sizeof(Com.c_str()));
   wchar_t *Wch = (wchar_t*)std::malloc(Com.Length()*sizeof(wchar_t));
   // int x = sizeof(Com.c_str());
   int x = Com.Length()*sizeof(wchar_t);
   // mbstowcs(Wch, Com.c_str(), x);
   mbstowcs(Wch, a, x);
   //CreateFile 建立一個通道 基於WINAPI的函數
   h_RS232 = CreateFile(Wch, GENERIC_READ | GENERIC_WRITE, 0, NULL,
     OPEN_EXISTING, 0, NULL);
   if (h_RS232) {
 
     // 清空上一次的狀態
     PurgeComm(h_RS232,
       PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR);
 
     SetCommState(h_RS232, &dcb);
     // ShowMessage("Connect Success!");
 
     // Form3->sts_text_lbl->Caption = Form3->portbox->Text +
     // " (9600 ,8 , N, 1)";
 
     GetCommTimeouts(h_RS232, &ctmoOld);
     ctmoNew.ReadTotalTimeoutConstant = 100; // 10ms~50ms
     ctmoNew.ReadTotalTimeoutMultiplier = 0;
     ctmoNew.WriteTotalTimeoutConstant = 0;
     ctmoNew.WriteTotalTimeoutMultiplier = 0;
     SetCommTimeouts(h_RS232, &ctmoNew);
 
     // while(true){
     // WriteFile(h_RS232,ss.c_str(),strlen(ss.c_str()),&ByteCount,NULL);}
     return 1;
   }
   else {
     // ShowMessage("Connect Fail!");
 
     return 0;
   }
 
 }

沒有留言:

張貼留言