[問題] 單機RS232傳送問題
( *[1m *[m 為色碼,可以按 Ctrl+V 預覽會顯示的顏色 )
( 未必需要依照此格式,文章條理清楚即可 )
1.遇到的問題:
我有一台電腦 我差了一個USB轉RS232的線
所以我現在的RS232是一個COM3的串列阜。
我是把RS232的腳位 2,3 接起來短路打算自己送資料自己接資料。
我在電腦裡面送出一個字串"I am test string."
2.希望得到的正確結果:
按下Esc之後
在螢幕上顯示"I get this massage = I am test string."
3.程式跑出來的錯誤結果:
按下Esc之後
螢幕上顯示"I get this massage ="
4.開發平台:
VC++ 2008 in Win xp
5.有問題的code:
#include <windows.h>
#include <stdio.h>
#include <conio.h> //for _getch() and _kbhit();
#include <string>
using namespace std;
int main(){
HANDLE hComm;
DCB dcb;
string Temp;
//for receiving
char inbuff[1024];
DWORD nBytesRead,dwEvent,dwError;
COMSTAT cs;
int end=FALSE,ky;
//for sending
const char *SendData;
unsigned long lrc, BS;
char str1[]="I am a test string.";
printf("%s\n",str1);
hComm = CreateFile("COM3",
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
0,
0);
if (hComm == INVALID_HANDLE_VALUE){
printf("wrong port connection.\n");
return 0;
}
GetCommState(hComm,&dcb);
dcb.BaudRate = CBR_9600;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
if (!SetCommState(hComm, &dcb)){
printf("setting error.\n");
return 0;
}
//send
Temp=str1;
SendData = Temp.c_str();
BS=strlen(SendData);
WriteFile(hComm, SendData,BS,&lrc,NULL);
//receive
ClearCommError(hComm,&dwError,&cs);
if (cs.cbInQue > sizeof(inbuff)){
PurgeComm(hComm, PURGE_RXCLEAR);
printf("your massage is too big\n");
return 0;
}
while (!end){
ReadFile(hComm, inbuff,cs.cbInQue, &nBytesRead,NULL);
inbuff[cs.cbInQue]='\0';
if (_kbhit()){
if((ky = _getch()) =='\x1B'){
end=TRUE;
}
}
}
printf("I get this massage = %s \n",inbuff);
return 0;
}
麻煩各位大大教一下小新米 ORZ
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.135.96.181
推
10/10 19:48, , 1F
10/10 19:48, 1F
→
10/10 19:49, , 2F
10/10 19:49, 2F
→
10/10 19:50, , 3F
10/10 19:50, 3F
→
10/10 19:51, , 4F
10/10 19:51, 4F
→
10/10 21:33, , 5F
10/10 21:33, 5F
推
10/10 21:59, , 6F
10/10 21:59, 6F
→
10/10 21:59, , 7F
10/10 21:59, 7F
→
10/10 22:00, , 8F
10/10 22:00, 8F
→
10/10 22:00, , 9F
10/10 22:00, 9F
→
10/10 22:01, , 10F
10/10 22:01, 10F
→
10/10 22:03, , 11F
10/10 22:03, 11F
→
10/10 22:47, , 12F
10/10 22:47, 12F
→
10/10 22:47, , 13F
10/10 22:47, 13F
→
10/10 22:48, , 14F
10/10 22:48, 14F
推
10/10 23:30, , 15F
10/10 23:30, 15F
→
10/10 23:30, , 16F
10/10 23:30, 16F
推
10/10 23:33, , 17F
10/10 23:33, 17F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章