我使用C++ Builder 6.0调用Win32 API实现的。 首先开一个线程。 void __fastcall TForm1::FormCreate(TObject *Sender) { ReadComm =new TRead232(true); ReadComm->FreeOnTerminate = true; } 通过一个按钮实现打开/关闭串口 void __fastcall TForm1::Button1Click(TObject *Sender) { if(Button1->Caption == "打开通讯端口") //按钮名称是"打开通讯端口"? { char *ComNo; DCB dcb; String Temp; Temp = "COM"+IntToStr(rdCom->ItemIndex+1); // TRadioGroup *rdCom; 定义要选择的串口 ComNo = Temp.c_str(); hComm =CreateFile(ComNo,GENERIC_READ|GENERIC_WRITE, 0,NULL,OPEN_EXISTING,0,0); if(hComm == INVALID_HANDLE_VALUE) { MessageBox(0,"打开串口失败!!","Set Error",MB_OK); return; } GetCommState(hComm,&dcb); dcb.BaudRate = CBR_9600; dcb.ByteSize = 8; dcb.Parity = NOPARITY; dcb.StopBits = ONESTOPBIT; if(!SetCommState(hComm,&dcb)) { MessageBox(0,"打通讯端口设置错误!!","Set Error",MB_OK); CloseHandle(hComm); return; } Timer1->Enabled = True; Button1->Caption = "关闭串口"; Shape1->Brush->Color = clRed; //启动接收线程
ReadComm->Resume(); } else { Button1->Caption = "打开通讯端口"; CloseHandle(hComm); Shape1->Brush->Color = clBlack; Timer1->Enabled = False; ReadComm->Terminate();
} } 接收由线程TRead232完成 void __fastcall TRead232::Execute() { SetName(); //---- Place thread code here ---- if(!Terminated) Synchronize(ReadData); } //--------------------------------------------------------------------------- void __fastcall TRead232::ReadData() { Form1->Caption = "Updated in a thread";
String Temp; char inbuff[1024]; DWORD nBytesRead,dwEvent,dwError; COMSTAT cs; if(hComm == INVALID_HANDLE_VALUE) { MessageBox(0,"串口失败!!","Set Error",MB_OK);
return; } ClearCommError(hComm,&dwError,&cs); Form1->Edit1->Text = cs.cbInQue; if(cs.cbInQue > sizeof(inbuff)) { PurgeComm(hComm,PURGE_RXCLEAR); return; } ReadFile(hComm,inbuff,cs.cbInQue,&nBytesRead,NULL); inbuff[cs.cbInQue]='\0'; Form1->Memo1->Text =Form1->Memo1->Text+inbuff; } 发送是定时器TIMER1触发,定时发送的。 void __fastcall TForm1::Timer1Timer(TObject *Sender) { char SendData[20]; byte ch; int i; unsigned long lrc,BS; if (hComm==0) return; SendData[0] = 0x41; SendData[1] = 0x03; SendData[2] = 0x00; SendData[3] = 0x01; SendData[4] = 0x00; SendData[5] = 0x04; SendData[6] = 0x1b; SendData[7] = 0x09; SendData[8] = '\0'; // BS = 8; // StrLen(SendData); for(i=0;i<=7;i++) { ch = SendData; WriteFile(hComm,&ch,1,&lrc,NULL); } } 原来想一起发的,发现不成功,还是一个一个发就没有问题了。 |