線上訂房服務-台灣趴趴狗聯合訂房中心
發文 回覆 瀏覽次數:2083
推到 Plurk!
推到 Facebook!

為什麼我 rs232程式會出錯

尚未結案
plihui
初階會員


發表:88
回覆:96
積分:41
註冊:2003-07-03

發送簡訊給我
#1 引用回覆 回覆 發表時間:2005-09-20 16:49:37 IP:218.168.xxx.xxx 未訂閱
void __fastcall TForm1::Button1Click(TObject *Sender)
{
//選擇使用的port: com1 或 com2
 char *Com_port;
 DCB dcb;
 String Com_name="COM" IntToStr(CommSelect->ItemIndex 1);
 Com_port=Com_name.c_str();
 hComm=CreateFile(Com_port, GENERIC_READ | GENERIC_WRITE,
                  0, NULL, OPEN_EXISTING, 0 ,0);
 if ( hComm == INVALID_HANDLE_VALUE)
  {
  MessageBox(0, "開啟錯誤的通訊阜!!!","錯誤的通訊阜", MB_OK);
  return;
  }
 // 將dcb位置傳入,已設定通訊參數
 GetCommState(hComm,&dcb);
 dcb.BaudRate = CBR_9600;
 dcb.ByteSize = 8;
 dcb.Parity=NOPARITY;
 dcb.StopBits=ONESTOPBIT;     if( !SetCommState( hComm, &dcb) )
  {
   MessageBox(0, "通訊參數設定失敗", "Setting Error", MB_OK);
   CloseHandle(hComm);
   return;
  }
}
//--------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
 DWORD nBytes_W=1; //nBytes_W:number of bytes to write
 unsigned long lrc; //pointer to number of bytes written
 AnsiString Data_s="0xff 0x11";     byte _tdata;     if ( hComm == 0)
 {
  MessageBox(NULL,"COM port is not opened!!","OK",MB_OK);
  return ;
 }     //bug段
 //將字串切割為命令和參數輸出
  int index=0;
 char *token=strtok(Data_s.c_str()," ");
 vector  cc;
 while (token != NULL)
   {
    cc.push_back(token);
    token=strtok(NULL," ");
    _tdata=StrToInt(cc[index]);
    Look_Up_Table.push_back(_tdata);
    ShowMessage("0x" IntToHex(_tdata, 2) "\n");
    WriteFile(hComm,&_tdata,1, &lrc, NULL);  //一次輸出1個byte
    index  ;
   }    }    //--------------------------------------------------------------
void __fastcall TForm1::Button3Click(TObject *Sender)
{     byte in_buff[2];
 DWORD nBytes_R, dwEvent , dwError;     COMSTAT cs; //The COMSTAT structure contains information about a communications device.
 ClearCommError(hComm,&dwError,&cs);
 // ClearCommError():讀取串列埠現在狀態
 //reports the current status of a communications device     if(cs.cbInQue > sizeof(in_buff))
  {
   PurgeComm(hComm, PURGE_RXCLEAR);
   return;
  }     ReadFile(hComm, in_buff, cs.cbInQue, &nBytes_R, NULL);     //檢查命令 參數傳遞正確與否
 if(in_buff[0]==Look_Up_Table[0])
 ShowMessage("0x" IntToHex(in_buff[0], 2) "\n");//BCB debug用:顯示輸入byte 1的16進位和2進位
 if(in_buff[1]==Look_Up_Table[1])
 ShowMessage("0x" IntToHex(in_buff[1], 2) "\n");//BCB debug用:顯示輸入byte 1的16進位和2進位    }
如題 : 我用一條RS232將RX和TX對接,對同一台電腦做檔案傳輸 此檔案傳輸方法為 byte,如同上面程式碼所示(在此例中以Data_s代表讀進來的文字檔案),需要將Data_s切割為 0xff ,0x11輸出 結果發現收到秀出的為0x7f 0x11 想請問各位是哪裡出現了問題呢?>
DavidLo
高階會員


發表:17
回覆:225
積分:168
註冊:2004-07-21

發送簡訊給我
#2 引用回覆 回覆 發表時間:2005-09-20 23:02:36 IP:220.139.xxx.xxx 未訂閱
應該型態轉換問題! 試試我的方法: EditS4->Text = IntToHex((unsigned short)ReadKeyProData(7),4);
系統時間:2024-04-20 22:29:15
聯絡我們 | Delphi K.Top討論版
本站聲明
1. 本論壇為無營利行為之開放平台,所有文章都是由網友自行張貼,如牽涉到法律糾紛一切與本站無關。
2. 假如網友發表之內容涉及侵權,而損及您的利益,請立即通知版主刪除。
3. 請勿批評中華民國元首及政府或批評各政黨,是藍是綠本站無權干涉,但這裡不是政治性論壇!