日期:2014-05-16  浏览次数:20503 次

javascript 操作MSCOMM32串口通信
javascript 直接操作MSCOMM32发数据只能发0到127,128到255不能发。所以要自己写一个activeX控件来进行数据转换

VB6

activeX 源代码

'把A1 01 0D 十六进制转成字符发给javascirpt
Public Function receivedata(ssr)
Dim leng
Dim bb() As Byte
bb = ssr
'leng = Len(bb)
    For i = LBound(bb) To UBound(bb)
        tmpHex = Hex(bb(i))
        RtnStr = RtnStr & IIf(bb(i) < &H10, "0" & tmpHex, tmpHex) & " "
    Next
receivedata = RtnStr
End Function


'把A1 01 0D 转成字节数组发给mscomm
Public Function senddata(ss)
Dim arr() As Byte
Dim s, i, leng
leng = Len(ss) \ 3
s = Split(ss, " ")
ReDim arr(leng) As Byte
For i = 0 To leng
arr(i) = Val("&H" & s(i))
Next i
senddata = arr
End Function


<!--

html

-->

<html>   
<head>   
<title>JavaScript MSCOMM32.OCX </title> 

<SCRIPT ID=clientEventHandlersJS LANGUAGE=javascript>   
//重写 mscomm 控件的唯一事件处理代码   
function comm_OnComm()   
{   
var len=0;   
if(comm.CommEvent==1)//如果是发送事件   
{   
    window.alert("发送成功");//这句正常,说明发送成功了   
}   
else if(comm.CommEvent==2)//如果是接收事件   
{
var leng=comm.InBufferCount;
var instr=cnv.receivedata(comm.Input);
document.form1.txtReceive.value=document.form1.txtReceive.value + instr;


}   
</SCRIPT> 

<SCRIPT LANGUAGE=javascript FOR=comm EVENT=OnComm>    
// comm控件每遇到 OnComm 事件就调用 comm_OnComm()函数   
comm_OnComm()   
</SCRIPT> 


<script language="JavaScript" type="text/JavaScript">   
//打开端口并发送命令程序   
function OpenPort()   
{  

if(comm.PortOpen==false)   
{
try{
comm.PortOpen=true;
var sendstr=document.form1.txtsend.value;
comm.Output=cnv.senddata(sendstr);//发送命令
}catch(e){
alert(e);
}
window.alert("成功发出命令!");
}   
else   
{   
var sendstr=document.form1.txtsend.value;
comm.Output=cnv.senddata(sendstr);//发送命令    
}   
}

  
</script>  
</head>
<OBJECT CLASSID="clsid:5220cb21-c88d-11cf-b347-00aa00a28331">
<PARAM NAME="LPKPath" VALUE="LPKfilename.LPK">
</OBJECT>


<OBJECT ID="cnv"
CLASSID="CLSID:6AE2FA6C-7428-4BBC-A80E-8F3F5AF8517A"
CODEBASE="mycnv.CAB#version=1,0,0,0">
<param name="_ExtentX" value="8467">
<param name="_ExtentY" value="6350">
</OBJECT>
<object CLASSID="clsid:648A5600-2C6E-101B-82B6-000000000014" id="comm" codebase="MSCOMM32.OCX" type="application/x-oleobject" style="LEFT: 54px; TOP: 14px">
<param NAME="CommPort" VALUE="8">
<param NAME="DTREnable" VALUE="1">
<param NAME="Handshaking" VALUE="0">
<param NAME="InBufferSize" VALUE="1024">
<param NAME="InputLen" VALUE="0">
<param NAME="NullDiscard" VALUE="0">
<param NAME="OutBufferSize" VALUE="512">
<param NAME="ParityReplace" VALUE="?">
<param NAME="RThreshold" VALUE="1">
<param NAME="RTSEnable" VALUE="1">
<param NAME="SThreshold" VALUE="2">
<param NAME