modbus协议_PC实现.doc_第1页
modbus协议_PC实现.doc_第2页
modbus协议_PC实现.doc_第3页
全文预览已结束

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

modbus协议PC端的实现我使用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 inbuff1024;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); inbuffcs.cbInQue=0; Form1-Memo1-Text =Form1-Memo1-Text+inbuff;发送是定时器TIMER1触发,定时发送的。void _fastcall TForm1:Timer1Timer(TObject *Sender)char SendData20;byte ch;int i;unsigned long lrc,BS;if (hComm=0) return;SendData0 = 0x41;SendData1 = 0x03;SendData2 = 0x00;SendData3 = 0x01;SendData4 = 0x00;SendData5 = 0x04;SendData6 = 0x1b;SendData7 = 0x09;SendData8 = 0;/ BS = 8; / StrLen(S

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论