代码改变世界

delphi之动态库调用和串口通讯

2016-10-22 16:17  绿贝  阅读(640)  评论(0编辑  收藏  举报

串口通讯:

Spcomm 控件属性:

 

CommName  :表示COM1,COM2等串口的名字;

 

BaudRate:设定波特率9600,4800等

 

StartComm

StopComm

 

 

 函数WriteCommData(pDataToWrite: PChar;dwSizeofDataToWrite:Word ): boolean

用于发送一个字符串到写线程,发送成功返回true,发送失败返回false, 执行此函数将立即得到返回值,发送操作随后行。    

函数有两个参数,其中 pdatatowrite是要发送的字符串,dwsizeofdatatowrite 是发送的长度。

 

事件OnReceiveData : procedure (Sender: TObject;Buffer: Pointer;BufferLength: Word) of object   

当输入缓存有数据时将触发该事件,在这里可以对从串口收到的数据进行处理。Buffer中是收到的数据,bufferlength是收到的数据长度

 

 动态库调用

 

 unit CMUPS_HB600DLL;

interface
type
    IcumpsHB600 = record

     end;

    function ZT_UPS_OpenDevice(pstrCom :pansichar; var m_nUPSHandle:pinteger;nFage:Integer=0):Integer;stdcall;  //打开设备
    function ZT_UPS_CloseDevice(nHandle:pInteger):Integer;stdcall;//关闭设备
    function ZT_UPS_GetStatus (nHandle:pInteger):Integer;stdcall; // 取得设备状态



implementation

  function ZT_UPS_OpenDevice; external 'ZT_UPS.dll';
  function ZT_UPS_CloseDevice; external 'ZT_UPS.dll';
  function ZT_UPS_GetStatus; external 'ZT_UPS.dll';



end.

 

上面是个例子。需要注意: 

一、调用参数用stdcall 

二、用external语句指定被调用的DLL文件的路径和名称 

三、注意参数的传递。

pansichar类型对应的是c语言的char*
pinteger类型对应的是c语言的int*
integer类型对应的是c语言的int
var m_nUPSHandle:pinteger 对应的是c语言的int* ,这里是引用传递